Delete demos directory

This commit is contained in:
Travis Plunk 2024-09-06 11:10:17 -07:00 committed by GitHub
parent 0b33361d18
commit b42d188fdd
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
29 changed files with 0 additions and 1555 deletions

View File

@ -1,236 +0,0 @@
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
#Region utility functions
$global:sudocmd = "sudo"
Function GetApacheCmd{
if (Test-Path "/usr/sbin/apache2ctl"){
$cmd = "/usr/sbin/apache2ctl"
}elseif(Test-Path "/usr/sbin/httpd"){
$cmd = "/usr/sbin/httpd"
}else{
Write-Error "Unable to find httpd or apache2ctl program. Unable to continue"
exit -1
}
$cmd
}
Function GetApacheVHostDir{
if (Test-Path "/etc/httpd/conf.d"){
Return "/etc/httpd/conf.d/"
}
if (Test-Path "/etc/apache2/sites-enabled"){
Return "/etc/apache2/sites-enabled"
}
}
Function CleanInputString([string]$inputStr){
$outputStr = $inputStr.Trim().Replace('`n','').Replace('\n','')
$outputStr
}
#EndRegion utility functions
#Region Class specifications
Class ApacheModule{
[string]$ModuleName
ApacheModule([string]$aModule){
$this.ModuleName = $aModule
}
}
Class ApacheVirtualHost{
[string]$ServerName
[string]$DocumentRoot
[string]$VirtualHostIPAddress = "*"
[string[]]$ServerAliases
[int]$VirtualHostPort = "80"
[string]$ServerAdmin
[string]$CustomLogPath
[string]$ErrorLogPath
[string]$ConfigurationFile
#region class constructors
ApacheVirtualHost([string]$ServerName, [string]$ConfFile, [string]$VirtualHostIPAddress,[int]$VirtualHostPort){
$this.ServerName = $ServerName
$this.ConfigurationFile = $ConfFile
$this.VirtualHostIPAddress = $VirtualHostIPAddress
$this.VirtualHostPort = $VirtualHostPort
}
#Full specification
ApacheVirtualHost([string]$ServerName, [string]$DocumentRoot, [string[]]$ServerAliases, [string]$ServerAdmin, [string]$CustomLogPath, [string]$ErrorLogPath, [string]$VirtualHostIPAddress, [int]$VirtualHostPort, [string]$ConfigurationFile){
$this.ServerName = $ServerName
$this.DocumentRoot = $DocumentRoot
$this.ServerAliases = $ServerAliases
$this.ServerAdmin = $ServerAdmin
$this.CustomLogPath = $CustomLogPath
$this.ErrorLogPath = $ErrorLogPath
$this.VirtualHostIPAddress = $VirtualHostIPAddress
$this.VirtualHostPort = $VirtualHostPort
$this.ConfigurationFile = $ConfigurationFile
}
#Default Port and IP
#endregion
#region class methods
Save($ConfigurationFile){
if (!(Test-Path $this.DocumentRoot)){ New-Item -Type Directory $this.DocumentRoot }
$VHostsDirectory = GetApacheVHostDir
if (!(Test-Path $VHostsDirectory)){
Write-Error "Specified virtual hosts directory does not exist: $VHostsDirectory"
exit 1
}
$VHostIPAddress = $this.VirtualHostIPAddress
[string]$VhostPort = $this.VirtualHostPort
$VHostDef = "<VirtualHost " + "$VHostIPAddress" + ":" + $VHostPort + " >`n"
$vHostDef += "DocumentRoot " + $this.DocumentRoot + "`n"
ForEach ($Alias in $this.ServerAliases){
if ($Alias.trim() -ne ""){
$vHostDef += "ServerAlias " + $Alias + "`n"
}
}
$vHostDef += "ServerName " + $this.ServerName +"`n"
if ($this.ServerAdmin.Length -gt 1){$vHostDef += "ServerAdmin " + $this.ServerAdmin +"`n"}
if ($this.CustomLogPath -like "*/*"){$vHostDef += "CustomLog " + $this.CustomLogPath +"`n"}
if ($this.ErrorLogPath -like "*/*"){$vHostDef += "ErrorLog " + $this.ErrorLogpath +"`n"}
$vHostDef += "</VirtualHost>"
$filName = $ConfigurationFile
$VhostDef | Out-File "/tmp/${filName}" -Force -Encoding:ascii
& $global:sudocmd "mv" "/tmp/${filName}" "${VhostsDirectory}/${filName}"
Write-Information "Restarting Apache HTTP Server"
Restart-ApacheHTTPServer
}
#endregion
}
#EndRegion Class Specifications
Function New-ApacheVHost {
[CmdletBinding()]
param(
[parameter (Mandatory = $true)][string]$ServerName,
[parameter (Mandatory = $true)][string]$DocumentRoot,
[string]$VirtualHostIPAddress,
[string[]]$ServerAliases,
[int]$VirtualHostPort,
[string]$ServerAdmin,
[string]$CustomLogPath,
[string]$ErrorLogPath
)
$NewConfFile = $VHostsDirectory + "/" + $ServerName + ".conf"
if(!($VirtualHostIPAddress)){$VirtualHostIPAddress = "*"}
if(!($VirtualHostPort)){$VirtualHostPort = "80"}
$newVHost = [ApacheVirtualHost]::new("$ServerName","$DocumentRoot","$ServerAliases","$ServerAdmin","$CustomLogPath","$ErrorLogPath","$VirtualHostIPAddress",$VirtualHostPort,"$NewConfFile")
$newVHost.Save("$ServerName.conf")
}
Function GetVHostProps([string]$ConfFile,[string]$ServerName,[string]$Listener){
$confContents = Get-Content $ConfFile
[boolean]$Match = $false
$DocumentRoot = ""
$CustomLogPath = ""
$ErrorLogPath = ""
$ServerAdmin = ""
ForEach ($confline in $confContents){
if ($confLine -like "<VirtualHost*${Listener}*"){
$Match = $true
}
if($Match){
Switch -wildcard ($confline) {
"*DocumentRoot*"{$DocumentRoot = $confline.split()[1].trim()}
"*CustomLog*"{$CustomLogPath = $confline.split()[1].trim()}
"*ErrorLog*"{$ErrorLogPath = $confline.split()[1].trim()}
"*ServerAdmin*"{$ServerAdmin = $confline.split()[1].trim()}
#Todo: Server aliases
}
if($confline -like "*</VirtualHost>*"){
$Match = $false
}
}
}
@{"DocumentRoot" = "$DocumentRoot"; "CustomLogPath" = "$CustomLogPath"; "ErrorLogPath" = "$ErrorLogPath"; "ServerAdmin" = $ServerAdmin}
}
Function Get-ApacheVHost{
$cmd = GetApacheCmd
$Vhosts = @()
$res = & $global:sudocmd $cmd -t -D DUMP_VHOSTS
ForEach ($line in $res){
$ServerName = $null
if ($line -like "*:*.conf*"){
$RMatch = $line -match "(?<Listen>.*:[0-9]*)(?<ServerName>.*)\((?<ConfFile>.*)\)"
$ListenAddress = $Matches.Listen.trim()
$ServerName = $Matches.ServerName.trim()
$ConfFile = $Matches.ConfFile.trim().split(":")[0].Replace('(','')
}else{
if ($line.trim().split()[0] -like "*:*"){
$ListenAddress = $line.trim().split()[0]
}elseif($line -like "*.conf*"){
if ($line -like "*default*"){
$ServerName = "_Default"
$ConfFile = $line.trim().split()[3].split(":")[0].Replace('(','')
}elseif($line -like "*namevhost*"){
$ServerName = $line.trim().split()[3]
$ConfFile = $line.trim().split()[4].split(":")[0].Replace('(','')
}
}
}
if ($null -ne $ServerName){
$vHost = [ApacheVirtualHost]::New($ServerName, $ConfFile, $ListenAddress.Split(":")[0],$ListenAddress.Split(":")[1])
$ExtProps = GetVHostProps $ConfFile $ServerName $ListenAddress
$vHost.DocumentRoot = $ExtProps.DocumentRoot
#Custom log requires additional handling. NYI
#$vHost.CustomLogPath = $ExtProps.CustomLogPath
$vHost.ErrorLogPath = $ExtProps.ErrorLogPath
$vHost.ServerAdmin = $ExtProps.ServerAdmin
$Vhosts += $vHost
}
}
Return $Vhosts
}
Function Restart-ApacheHTTPServer{
[CmdletBinding()]
Param(
[switch]$Graceful
)
if ($null -eq $Graceful){$Graceful = $false}
$cmd = GetApacheCmd
if ($Graceful){
& $global:sudocmd $cmd -k graceful
}else{
& $global:sudocmd $cmd -k restart
}
}
Function Get-ApacheModule{
$cmd = GetApacheCmd
$ApacheModules = @()
$Results = & $global:sudocmd $cmd -M |grep -v Loaded
Foreach ($mod in $Results){
$modInst = [ApacheModule]::new($mod.trim())
$ApacheModules += ($modInst)
}
$ApacheModules
}

View File

@ -1,33 +0,0 @@
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
Import-Module $PSScriptRoot/Apache/Apache.psm1
#list Apache Modules
Write-Host -Foreground Blue "Get installed Apache Modules like *proxy* and Sort by name"
Get-ApacheModule | Where-Object {$_.ModuleName -like "*proxy*"} | Sort-Object ModuleName | Out-Host
#Graceful restart of Apache
Write-Host -Foreground Blue "Restart Apache Server gracefully"
Restart-ApacheHTTPServer -Graceful | Out-Host
#Enumerate current virtual hosts (web sites)
Write-Host -Foreground Blue "Enumerate configured Apache Virtual Hosts"
Get-ApacheVHost |Out-Host
#Add a new virtual host
Write-Host -Foreground Yellow "Create a new Apache Virtual Host"
New-ApacheVHost -ServerName "mytestserver" -DocumentRoot /var/www/html/mytestserver -VirtualHostIPAddress * -VirtualHostPort 8090 | Out-Host
#Enumerate new set of virtual hosts
Write-Host -Foreground Blue "Enumerate Apache Virtual Hosts Again"
Get-ApacheVHost |Out-Host
#Cleanup
Write-Host -Foreground Blue "Remove demo virtual host"
if (Test-Path "/etc/httpd/conf.d"){
& sudo rm "/etc/httpd/conf.d/mytestserver.conf"
}
if (Test-Path "/etc/apache2/sites-enabled"){
& sudo rm "/etc/apache2/sites-enabled/mytestserver.conf"
}

View File

@ -1,18 +0,0 @@
## Apache Management Demo
This demo shows management of Apache HTTP Server with PowerShell cmdlets implemented in a script module.
- **Get-ApacheVHost**: Enumerate configured Apache Virtual Host (website) instances as objects.
- **Get-ApacheModule**: Enumerate loaded Apache modules
- **Restart-ApacheHTTPserver**: Restart the Apache web server
- **New-ApacheVHost**: Create a new Apache Virtual Host (website) based on supplied parameters
## Prerequisites ##
- Install PowerShell
- Install Apache packages
- `sudo apt-get install apache2`
- `sudo yum install httpd`
Note: Management of Apache requires privileges. The user must have authorization to elevate with sudo. You will be prompted for a sudo password when running the demo.

View File

@ -1,70 +0,0 @@
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
### The techniques used in this demo are documented at
### https://azure.microsoft.com/documentation/articles/powershell-azure-resource-manager/
### Import AzureRM.Profile.NetCore.Preview and AzureRM.Resources.NetCore.Preview modules.
### AzureRM.NetCore.Preview is a wrapper module that pulls in these modules
###
### Because of issue https://github.com/PowerShell/PowerShell/issues/1618,
### currently you will not be able to use "Install-Module AzureRM.NetCore.Preview" from
### PowerShellGallery. You can use the following workaround until the issue is fixed:
###
### Install-Package -Name AzureRM.NetCore.Preview -Source https://www.powershellgallery.com/api/v2 -ProviderName NuGet -ExcludeVersion -Destination <Folder you want this to be installed>
###
### Ensure $env:PSModulePath is updated with the location you used to install.
Import-Module AzureRM.NetCore.Preview
### Supply your Azure Credentials
Login-AzureRmAccount
### Specify a name for Azure Resource Group
$resourceGroupName = "PSAzDemo" + (New-Guid | ForEach-Object guid) -replace "-",""
$resourceGroupName
### Create a new Azure Resource Group
New-AzureRmResourceGroup -Name $resourceGroupName -Location "West US"
### Deploy an Ubuntu 14.04 VM using Resource Manager cmdlets
### Template is available at
### http://armviz.io/#/?load=https:%2F%2Fraw.githubusercontent.com%2FAzure%2Fazure-quickstart-templates%2Fmaster%2F101-vm-simple-linux%2Fazuredeploy.json
$dnsLabelPrefix = $resourceGroupName | ForEach-Object tolower
$dnsLabelPrefix
#[SuppressMessage("Microsoft.Security", "CS002:SecretInNextLine", Justification="Demo/doc secret.")]
$password = ConvertTo-SecureString -String "PowerShellRocks!" -AsPlainText -Force
New-AzureRmResourceGroupDeployment -ResourceGroupName $resourceGroupName -TemplateFile ./Compute-Linux.json -adminUserName psuser -adminPassword $password -dnsLabelPrefix $dnsLabelPrefix
### Monitor the status of the deployment
Get-AzureRmResourceGroupDeployment -ResourceGroupName $resourceGroupName
### Discover the resources we created by the previous deployment
Find-AzureRmResource -ResourceGroupName $resourceGroupName | Select-Object Name,ResourceType,Location
### Get the state of the VM we created
### Notice: The VM is in running state
Get-AzureRmResource -ResourceName MyUbuntuVM -ResourceType Microsoft.Compute/virtualMachines -ResourceGroupName $resourceGroupName -ODataQuery '$expand=instanceView' | ForEach-Object properties | ForEach-Object instanceview | ForEach-Object statuses
### Discover the operations we can perform on the compute resource
### Notice: Operations like "Power Off Virtual Machine", "Start Virtual Machine", "Create Snapshot", "Delete Snapshot", "Delete Virtual Machine"
Get-AzureRmProviderOperation -OperationSearchString Microsoft.Compute/* | Select-Object OperationName,Operation
### Power Off the Virtual Machine we created
Invoke-AzureRmResourceAction -ResourceGroupName $resourceGroupName -ResourceType Microsoft.Compute/virtualMachines -ResourceName MyUbuntuVM -Action poweroff
### Check the VM state again. It should be stopped now.
Get-AzureRmResource -ResourceName MyUbuntuVM -ResourceType Microsoft.Compute/virtualMachines -ResourceGroupName $resourceGroupName -ODataQuery '$expand=instanceView' | ForEach-Object properties | ForEach-Object instanceview | ForEach-Object statuses
### As you know, you may still be incurring charges even if the VM is in stopped state
### Deallocate the resource to avoid this charge
Invoke-AzureRmResourceAction -ResourceGroupName $resourceGroupName -ResourceType Microsoft.Compute/virtualMachines -ResourceName MyUbuntuVM -Action deallocate
### The following command removes the Virtual Machine
Remove-AzureRmResource -ResourceName MyUbuntuVM -ResourceType Microsoft.Compute/virtualMachines -ResourceGroupName $resourceGroupName
### Look at the resources that still exists
Find-AzureRmResource -ResourceGroupName $resourceGroupName | Select-Object Name,ResourceType,Location
### Remove the resource group and its resources
Remove-AzureRmResourceGroup -Name $resourceGroupName

View File

@ -1,200 +0,0 @@
{
"$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
"contentVersion": "1.0.0.0",
"parameters": {
"adminUsername": {
"type": "string",
"metadata": {
"description": "User name for the Virtual Machine."
}
},
"adminPassword": {
"type": "securestring",
"metadata": {
"description": "Password for the Virtual Machine."
}
},
"dnsLabelPrefix": {
"type": "string",
"metadata": {
"description": "Unique DNS Name for the Public IP used to access the Virtual Machine."
}
},
"ubuntuOSVersion": {
"type": "string",
"defaultValue": "14.04.2-LTS",
"allowedValues": [
"12.04.5-LTS",
"14.04.2-LTS",
"15.10",
"16.04.0-LTS"
],
"metadata": {
"description": "The Ubuntu version for the VM. This will pick a fully patched image of this given Ubuntu version. Allowed values: 12.04.5-LTS, 14.04.2-LTS, 15.10, 16.04.0-LTS."
}
}
},
"variables": {
"storageAccountName": "[concat(uniquestring(resourceGroup().id), 'salinuxvm')]",
"dataDisk1VhdName": "datadisk1",
"imagePublisher": "Canonical",
"imageOffer": "UbuntuServer",
"OSDiskName": "osdiskforlinuxsimple",
"nicName": "myVMNic",
"addressPrefix": "10.0.0.0/16",
"subnetName": "Subnet",
"subnetPrefix": "10.0.0.0/24",
"storageAccountType": "Standard_LRS",
"publicIPAddressName": "myPublicIP",
"publicIPAddressType": "Dynamic",
"vmStorageAccountContainerName": "vhds",
"vmName": "MyUbuntuVM",
"vmSize": "Standard_D1",
"virtualNetworkName": "MyVNET",
"vnetID": "[resourceId('Microsoft.Network/virtualNetworks',variables('virtualNetworkName'))]",
"subnetRef": "[concat(variables('vnetID'),'/subnets/',variables('subnetName'))]",
"apiVersion": "2015-06-15"
},
"resources": [
{
"type": "Microsoft.Storage/storageAccounts",
"name": "[variables('storageAccountName')]",
"apiVersion": "2016-01-01",
"location": "[resourceGroup().location]",
"sku": {
"name": "[variables('storageAccountType')]"
},
"kind": "Storage",
"properties": {}
},
{
"apiVersion": "[variables('apiVersion')]",
"type": "Microsoft.Network/publicIPAddresses",
"name": "[variables('publicIPAddressName')]",
"location": "[resourceGroup().location]",
"properties": {
"publicIPAllocationMethod": "[variables('publicIPAddressType')]",
"dnsSettings": {
"domainNameLabel": "[parameters('dnsLabelPrefix')]"
}
}
},
{
"apiVersion": "[variables('apiVersion')]",
"type": "Microsoft.Network/virtualNetworks",
"name": "[variables('virtualNetworkName')]",
"location": "[resourceGroup().location]",
"properties": {
"addressSpace": {
"addressPrefixes": [
"[variables('addressPrefix')]"
]
},
"subnets": [
{
"name": "[variables('subnetName')]",
"properties": {
"addressPrefix": "[variables('subnetPrefix')]"
}
}
]
}
},
{
"apiVersion": "[variables('apiVersion')]",
"type": "Microsoft.Network/networkInterfaces",
"name": "[variables('nicName')]",
"location": "[resourceGroup().location]",
"dependsOn": [
"[concat('Microsoft.Network/publicIPAddresses/', variables('publicIPAddressName'))]",
"[concat('Microsoft.Network/virtualNetworks/', variables('virtualNetworkName'))]"
],
"properties": {
"ipConfigurations": [
{
"name": "ipconfig1",
"properties": {
"privateIPAllocationMethod": "Dynamic",
"publicIPAddress": {
"id": "[resourceId('Microsoft.Network/publicIPAddresses',variables('publicIPAddressName'))]"
},
"subnet": {
"id": "[variables('subnetRef')]"
}
}
}
]
}
},
{
"apiVersion": "[variables('apiVersion')]",
"type": "Microsoft.Compute/virtualMachines",
"name": "[variables('vmName')]",
"location": "[resourceGroup().location]",
"dependsOn": [
"[concat('Microsoft.Storage/storageAccounts/', variables('storageAccountName'))]",
"[concat('Microsoft.Network/networkInterfaces/', variables('nicName'))]"
],
"properties": {
"hardwareProfile": {
"vmSize": "[variables('vmSize')]"
},
"osProfile": {
"computerName": "[variables('vmName')]",
"adminUsername": "[parameters('adminUsername')]",
"adminPassword": "[parameters('adminPassword')]"
},
"storageProfile": {
"imageReference": {
"publisher": "[variables('imagePublisher')]",
"offer": "[variables('imageOffer')]",
"sku": "[parameters('ubuntuOSVersion')]",
"version": "latest"
},
"osDisk": {
"name": "osdisk",
"vhd": {
"uri": "[concat(reference(concat('Microsoft.Storage/storageAccounts/', variables('storageAccountName')), variables('apiVersion')).primaryEndpoints.blob, variables('vmStorageAccountContainerName'),'/',variables('OSDiskName'),'.vhd')]"
},
"caching": "ReadWrite",
"createOption": "FromImage"
},
"dataDisks": [
{
"name": "datadisk1",
"diskSizeGB": "100",
"lun": 0,
"vhd": {
"uri": "[concat(reference(concat('Microsoft.Storage/storageAccounts/', variables('storageAccountName')), variables('apiVersion')).primaryEndpoints.blob, variables('vmStorageAccountContainerName'),'/',variables('dataDisk1VhdName'),'.vhd')]"
},
"createOption": "Empty"
}
]
},
"networkProfile": {
"networkInterfaces": [
{
"id": "[resourceId('Microsoft.Network/networkInterfaces',variables('nicName'))]"
}
]
},
"diagnosticsProfile": {
"bootDiagnostics": {
"enabled": "true",
"storageUri": "[concat(reference(concat('Microsoft.Storage/storageAccounts/', variables('storageAccountName')), variables('apiVersion')).primaryEndpoints.blob)]"
}
}
}
}
],
"outputs": {
"hostname": {
"type": "string",
"value": "[concat(parameters('dnsLabelPrefix'), '.', resourceGroup().location, '.cloudapp.azure.com')]"
},
"sshCommand": {
"type": "string",
"value": "[concat('ssh ', parameters('adminUsername'), '@', parameters('dnsLabelPrefix'), '.', resourceGroup().location, '.cloudapp.azure.com')]"
}
}
}

View File

@ -1,11 +0,0 @@
## Demo: Managing Azure using PowerShell
This demo (Azure-Demo.ps1) shows management of Azure Compute resource using Azure Resource Management (ARM) cmdlets.
## Prerequisites ##
- Install the latest PowerShell Core.
- Install AzureRM.NetCore.Preview, AzureRM.Profile.NetCore.Preview and AzureRM.Resources.NetCore.Preview modules to a local directory.
- The instructions for downloading these modules are in Azure-Demo.ps1 file.
- You have to use the command "Install-Package -Name AzureRM.NetCore.Preview -Source https://www.powershellgallery.com/api/v2 -ProviderName NuGet -ExcludeVersion -Destination <Local Directory>"

View File

@ -1,124 +0,0 @@
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
#Get Distro type and set distro-specific variables
$OSname = Get-Content "/etc/os-release" |Select-String -Pattern "^Name="
$OSName = $OSName.tostring().split("=")[1].Replace('"','')
if ($OSName -like "Ubuntu*"){
$distro = "Ubuntu"
$ApachePackages = @("apache2","php5","libapache2-mod-php5")
$ServiceName = "apache2"
$VHostDir = "/etc/apache2/sites-enabled"
$PackageManager = "apt"
}elseif (($OSName -like "CentOS*") -or ($OSName -like "Red Hat*") -or ($OSname -like "Oracle*")){
$distro = "Fedora"
$ApachePackages = @("httpd","mod_ssl","php","php-mysql")
$ServiceName = "httpd"
$VHostDir = "/etc/httpd/conf.d"
$PackageManager = "yum"
}else{
Write-Error "Unknown Linux operating system. Cannot continue."
}
#Get Service Controller
if ((Test-Path "/bin/systemctl") -or (Test-Path "/usr/bin/systemctl")){
$ServiceCtl = "SystemD"
}else{
$ServiceCtl = "init"
}
#Get FQDN
$hostname = & hostname --fqdn
Write-Host -ForegroundColor Blue "Compile a DSC MOF for the Apache Server configuration"
Configuration ApacheServer{
Node localhost{
ForEach ($Package in $ApachePackages){
nxPackage $Package{
Ensure = "Present"
Name = $Package
PackageManager = $PackageManager
}
}
nxFile vHostDirectory{
DestinationPath = $VhostDir
Type = "Directory"
Ensure = "Present"
Owner = "root"
Mode = "744"
}
#Ensure default content does not exist
nxFile DefVHost{
DestinationPath = "${VhostDir}/000-default.conf"
Ensure = "Absent"
}
nxFile Welcome.conf{
DestinationPath = "${VhostDir}/welcome.conf"
Ensure = "Absent"
}
nxFile UserDir.conf{
DestinationPath = "${VhostDir}/userdir.conf"
Ensure = "Absent"
}
#Ensure website is defined
nxFile DefaultSiteDir{
DestinationPath = "/var/www/html/defaultsite"
Type = "Directory"
Owner = "root"
Mode = "744"
Ensure = "Present"
}
nxFile DefaultSite.conf{
Destinationpath = "${VhostDir}/defaultsite.conf"
Owner = "root"
Mode = "744"
Ensure = "Present"
Contents = @"
<VirtualHost *:80>
DocumentRoot /var/www/html/defaultsite
ServerName $hostname
</VirtualHost>
"@
DependsOn = "[nxFile]DefaultSiteDir"
}
nxFile TestPhp{
DestinationPath = "/var/www/html/defaultsite/test.php"
Ensure = "Present"
Owner = "root"
Mode = "744"
Contents = @'
<?php phpinfo(); ?>
'@
}
#Configure Apache Service
nxService ApacheService{
Name = "$ServiceName"
Enabled = $true
State = "running"
Controller = $ServiceCtl
DependsOn = "[nxFile]DefaultSite.conf"
}
}
}
ApacheServer -OutputPath "/tmp"
Pause
Write-Host -ForegroundColor Blue "Apply the configuration locally"
& sudo /opt/microsoft/dsc/Scripts/StartDscConfiguration.py -configurationmof /tmp/localhost.mof | Out-Host
Pause
Write-Host -ForegroundColor Blue "Get the current configuration"
& sudo /opt/microsoft/dsc/Scripts/GetDscConfiguration.py | Out-Host

View File

@ -1,15 +0,0 @@
# DSC MOF Compilation Demo
[PowerShell Desired State Configuration](https://learn.microsoft.com/powershell/dsc/overview) is a declarative configuration platform for Windows and Linux.
DSC configurations can be authored in PowerShell and compiled into the resultant MOF document.
This demo shows use of PowerShell to author a DSC configuration to set the configuration of an Apache web server. PowerShell scripting is used to assess distribution and version-specific properties,
such as the service controller and repo manager tools, for use in the configuration.
## Prerequisites
- PowerShell >= 6.0.0-alpha.8 [https://github.com/PowerShell/PowerShell/releases](https://github.com/PowerShell/PowerShell/releases)
- OMI: >= 1.1.0 [https://www.github.com/microsoft/omi/releases](https://www.github.com/microsoft/omi/releases)
- Desired State Configuration for Linux >= 1.1.1-278 [https://github.com/Microsoft/PowerShell-DSC-for-Linux/releases](https://github.com/Microsoft/PowerShell-DSC-for-Linux/releases)
> Note: applying the DSC configuration requires privileges. The user must have sudo authorization capabilities. You will be prompted for a sudo password when running the demo.

View File

@ -1,32 +0,0 @@
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
# This is a short example of the Docker-PowerShell module. The same cmdlets may be used to manage both local & remote machines, including both Windows & Linux hosts
# The only difference between them is the example container image is pulled & run.
# Import the Docker module
# It's available at https://github.com/Microsoft/Docker-PowerShell
Import-Module Docker
# Pull the 'hello-world' image from Docker Hub
Pull-ContainerImage hello-world # Linux
# Pull-ContainerImage patricklang/hello-world # Windows
# Now run it
Run-ContainerImage hello-world # Linux
# Run-ContainerImage patricklang/hello-world # Windows
# Make some room on the screen
cls
# List all containers that have exited
Get-Container | Where-Object State -EQ "exited"
# That found the right one, so go ahead and remove it
Get-Container | Where-Object State -EQ "exited" | Remove-Container
# Now remove the container image
Remove-ContainerImage hello-world
# And list the container images left on the container host
Get-ContainerImage

View File

@ -1,4 +0,0 @@
This folder contains demos primarily targeted for Linux systems.
Each demo showcases how to use PowerShell to be more productive by
leveraging objects and how it can integrate with existing Linux
scripts and/or commands.

View File

@ -1,21 +0,0 @@
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
Function Get-SystemDJournal {
[CmdletBinding()]
param (
[Alias("args")][string]$journalctlParameters
)
$sudocmd = "sudo"
$cmd = "journalctl"
$Result = & $sudocmd $cmd $journalctlParameters -o json --no-pager
Try
{
$JSONResult = $Result|ConvertFrom-Json
$JSONResult
}
Catch
{
$Result
}
}

View File

@ -1,12 +0,0 @@
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
Import-Module $PSScriptRoot/SystemD/SystemD.psm1
#list recent journal events
Write-Host -Foreground Blue "Get recent SystemD journal messages"
Get-SystemDJournal -args "-xe" |Out-Host
#Drill into SystemD unit messages
Write-Host -Foreground Blue "Get recent SystemD journal messages for services and return Unit, Message"
Get-SystemDJournal -args "-xe" | Where-Object {$_._SYSTEMD_UNIT -like "*.service"} | Format-Table _SYSTEMD_UNIT, MESSAGE | Select-Object -First 10 | Out-Host

View File

@ -1,10 +0,0 @@
## SystemD: journalctl demo
This demo shows use of a PowerShell script module to wrap a native tool (journalctl) so that the output is structured for filtering and presentation control. `journalctl` is expressed as a cmdlet: Get-SystemDJournal, and the JSON output of journalctl is converted to a PowerShell object.
## Prerequisites ##
- Requires a SystemD-based operating system (Red Hat or CentOS 7, Ubuntu 16.04)
- Install PowerShell
Note: Accessing the SystemD journal requires privileges. The user must have authorization to elevate with sudo. You will be prompted for a sudo password when running the demo.

View File

@ -1,54 +0,0 @@
# Using Windows PowerShell modules with PowerShell Core
## Windows PowerShell vs PowerShell Core
Existing Windows PowerShell users are familiar with the large number of modules available, however, they are not necessarily compatible with PowerShell Core.
More information regarding compatibility is in a [blog post](https://devblogs.microsoft.com/powershell/powershell-6-0-roadmap-coreclr-backwards-compatibility-and-more/).
Windows PowerShell 5.1 is based on .Net Framework 4.6.1, while PowerShell Core is based on .Net Core 2.x.
Although both adhere to .Net Standard 2.0 and can be compatible, some modules may be using APIs or cmdlets not supported on CoreCLR or using APIs from Windows PowerShell that have been deprecated and removed from PowerShell Core (for example, PSSnapins).
## Importing a Windows PowerShell module
Since compatibility cannot be ensured, PowerShell Core, by default, does not look in the Windows PowerShell module path to find those modules.
However, advanced users can explicitly enable PowerShell Core to include the Windows PowerShell module path and attempt to import those modules.
First, install the [WindowsPSModulePath](https://www.powershellgallery.com/packages/WindowsPSModulePath) module from the PowerShellGallery:
```powershell
Install-Module WindowsPSModulePath -Scope CurrentUser
```
Then run `Add-WindowsPSModulePath` cmdlet to add the Windows PowerShell module path to your PowerShell Core module path:
```powershell
Add-WindowsPSModulePath
```
Note that this is only effective in the current PowerShell session.
If you want to persist this, you can add `Add-WindowsPSModulePath` to your profile:
```powershell
"Add-WindowsPSModulePath" >> $profile
```
Once the module path has been updated, you can list available modules:
```powershell
Get-Module -ListAvailable
```
Note that PowerShell Core is not aware which Windows PowerShell modules will work and which will not so all are listed.
We plan to improve this experience in the future.
You can now import a Windows PowerShell module or just execute a known cmdlet and allow auto-module loading to take care of importing the module:
```powershell
Get-VM
# this will automatically load the Hyper-V module
```
Most of the cmdlets based on CDXML will work just fine, as well as some C# based cmdlets that happen to be .NET Standard 2.0 compatible (for example, Hyper-V module) but the Active Directory module, for example, won't work.
## How you can help
Provide comments on Windows PowerShell modules that work or don't work in our [tracking issue](https://github.com/PowerShell/PowerShell/issues/4062).

View File

@ -1,69 +0,0 @@
<?xml version="1.0" encoding="utf-8" ?>
<Configuration>
<ViewDefinitions>
<View>
<Name>Default</Name>
<ViewSelectedBy>
<TypeName>CronJob</TypeName>
</ViewSelectedBy>
<TableControl>
<TableHeaders>
<TableColumnHeader>
<Label>Minute</Label>
<Width>10</Width>
<Alignment>Left</Alignment>
</TableColumnHeader>
<TableColumnHeader>
<Label>Hour</Label>
<Width>10</Width>
<Alignment>Left</Alignment>
</TableColumnHeader>
<TableColumnHeader>
<Label>DayOfMonth</Label>
<Width>10</Width>
<Alignment>Left</Alignment>
</TableColumnHeader>
<TableColumnHeader>
<Label>Month</Label>
<Width>10</Width>
<Alignment>Left</Alignment>
</TableColumnHeader>
<TableColumnHeader>
<Label>DayOfWeek</Label>
<Width>10</Width>
<Alignment>Left</Alignment>
</TableColumnHeader>
<TableColumnHeader>
<Label>Command</Label>
<Alignment>Left</Alignment>
</TableColumnHeader>
</TableHeaders>
<TableRowEntries>
<TableRowEntry>
<TableColumnItems>
<TableColumnItem>
<PropertyName>Minute</PropertyName>
</TableColumnItem>
<TableColumnItem>
<PropertyName>Hour</PropertyName>
</TableColumnItem>
<TableColumnItem>
<PropertyName>DayOfMonth</PropertyName>
</TableColumnItem>
<TableColumnItem>
<PropertyName>Month</PropertyName>
</TableColumnItem>
<TableColumnItem>
<PropertyName>DayOfWeek</PropertyName>
</TableColumnItem>
<TableColumnItem>
<PropertyName>Command</PropertyName>
</TableColumnItem>
</TableColumnItems>
</TableRowEntry>
</TableRowEntries>
</TableControl>
</View>
</ViewDefinitions>
</Configuration>

View File

@ -1,61 +0,0 @@
@{
# Script module or binary module file associated with this manifest.
RootModule = 'CronTab.psm1'
# Version number of this module.
ModuleVersion = '0.1.0.0'
# Supported PSEditions
CompatiblePSEditions = @('Core')
# ID used to uniquely identify this module
GUID = '508bb97f-de2e-482e-aae2-01caec0be8c7'
# Author of this module
Author = 'PowerShell'
# Company or vendor of this module
CompanyName = 'Microsoft Corporation'
# Copyright statement for this module
Copyright = 'Copyright (c) Microsoft Corporation.'
# Description of the functionality provided by this module
Description = 'Sample module for managing CronTab'
# Format files (.ps1xml) to be loaded when importing this module
FormatsToProcess = 'CronTab.ps1xml'
# Functions to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no functions to export.
FunctionsToExport = 'New-CronJob','Remove-CronJob','Get-CronJob','Get-CronTabUser'
# Private data to pass to the module specified in RootModule/ModuleToProcess. This may also contain a PSData hashtable with additional module metadata used by PowerShell.
PrivateData = @{
PSData = @{
# Tags applied to this module. These help with module discovery in online galleries.
# Tags = @()
# A URL to the license for this module.
# LicenseUri = ''
# A URL to the main website for this project.
# ProjectUri = ''
# A URL to an icon representing this module.
# IconUri = ''
# ReleaseNotes of this module
# ReleaseNotes = ''
} # End of PSData hashtable
} # End of PrivateData hashtable
# HelpInfo URI of this module
# HelpInfoURI = ''
}

View File

@ -1,264 +0,0 @@
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
using namespace System.Collections.Generic
using namespace System.Management.Automation
$crontabcmd = "/usr/bin/crontab"
class CronJob {
[string] $Minute
[string] $Hour
[string] $DayOfMonth
[string] $Month
[string] $DayOfWeek
[string] $Command
[string] ToString()
{
return "{0} {1} {2} {3} {4} {5}" -f
$this.Minute, $this.Hour, $this.DayOfMonth, $this.Month, $this.DayOfWeek, $this.Command
}
}
# Internal helper functions
function Get-CronTab ([String] $user) {
$crontab = Invoke-CronTab -user $user -arguments "-l" -noThrow
if ($crontab -is [ErrorRecord]) {
if ($crontab.Exception.Message.StartsWith("no crontab for ")) {
$crontab = @()
}
else {
throw $crontab.Exception
}
}
[string[]] $crontab
}
function ConvertTo-CronJob ([String] $crontab) {
$split = $crontab -split " ", 6
$cronjob = [CronJob]@{
Minute = $split[0];
Hour = $split[1];
DayOfMonth= $split[2];
Month =$split[3];
DayOfWeek = $split[4];
Command = $split[5]
}
$cronjob
}
function Invoke-CronTab ([String] $user, [String[]] $arguments, [Switch] $noThrow) {
If ($user -ne [String]::Empty) {
$arguments = Write-Output "-u" $UserName $arguments
}
Write-Verbose "Running: $crontabcmd $arguments"
$output = & $crontabcmd @arguments 2>&1
if ($LASTEXITCODE -ne 0 -and -not $noThrow) {
$e = New-Object System.InvalidOperationException -ArgumentList $output.Exception.Message
throw $e
} else {
$output
}
}
function Import-CronTab ([String] $user, [String[]] $crontab) {
$temp = New-TemporaryFile
[String]::Join([Environment]::NewLine,$crontab) | Set-Content $temp.FullName
Invoke-CronTab -user $user $temp.FullName
Remove-Item $temp
}
# Public functions
function Remove-CronJob {
<#
.SYNOPSIS
Removes the exactly matching cron job from the cron table
.DESCRIPTION
Removes the exactly matching cron job from the cron table
.EXAMPLE
Get-CronJob | Where-Object {%_.Command -like 'foo *'} | Remove-CronJob
.RETURNVALUE
None
.PARAMETER UserName
Optional parameter to specify a specific user's cron table
.PARAMETER Job
Cron job object returned from Get-CronJob
.PARAMETER Force
Don't prompt when removing the cron job
#>
[CmdletBinding(SupportsShouldProcess=$true,ConfirmImpact="High")]
param (
[ArgumentCompleter( { $wordToComplete = $args[2]; Get-CronTabUser | Where-Object { $_ -like "$wordToComplete*" } | Sort-Object } )]
[Alias("u")]
[Parameter(Mandatory=$false)]
[String]
$UserName,
[Alias("j")]
[Parameter(Mandatory=$true,ValueFromPipeline=$true)]
[CronJob]
$Job,
[Switch]
$Force
)
process {
[string[]] $crontab = Get-CronTab -user $UserName
$newcrontab = [List[string]]::new()
$found = $false
$JobAsString = $Job.ToString()
foreach ($line in $crontab) {
if ($JobAsString -ceq $line) {
$found = $true
} else {
$newcrontab.Add($line)
}
}
if (-not $found) {
$e = New-Object System.Exception -ArgumentList "Job not found"
throw $e
}
if ($Force -or $PSCmdlet.ShouldProcess($Job.Command,"Remove")) {
Import-CronTab -user $UserName -crontab $newcrontab
}
}
}
function New-CronJob {
<#
.SYNOPSIS
Create a new cron job
.DESCRIPTION
Create a new job in the cron table. Date and time parameters can be specified
as ranges such as 10-30, as a list: 5,6,7, or combined 1-5,10-15. An asterisk
means 'first through last' (the entire allowed range). Step values can be used
with ranges or with an asterisk. Every 2 hours can be specified as either
0-23/2 or */2.
.EXAMPLE
New-CronJob -Minute 10-30 -Hour 10-20/2 -DayOfMonth */2 -Command "/bin/bash -c 'echo hello' > ~/hello"
.RETURNVALUE
If successful, an object representing the cron job is returned
.PARAMETER UserName
Optional parameter to specify a specific user's cron table
.PARAMETER Minute
Valid values are 0 to 59. If not specified, defaults to *.
.PARAMETER Hour
Valid values are 0-23. If not specified, defaults to *.
.PARAMETER DayOfMonth
Valid values are 1-31. If not specified, defaults to *.
.PARAMETER Month
Valid values are 1-12. If not specified, defaults to *.
.PARAMETER DayOfWeek
Valid values are 0-7. 0 and 7 are both Sunday. If not specified, defaults to *.
.PARAMETER Command
Command to execute at the scheduled time and day.
#>
[CmdletBinding()]
param (
[ArgumentCompleter( { $wordToComplete = $args[2]; Get-CronTabUser | Where-Object { $_ -like "$wordToComplete*" } | Sort-Object } )]
[Alias("u")]
[Parameter(Mandatory=$false)]
[String]
$UserName,
[Alias("mi")][Parameter(Position=1)][String[]] $Minute = "*",
[Alias("h")][Parameter(Position=2)][String[]] $Hour = "*",
[Alias("dm")][Parameter(Position=3)][String[]] $DayOfMonth = "*",
[Alias("mo")][Parameter(Position=4)][String[]] $Month = "*",
[Alias("dw")][Parameter(Position=5)][String[]] $DayOfWeek = "*",
[Alias("c")][Parameter(Mandatory=$true,Position=6)][String] $Command
)
process {
# TODO: validate parameters, note that different versions of crontab support different capabilities
$line = "{0} {1} {2} {3} {4} {5}" -f [String]::Join(",",$Minute), [String]::Join(",",$Hour),
[String]::Join(",",$DayOfMonth), [String]::Join(",",$Month), [String]::Join(",",$DayOfWeek), $Command
[string[]] $crontab = Get-CronTab -user $UserName
$crontab += $line
Import-CronTab -User $UserName -crontab $crontab
ConvertTo-CronJob -crontab $line
}
}
function Get-CronJob {
<#
.SYNOPSIS
Returns the current cron jobs from the cron table
.DESCRIPTION
Returns the current cron jobs from the cron table
.EXAMPLE
Get-CronJob -UserName Steve
.RETURNVALUE
CronJob objects
.PARAMETER UserName
Optional parameter to specify a specific user's cron table
#>
[CmdletBinding()]
[OutputType([CronJob])]
param (
[Alias("u")][Parameter(Mandatory=$false)][String] $UserName
)
process {
$crontab = Get-CronTab -user $UserName
ForEach ($line in $crontab) {
if ($line.Trim().Length -gt 0)
{
ConvertTo-CronJob -crontab $line
}
}
}
}
function Get-CronTabUser {
<#
.SYNOPSIS
Returns the users allowed to use crontab
#>
[CmdletBinding()]
[OutputType([String])]
param()
$allow = '/etc/cron.allow'
if (Test-Path $allow)
{
Get-Content $allow
}
else
{
$users = Get-Content /etc/passwd | ForEach-Object { ($_ -split ':')[0] }
$deny = '/etc/cron.deny'
if (Test-Path $deny)
{
$denyUsers = Get-Content $deny
$users | Where-Object { $denyUsers -notcontains $_ }
}
else
{
$users
}
}
}

View File

@ -1,15 +0,0 @@
## CronTab demo
This demo shows examining, creating, and removing cron jobs via crontab.
Output of Get-CronJob is a strongly typed object with properties like DayOfWeek or Command.
Remove-CronJob prompts before removing the job unless you specify -Force.
Tab completion of -UserName is supported, e.g.
Get-CronJob -u <TAB>
NYI: no way to run crontab with sudo if necessary
NYI: ignoring shell variables or comments
NYI: New-CronJob -Description "..." (save in comments"
NYI: @reboot,@daily,@hourly,etc

View File

@ -1,32 +0,0 @@
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
Import-Module $PSScriptRoot/CronTab/CronTab.psd1
Write-Host -Foreground Yellow "Get the existing cron jobs"
Get-CronJob | Out-Host
Write-Host -Foreground Yellow "New cron job to clean out tmp every day at 1am"
New-CronJob -Command 'rm -rf /tmp/*; #demo' -Hour 1 | Out-Host
Write-Host -Foreground Yellow "Add some more jobs"
New-CronJob -Command 'python -c ~/scripts/backup_users; #demo' -Hour 2 -DayOfWeek 1-5 | Out-Host
New-CronJob -Command 'powershell -c "cd ~/src/PowerShell; ipmo ./build.psm1; Start-PSBuild"; #demo' -Hour 2 -DayOfWeek * | Out-Host
Write-Host -Foreground Yellow "Show in bash that the new cron job exists"
crontab -l
Write-Host -Foreground Yellow "Get jobs that run every day"
Get-CronJob | Where-Object { $_.DayOfWeek -eq '*' -or $_.DayOfWeek -eq '1-7' } | Out-Host
Write-Host -Foreground Yellow "Remove one cron job, with prompting to confirm"
Get-CronJob | Where-Object { $_.Command -match '^powershell.*' } | Remove-CronJob | Out-Host
Write-Host -Foreground Yellow "And the other job remains"
Get-CronJob | Out-Host
Write-Host -Foreground Yellow "Remove remaining demo jobs without prompting"
Get-CronJob | Where-Object { $_.Command -match '#demo'} | Remove-CronJob -Force
Write-Host -Foreground Yellow "Show in bash that cron should be clean"
crontab -l

View File

@ -1,14 +0,0 @@
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
# DSC MOF Compilation
# DSC Configuration() script that:
# Defines base configuration users, groups, settings
# Uses PS function to set package configuration (ensure=Present) for an array of packages
# Probes for the existence of a package (Apache or MySQL) and conditionally configures the workload. I.e., if Apache is installed, configure Apache settings
# Demo execution:
# Show the .ps1
# Run the .ps1 to generate a MOF
# Apply the MOF locally with Start-DSCConfiguration
# Show the newly configured state

View File

@ -1,80 +0,0 @@
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
#region find, install, update, uninstall the PowerShell scripts from an online repository.
# Value: equivalent of pypi
# List of PowerShellGet commands
Get-Command -Module PowerShellGet
# Discover PowerShell Scripts
Find-Script
Find-Script -Name Start-Demo
# Save scripts to a specified location
Save-Script Start-Demo -Repository PSGallery -Path /tmp
Get-ChildItem -Path /tmp/Start-Demo.ps1
# Install a script to the common scripts location
Find-Script -Name Start-Demo -Repository PSGallery | Install-Script
Get-InstalledScript
# Install another script to show the update functionality
Install-Script Fabrikam-Script -RequiredVersion 1.0
Get-InstalledScript
Get-InstalledScript Fabrikam-Script | Format-List *
# Update the installed scripts
Update-Script -WhatIf
Update-Script
Get-InstalledScript
# Uninstall a script file
Uninstall-Script Fabrikam-Script -Verbose
#endregion
#region Using PowerShellGet find and install modules
# Value: equivalent of pypi
# Look for all the modules we'll be demoing today
Find-Module -Tag 'PowerShellCore_Demo'
# Save module to specified location
Save-Module -Tag 'PowerShellCore_Demo' -Path /tmp
# Pipe this to Install-Module to install them
Find-Module -Tag 'PowerShellCore_Demo' | Install-Module -Verbose
Get-InstalledModule
# Update all installed modules
Update-Module
#endregion
#region Using PowerShellGet with tags
# Look for all the scripts we'll be demoing today
Find-Script -Tag 'PowerShellCore_Demo'
# Pipe this to Install-Script to install them
Find-Script -Tag 'PowerShellCore_Demo' | Install-Script -Verbose
Get-InstalledScript
#endregion
#region Working with PowerShellGet repositories
# List available PS repositories
Get-PSRepository
# Register a new private feed
Register-PSRepository -Name "myPrivateGallery" SourceLocation "https://www.myget.org/F/powershellgetdemo/api/v2" -InstallationPolicy Trusted
# Change the trust level for a repositories
Set-PSRepository -Name "myPrivateGallery" -InstallationPolicy "Untrusted"
# Remove a private feed
Unregister-PSRepository -Name "myPrivateGallery"
#endregion

View File

@ -1,5 +0,0 @@
## PowerShellGet demo
PowerShellGet is a PowerShell module with the commands for discovering, installing, updating and publishing the PowerShell artifacts like Modules, DSC Resources, Role Capabilities and Scripts.
This demo shows discovering, installing, updating, uninstalling the PowerShell scripts from an online repository.

View File

@ -1,8 +0,0 @@
# PowerShell/Python Interoperation Demo
The `demo_script.ps1` file in this directory walks through a
demonstration of basic interoperation between PowerShell and Python
including how to use JSON to exchange structured objects between
Python and PowerShell.
The other files in this directory are referenced by `demo_script.ps1`.

View File

@ -1,14 +0,0 @@
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
#
# Wrap Python script in such a way to make it easy to
# consume from PowerShell
#
# The variable $PSScriptRoot points to the directory
# from which the script was executed. This allows
# picking up the Python script from the same directory
#
& $PSScriptRoot/class1.py | ConvertFrom-Json

View File

@ -1,19 +0,0 @@
#!/usr/bin/python3
import json
# Define a class with a method that returns JSON
class returnsjson:
def __init__(self):
the_object = self
def method1(self):
return json.dumps(['foo',
{
'bar': ('baz', None, 1.0, 2),
'buz': ('foo1', 'foo2', 'foo3')
},
'alpha',
1,2,3])
c = returnsjson()
print(c.method1())

View File

@ -1,63 +0,0 @@
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
#
# Demo simple interoperation between PowerShell and Python
# Basic execution of a Python script fragment
python -c "print('Hi!')"
# Capture output in a variable
$data = python -c "print('Hi!')"
# And show the data
$data
# Use in expressions
5 + (python -c "print(2 + 3)") + 7
# Create a Python script using a PowerShell here-string, no extension
@"
#!/usr/bin/python3
print('Hi!')
"@ | Out-File -Encoding ascii hi
# Make it executable
chmod +x hi
# Run it - shows that PowerShell really is a shell
./hi
# A more complex script that outputs JSON
cat class1.py
# Run the script
./class1.py
# Capture the data as structured objects (arrays and hashtables)
$data = ./class1.py | ConvertFrom-Json
# look at the first element of the returned array
$data[0]
# Look at the second
$data[1]
# Get a specific element from the data
$data[1].buz[1]
# Finally wrap it all up so it looks like a simple PowerShell command
cat class1.ps1
# And run it, treating the output as structured data.
(./class1)[1].buz[1]
# Finally a PowerShell script with in-line Python
cat inline_python.ps1
# and run it
./inline_python
####################################
# cleanup
rm hi

View File

@ -1,19 +0,0 @@
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
#
# An example showing inline Python code in a PowerShell script
#
"Hello from PowerShell!"
# Inline Python code in a "here string" which allows for a multi-line script
python3 -c @"
print(' Hello from Python!')
print(' Python and PowerShell get along great!')
"@
# Back to PowerShell...
"Back to PowerShell."
"Bye now!"

View File

@ -1,7 +0,0 @@
## REST demo
This demo shows how to interact with the GitHub API using the Invoke-WebRequest cmdlet.
rest.ps1:
Invoke-WebRequest and ConvertFrom-Json cmdlets are used to get the issues of a repo.
The issues are processed as objects to find the most commented on issues.

View File

@ -1,45 +0,0 @@
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
#-----------------
function Get-Issue
{
param([string]$UserName,
[string]$Repo,
[ValidateRange(1,100)][int]$PerPage = 100)
$body = @{
per_page = $PerPage
}
$uri = "https://api.github.com/repos/$UserName/$Repo/issues"
while ($uri)
{
$response = Invoke-WebRequest -Uri $uri -Body $body
$response.Content | ConvertFrom-Json | Write-Output
$uri = $null
foreach ($link in $response.Headers.Link -split ',')
{
if ($link -match '\s*<(.*)>;\s+rel="next"')
{
$uri = $Matches[1]
}
}
}
}
$issues = Get-Issue -UserName lzybkr -Repo PSReadline
$issues.Count
$issues | Sort-Object -Descending comments | Select-Object -First 15 | ft number,comments,title
foreach ($issue in $issues)
{
if ($issue.labels.name -contains 'bug' -and $issue.labels.name -contains 'vi mode')
{
"{0} is a vi mode bug" -f $issue.url
}
}