├── site-recovery └── dr-at-scale-onpremise-azure │ ├── .gitignore │ ├── CREDITS.md │ ├── input_template.csv │ ├── asr_template.ps1 │ ├── asr_failover.ps1 │ ├── asr_list_protectables.ps1 │ └── asr_logger.ps1 ├── CODEOWNERS ├── azure-migrate ├── migrate-at-scale-with-site-recovery │ ├── .gitignore │ ├── CREDITS.md │ ├── input_template.csv │ ├── asr_template.ps1 │ ├── asr_migration.ps1 │ └── asr_list_protectables.ps1 ├── assessment-utility │ ├── images │ │ ├── migrateoutput.jpg │ │ └── PowerBI_example_output.jpg │ ├── Sample files │ │ ├── As is PAYG.xlsx │ │ ├── Perf PAYG.xlsx │ │ ├── As is 1 Year RI.xlsx │ │ ├── As is 3 Year RI.xlsx │ │ ├── As is PAYG AHUB.xlsx │ │ ├── Perf 1 Year RI.xlsx │ │ ├── Perf 3 Year RI.xlsx │ │ ├── Perf PAYG AHUB.xlsx │ │ ├── As is 1 Year RI AHUB.xlsx │ │ ├── As is 3 Year RI AHUB.xlsx │ │ ├── Perf 1 Year RI AHUB.xlsx │ │ ├── Perf 3 Year RI AHUB.xlsx │ │ └── Application Inventory Export Sample.xlsx │ ├── Azure Migrate - Network Connections.pbit │ └── CommonAssessmentProperties.json ├── dependencies-at-scale │ ├── images │ │ └── PowerBI_example_output.jpg │ └── Azure Migrate - Network Connections.pbit ├── SQL Migration │ ├── get-clusterinfo.ps1 │ └── Update-ClusterConfig.ps1 ├── migrate-at-scale-vmware-agentles │ ├── AzMigrate_AutomationNScale │ │ ├── Input.csv │ │ └── AzMigrate_Template.txt │ └── Agentless VMware automation │ │ └── AzMigrate_Template.ps1 └── automation-script │ ├── AzMigrate_ClntScript.ps1 │ └── AzMigrate_Template.ps1 ├── maintenance-auto-scheduler ├── images │ ├── add_identity.png │ ├── assign_role.png │ └── run_function.png ├── function.json └── run.ps1 ├── .github └── pull_request_template.md ├── application-gateway └── iis │ ├── install_nginx.sh │ └── appgatewayurl.ps1 ├── virtual-machine ├── install-iis-format-disk │ └── install-iis-format-disk.ps1 ├── create-vm-detailed │ ├── create-windows-vm-quick.ps1 │ └── create-windows-vm-detailed.ps1 ├── create-vm-iis │ └── create-windows-vm-iis.ps1 ├── create-vm-dsc │ └── create-windows-vm-iis-dsc.ps1 ├── create-vm-monitor-oms │ └── create-windows-vm-detailed-oms.ps1 ├── copy-managed-disks-to-same-or-different-subscription │ └── copy-managed-disks-to-same-or-different-subscription.ps1 ├── create-managed-disk-from-snapshot │ └── create-managed-disk-from-snapshot.ps1 ├── copy-snapshot-to-storage-account │ └── copy-snapshot-to-storage-account.ps1 ├── copy-snapshot-to-same-or-different-subscription │ └── copy-snapshot-to-same-or-different-subscription.ps1 └── create-snapshots-from-vhd-in-different-subscription │ └── create-snapshots-from-vhd-in-different-subscription.ps1 ├── .gitattributes ├── event-grid ├── subscribe-to-azure-subscription │ └── subscribe-to-azure-subscription.ps1 ├── subscribe-to-resource-group │ └── subscribe-to-resource-group.ps1 ├── create-custom-topic │ └── create-custom-topic.ps1 ├── subscribe-to-azure-subscription-preview │ └── subscribe-to-azure-subscription-preview.ps1 ├── subscribe-to-resource-group-preview │ └── subscribe-to-resource-group-preview.ps1 ├── subscribe-to-custom-topic │ └── subscribe-to-custom-topic.ps1 ├── subscribe-to-blob-storage │ └── subscribe-to-blob-storage.ps1 ├── subscribe-to-custom-topic-preview │ └── subscribe-to-custom-topic-preview.ps1 ├── filter-events │ └── filter-events.ps1 └── filter-events-preview │ └── filter-events-preview.ps1 ├── virtual-machine-scale-sets ├── simple-scale-set │ └── simple-scale-set.ps1 ├── use-custom-vm-image │ └── use-custom-vm-image.ps1 ├── use-data-disks │ └── use-data-disks.ps1 ├── create-single-availability-zone │ └── create-single-availability-zone.ps1 ├── create-zone-redundant-scale-set │ └── create-zone-redundant-scale-set.ps1 └── install-apps │ └── install-apps.ps1 ├── cosmosdb ├── table │ ├── ps-table-ru-get.ps1 │ ├── ps-table-ru-migrate.ps1 │ ├── ps-table-ru-migration.ps1 │ ├── ps-table-list-get.ps1 │ ├── ps-table-ru-update.ps1 │ ├── ps-table-create.ps1 │ ├── ps-table-autoscale.ps1 │ └── ps-table-lock.ps1 ├── gremlin │ ├── ps-gremlin-ru-get.ps1 │ ├── ps-gremlin-list-get.ps1 │ ├── ps-gremlin-ru-update.ps1 │ ├── ps-gremlin-ru-migrate.ps1 │ └── ps-gremlin-autoscale.ps1 ├── common │ ├── ps-account-failover-priority-update.ps1 │ ├── ps-account-update.ps1 │ ├── ps-account-keys-connection-strings.ps1 │ ├── ps-account-firewall-create.ps1 │ └── ps-account-update-region.ps1 ├── cassandra │ ├── ps-cassandra-ru-get.ps1 │ ├── ps-cassandra-list-get.ps1 │ ├── ps-cassandra-ru-update.ps1 │ └── ps-cassandra-ru-migrate.ps1 ├── sql │ ├── ps-sql-ru-get.ps1 │ ├── ps-sql-list-get.ps1 │ ├── ps-sql-ru-update.ps1 │ ├── ps-sql-ru-migrate.ps1 │ ├── ps-sql-autoscale.ps1 │ ├── ps-container-large-partition-key.ps1 │ └── ps-container-create-index-none.ps1 └── mongodb │ ├── ps-mongodb-ru-get.ps1 │ ├── ps-mongodb-list-get.ps1 │ ├── ps-mongodb-ru-update.ps1 │ └── ps-mongodb-ru-migrate.ps1 ├── service-fabric ├── add-inbound-nsg-rule │ └── add-inbound-nsg-rule.ps1 ├── change-rdp-user-and-pw │ └── change-rdp-user-and-pw.ps1 ├── remove-application │ └── remove-application.ps1 ├── add-application-certificate │ └── add-new-application-certificate.ps1 ├── change-rdp-port-range │ └── change-rdp-port-range.ps1 ├── create-test-cluster │ └── create-test-cluster.ps1 ├── open-port-in-load-balancer │ └── open-port-in-load-balancer.ps1 ├── create-secure-cluster │ └── create-secure-cluster.ps1 └── deploy-application │ └── deploy-application.ps1 ├── managed-applications ├── create-application │ └── create-application.ps1 ├── apply-policy │ └── apply-policy.ps1 ├── create-definition │ └── create-definition.ps1 └── get-application │ └── get-application.ps1 ├── app-service ├── backup-delete │ └── backup-delete.ps1 ├── scale-manual │ └── scale-manual.ps1 ├── deploy-github │ └── deploy-github.ps1 ├── backup-restore │ └── backup-restore.ps1 ├── monitor-with-logs │ └── monitor-with-logs.ps1 ├── deploy-local-git │ └── deploy-local-git.ps1 ├── deploy-github-continuous │ └── deploy-github-continuous.ps1 ├── connect-to-storage │ └── connect-to-storage.ps1 ├── map-custom-domain │ └── map-custom-domain.ps1 ├── deploy-deployment-slot │ └── deploy-deployment-slot.ps1 ├── scale-geographic │ └── scale-geographic.ps1 ├── connect-to-sql │ └── connect-to-sql.ps1 ├── backup-restore-diff-sub │ └── backup-restore-diff-sub.ps1 ├── configure-ssl-certificate │ └── configure-ssl-certificate.ps1 ├── backup-onetime │ └── backup-onetime.ps1 ├── backup-scheduled │ └── backup-scheduled.ps1 └── deploy-ftp │ └── deploy-ftp.ps1 ├── virtual-network ├── peer-two-virtual-networks │ └── peer-two-virtual-networks.ps1 └── create-windows-vm-detailed.ps1 ├── notification-hubs └── create-notification-hub │ └── create-notification-hub.ps1 ├── devtest-lab ├── add-external-user-to-lab │ └── add-external-user-to-custom-lab.ps1 ├── create-custom-role-in-lab │ └── create-custom-role-in-lab.ps1 └── create-custom-image-from-vhd │ └── create-custom-image-from-vhd.ps1 ├── container-registry ├── README.md ├── service-principal-assign-role │ └── service-principal-assign-role.ps1 └── service-principal-create │ └── service-principal-create.ps1 ├── hdinsight ├── use-pig │ ├── use-pig.Tests.ps1 │ └── use-pig.ps1 ├── use-mapreduce │ └── use-mapreduce.Tests.ps1 ├── use-csharp-mapreduce │ └── use-csharp-mapreduce.Tests.ps1 ├── use-hive │ └── use-hive.Tests.ps1 └── mahout │ └── use-mahout.Tests.ps1 ├── application-proxy ├── get-all-appproxy-apps-basic.ps1 ├── get-all-connectors.ps1 ├── get-all-appproxy-apps-with-policy.ps1 ├── get-all-wildcard-apps.ps1 ├── get-all-default-domain-apps.ps1 └── get-all-custom-domain-no-cert.ps1 ├── LICENSE ├── api-management ├── create-apim-service │ └── create_apim_service.ps1 ├── scale-and-addregion-apim-service │ └── scale_and_addregion_apim_service.ps1 ├── setup-rate-limit-policy │ └── setup_rate_limit_policy.ps1 └── backup-restore-apim-service │ └── backup_restore_apim_service.ps1 ├── storage ├── rotate-storage-account-keys │ └── rotate-storage-account-keys.ps1 ├── calculate-container-size │ └── calculate-container-size.ps1 └── delete-containers-by-prefix │ └── delete-containers-by-prefix.ps1 ├── README.md └── sql-database └── create-and-configure-database └── create-and-configure-database.ps1 /site-recovery/dr-at-scale-onpremise-azure/.gitignore: -------------------------------------------------------------------------------- 1 | *.csv 2 | *.txt 3 | #.vscode/ 4 | .vs/ 5 | !input_template.csv -------------------------------------------------------------------------------- /CODEOWNERS: -------------------------------------------------------------------------------- 1 | # SQL VM: Script to upgrade extension from LightWeight to Full 2 | /sql-virtual-machine/upgrade-sql-vms-to-full/* @yareyes 3 | -------------------------------------------------------------------------------- /azure-migrate/migrate-at-scale-with-site-recovery/.gitignore: -------------------------------------------------------------------------------- 1 | *.csv 2 | *.txt 3 | #.vscode/ 4 | .vs/ 5 | !input_template.csv 6 | !samplecsv.csv 7 | -------------------------------------------------------------------------------- /maintenance-auto-scheduler/images/add_identity.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Azure/azure-docs-powershell-samples/HEAD/maintenance-auto-scheduler/images/add_identity.png -------------------------------------------------------------------------------- /maintenance-auto-scheduler/images/assign_role.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Azure/azure-docs-powershell-samples/HEAD/maintenance-auto-scheduler/images/assign_role.png -------------------------------------------------------------------------------- /maintenance-auto-scheduler/images/run_function.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Azure/azure-docs-powershell-samples/HEAD/maintenance-auto-scheduler/images/run_function.png -------------------------------------------------------------------------------- /azure-migrate/assessment-utility/images/migrateoutput.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Azure/azure-docs-powershell-samples/HEAD/azure-migrate/assessment-utility/images/migrateoutput.jpg -------------------------------------------------------------------------------- /azure-migrate/assessment-utility/Sample files/As is PAYG.xlsx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Azure/azure-docs-powershell-samples/HEAD/azure-migrate/assessment-utility/Sample files/As is PAYG.xlsx -------------------------------------------------------------------------------- /azure-migrate/assessment-utility/Sample files/Perf PAYG.xlsx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Azure/azure-docs-powershell-samples/HEAD/azure-migrate/assessment-utility/Sample files/Perf PAYG.xlsx -------------------------------------------------------------------------------- /azure-migrate/assessment-utility/Sample files/As is 1 Year RI.xlsx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Azure/azure-docs-powershell-samples/HEAD/azure-migrate/assessment-utility/Sample files/As is 1 Year RI.xlsx -------------------------------------------------------------------------------- /azure-migrate/assessment-utility/Sample files/As is 3 Year RI.xlsx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Azure/azure-docs-powershell-samples/HEAD/azure-migrate/assessment-utility/Sample files/As is 3 Year RI.xlsx -------------------------------------------------------------------------------- /azure-migrate/assessment-utility/Sample files/As is PAYG AHUB.xlsx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Azure/azure-docs-powershell-samples/HEAD/azure-migrate/assessment-utility/Sample files/As is PAYG AHUB.xlsx -------------------------------------------------------------------------------- /azure-migrate/assessment-utility/Sample files/Perf 1 Year RI.xlsx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Azure/azure-docs-powershell-samples/HEAD/azure-migrate/assessment-utility/Sample files/Perf 1 Year RI.xlsx -------------------------------------------------------------------------------- /azure-migrate/assessment-utility/Sample files/Perf 3 Year RI.xlsx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Azure/azure-docs-powershell-samples/HEAD/azure-migrate/assessment-utility/Sample files/Perf 3 Year RI.xlsx -------------------------------------------------------------------------------- /azure-migrate/assessment-utility/Sample files/Perf PAYG AHUB.xlsx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Azure/azure-docs-powershell-samples/HEAD/azure-migrate/assessment-utility/Sample files/Perf PAYG AHUB.xlsx -------------------------------------------------------------------------------- /azure-migrate/assessment-utility/images/PowerBI_example_output.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Azure/azure-docs-powershell-samples/HEAD/azure-migrate/assessment-utility/images/PowerBI_example_output.jpg -------------------------------------------------------------------------------- /azure-migrate/assessment-utility/Sample files/As is 1 Year RI AHUB.xlsx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Azure/azure-docs-powershell-samples/HEAD/azure-migrate/assessment-utility/Sample files/As is 1 Year RI AHUB.xlsx -------------------------------------------------------------------------------- /azure-migrate/assessment-utility/Sample files/As is 3 Year RI AHUB.xlsx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Azure/azure-docs-powershell-samples/HEAD/azure-migrate/assessment-utility/Sample files/As is 3 Year RI AHUB.xlsx -------------------------------------------------------------------------------- /azure-migrate/assessment-utility/Sample files/Perf 1 Year RI AHUB.xlsx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Azure/azure-docs-powershell-samples/HEAD/azure-migrate/assessment-utility/Sample files/Perf 1 Year RI AHUB.xlsx -------------------------------------------------------------------------------- /azure-migrate/assessment-utility/Sample files/Perf 3 Year RI AHUB.xlsx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Azure/azure-docs-powershell-samples/HEAD/azure-migrate/assessment-utility/Sample files/Perf 3 Year RI AHUB.xlsx -------------------------------------------------------------------------------- /azure-migrate/dependencies-at-scale/images/PowerBI_example_output.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Azure/azure-docs-powershell-samples/HEAD/azure-migrate/dependencies-at-scale/images/PowerBI_example_output.jpg -------------------------------------------------------------------------------- /azure-migrate/assessment-utility/Azure Migrate - Network Connections.pbit: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Azure/azure-docs-powershell-samples/HEAD/azure-migrate/assessment-utility/Azure Migrate - Network Connections.pbit -------------------------------------------------------------------------------- /azure-migrate/dependencies-at-scale/Azure Migrate - Network Connections.pbit: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Azure/azure-docs-powershell-samples/HEAD/azure-migrate/dependencies-at-scale/Azure Migrate - Network Connections.pbit -------------------------------------------------------------------------------- /azure-migrate/assessment-utility/Sample files/Application Inventory Export Sample.xlsx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Azure/azure-docs-powershell-samples/HEAD/azure-migrate/assessment-utility/Sample files/Application Inventory Export Sample.xlsx -------------------------------------------------------------------------------- /maintenance-auto-scheduler/function.json: -------------------------------------------------------------------------------- 1 | { 2 | "bindings": [ 3 | { 4 | "name": "Timer", 5 | "schedule": "0 */10 * * * *", 6 | "direction": "in", 7 | "type": "timerTrigger" 8 | } 9 | ] 10 | } 11 | -------------------------------------------------------------------------------- /.github/pull_request_template.md: -------------------------------------------------------------------------------- 1 | 6 | -------------------------------------------------------------------------------- /application-gateway/iis/install_nginx.sh: -------------------------------------------------------------------------------- 1 | apt-get update 2 | apt-get install -y nginx 3 | echo $(hostname) | sudo tee /var/www/html/index.html 4 | sudo mkdir -p /var/www/html/images 5 | echo "Images: " $(hostname) | sudo tee /var/www/html/images/test.html 6 | sudo mkdir -p /var/www/html/video 7 | echo "Video: " $(hostname) | sudo tee /var/www/html/video/test.html 8 | -------------------------------------------------------------------------------- /site-recovery/dr-at-scale-onpremise-azure/CREDITS.md: -------------------------------------------------------------------------------- 1 | # Credits 2 | 3 | ## Original contributors 4 | --- 5 | * Eduardo Díaz ([ediazrod](https://github.com/ediazrod)). Documentation and testing 6 | * Luis Javier Fernández ([luisjfdez](https://github.com/luisjfdez)). Main original developer 7 | * Gonzalo Fiuza ([gontxu7](https://github.com/gontxu7)). Documentation and testing 8 | * Juan Carlos Rodríguez. Original idea 9 | 10 | -------------------------------------------------------------------------------- /azure-migrate/migrate-at-scale-with-site-recovery/CREDITS.md: -------------------------------------------------------------------------------- 1 | # Credits 2 | 3 | ## Original contributors 4 | --- 5 | * Eduardo Díaz ([ediazrod](https://github.com/ediazrod)). Documentation and testing 6 | * Luis Javier Fernández ([luisjfdez](https://github.com/luisjfdez)). Main original developer 7 | * Gonzalo Fiuza ([gontxu7](https://github.com/gontxu7)). Documentation and testing 8 | * Juan Carlos Rodríguez. Original idea 9 | 10 | -------------------------------------------------------------------------------- /virtual-machine/install-iis-format-disk/install-iis-format-disk.ps1: -------------------------------------------------------------------------------- 1 | # This script is intended to be run from a custom script extension on a VM with an added data disk. 2 | # Install IIS on the VM 3 | Add-WindowsFeature Web-Server 4 | # Format the data disk that has been added to the VM 5 | Get-Disk | Where partitionstyle -eq 'raw' | Initialize-Disk -PartitionStyle MBR -PassThru | New-Partition -AssignDriveLetter -UseMaximumSize | Format-Volume -FileSystem NTFS -NewFileSystemLabel "myDataDisk" -Confirm:$false 6 | -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | # Set the default behavior, in case people don't have core.autocrlf set. 2 | * text=auto 3 | 4 | # Explicitly declare text files you want to always be normalized and converted 5 | # to native line endings on checkout. 6 | *.c text 7 | *.h text 8 | 9 | # Denote all files that are truly binary and should not be modified. 10 | *.gif binary 11 | *.ico binary 12 | *.jpg binary 13 | *.png binary 14 | 15 | # Declare files that will always have CRLF line endings on checkout. 16 | *.sln text eol=crlf 17 | -------------------------------------------------------------------------------- /application-gateway/iis/appgatewayurl.ps1: -------------------------------------------------------------------------------- 1 | Add-WindowsFeature Web-Server 2 | Add-Content -Path "C:\inetpub\wwwroot\Default.htm" -Value $($env:computername) 3 | New-Item -ItemType directory -Path "C:\inetpub\wwwroot\images" 4 | New-Item -ItemType directory -Path "C:\inetpub\wwwroot\video" 5 | $imagevalue = "Images: " + $($env:computername) 6 | Add-Content -Path "C:\inetpub\wwwroot\images\test.htm" -Value $imagevalue 7 | $videovalue = "Video: " + $($env:computername) 8 | Add-Content -Path "C:\inetpub\wwwroot\video\test.htm" -Value $videovalue -------------------------------------------------------------------------------- /event-grid/subscribe-to-azure-subscription/subscribe-to-azure-subscription.ps1: -------------------------------------------------------------------------------- 1 | # Provide an endpoint for handling the events. Must be formatted "https://your-endpoint-URL" 2 | $myEndpoint = "" 3 | 4 | # Select the Azure subscription you want to subscribe to. You need this command only if the 5 | # current subscription is not the one you wish to subscribe to. 6 | Set-AzContext -Subscription "" 7 | 8 | # Subscribe to the Azure subscription. The command creates the subscription for the currently selected Azure subscription. 9 | New-AzEventGridSubscription -Endpoint $myEndpoint -EventSubscriptionName demoSubscriptionToAzureSub 10 | -------------------------------------------------------------------------------- /virtual-machine-scale-sets/simple-scale-set/simple-scale-set.ps1: -------------------------------------------------------------------------------- 1 | # Provide your own secure password for use with the VM instances 2 | $cred = Get-Credential 3 | 4 | # Create a virtual machine scale set and supporting resources 5 | # A resource group, virtual network, load balancer, and NAT rules are automatically 6 | # created if they do not already exist 7 | $Params = @{ 8 | ResourceGroupName = 'myResourceGroup' 9 | VMScaleSetName = 'myScaleSet' 10 | Location = 'EastUS' 11 | VirtualNetworkName = 'myVnet' 12 | SubnetName = 'mySubnet' 13 | PublicIpAddressName = 'myPublicIPAddress' 14 | LoadBalancerName = 'myLoadBalancer' 15 | Credential = $cred 16 | } 17 | New-AzVmss @Params 18 | -------------------------------------------------------------------------------- /event-grid/subscribe-to-resource-group/subscribe-to-resource-group.ps1: -------------------------------------------------------------------------------- 1 | # Provide an endpoint for handling the events. Must be formatted "https://your-endpoint-URL" 2 | $myEndpoint = "" 3 | 4 | # Provide the name of the resource group to create and subscribe to. 5 | $myResourceGroup="" 6 | 7 | # Create resource grroup 8 | New-AzResourceGroup -Name $myResourceGroup -Location westus2 9 | 10 | # Subscribe to the resource group. Provide the name of the resource group you want to subscribe to. 11 | New-AzEventGridSubscription ` 12 | -Endpoint $myEndpoint ` 13 | -EventSubscriptionName demoSubscriptionToResourceGroup ` 14 | -ResourceGroupName $myResourceGroup 15 | -------------------------------------------------------------------------------- /cosmosdb/table/ps-table-ru-get.ps1: -------------------------------------------------------------------------------- 1 | # Reference: Az.CosmosDB | https://docs.microsoft.com/powershell/module/az.cosmosdb 2 | # -------------------------------------------------- 3 | # Purpose 4 | # Get RU/s throughput for Azure Cosmos DB Table API table 5 | # -------------------------------------------------- 6 | # Variables - ***** SUBSTITUTE YOUR VALUES ***** 7 | $resourceGroupName = "myResourceGroup" # Resource Group must already exist 8 | $accountName = "myaccount" # Must be all lower case 9 | $tableName = "myTable" 10 | # -------------------------------------------------- 11 | 12 | Get-AzCosmosDBTableThroughput -ResourceGroupName $resourceGroupName ` 13 | -AccountName $accountName -Name $tableName 14 | -------------------------------------------------------------------------------- /service-fabric/add-inbound-nsg-rule/add-inbound-nsg-rule.ps1: -------------------------------------------------------------------------------- 1 | Login-AzAccount 2 | Get-AzSubscription 3 | Set-AzContext -SubscriptionId "yourSubscriptionID" 4 | 5 | $RGname="sfclustertutorialgroup" 6 | $port=8081 7 | $rulename="allowAppPort$port" 8 | $nsgname="sf-vnet-security" 9 | 10 | # Get the NSG resource 11 | $nsg = Get-AzNetworkSecurityGroup -Name $nsgname -ResourceGroupName $RGname 12 | 13 | # Add the inbound security rule. 14 | $nsg | Add-AzNetworkSecurityRuleConfig -Name $rulename -Description "Allow app port" -Access Allow ` 15 | -Protocol * -Direction Inbound -Priority 3891 -SourceAddressPrefix "*" -SourcePortRange * ` 16 | -DestinationAddressPrefix * -DestinationPortRange $port 17 | 18 | # Update the NSG. 19 | $nsg | Set-AzNetworkSecurityGroup 20 | -------------------------------------------------------------------------------- /managed-applications/create-application/create-application.ps1: -------------------------------------------------------------------------------- 1 | # Create resource group 2 | New-AzResourceGroup -Name applicationGroup -Location westcentralus 3 | 4 | # Get ID of managed application definition 5 | $appid=(Get-AzManagedApplicationDefinition -ResourceGroupName appDefinitionGroup -Name ManagedStorage).ManagedApplicationDefinitionId 6 | 7 | # Create the managed application 8 | New-AzManagedApplication ` 9 | -Name storageApp ` 10 | -Location westcentralus ` 11 | -Kind ServiceCatalog ` 12 | -ResourceGroupName applicationGroup ` 13 | -ManagedApplicationDefinitionId $appid ` 14 | -ManagedResourceGroupName "InfrastructureGroup" ` 15 | -Parameter "{`"storageAccountNamePrefix`": {`"value`": `"demostorage`"}, `"storageAccountType`": {`"value`": `"Standard_LRS`"}}" -------------------------------------------------------------------------------- /azure-migrate/SQL Migration/get-clusterinfo.ps1: -------------------------------------------------------------------------------- 1 | #Run this script to gather cluster roles` information. 2 | #No parameters required. Script needs to be run on any cluster node. 3 | $clusterOutputFile="cluster-config.csv" 4 | $groups=Get-ClusterGroup 5 | "RoleName,ResourceName,IP,ProbePort,ServicePort,NewIP" | out-file $clusterOutputFile 6 | $probePort=59999 # initial probe port number. 7 | foreach ($g in $groups) 8 | { 9 | $resources=$g | Get-ClusterResource | Where-Object {$_.ResourceType -eq 'IP Address'} 10 | foreach ($r in $resources) 11 | { 12 | $params=$r | Get-ClusterParameter | Where-Object {$_.Name -eq "Address"} 13 | "$($g.name),$($r.Name),$($params.Value),$probePort,," | out-file $clusterOutputFile -append 14 | $probePort++ 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /event-grid/create-custom-topic/create-custom-topic.ps1: -------------------------------------------------------------------------------- 1 | # Give your custom topic a unique name 2 | $myTopic = "" 3 | 4 | # Provide a name for resource group to create. It will contain the custom event. 5 | $myResourceGroup = "" 6 | 7 | # Create resource group 8 | New-AzResourceGroup -Name $myResourceGroup -Location westus2 9 | 10 | # Create custom topic 11 | New-AzEventGridTopic -ResourceGroupName $myResourceGroup -Name $myTopic -Location westus2 12 | 13 | # Retrieve endpoint and key to use when publishing to the topic 14 | $endpoint = (Get-AzEventGridTopic -ResourceGroupName $myResourceGroup -Name $myTopic).Endpoint 15 | $key = (Get-AzEventGridTopicKey -ResourceGroupName $myResourceGroup -Name $myTopic).Key1 16 | 17 | $endpoint 18 | $key 19 | -------------------------------------------------------------------------------- /virtual-machine/create-vm-detailed/create-windows-vm-quick.ps1: -------------------------------------------------------------------------------- 1 | # Variables for common values 2 | $resourceGroup = "myResourceGroup" 3 | $location = "westeurope" 4 | $vmName = "myVM" 5 | 6 | # Create user object 7 | $cred = Get-Credential -Message "Enter a username and password for the virtual machine." 8 | 9 | # Create a resource group 10 | New-AzResourceGroup -Name $resourceGroup -Location $location 11 | 12 | # Create a virtual machine 13 | New-AzVM ` 14 | -ResourceGroupName $resourceGroup ` 15 | -Name $vmName ` 16 | -Location $location ` 17 | -Image "Win2016Datacenter" ` 18 | -VirtualNetworkName "myVnet" ` 19 | -SubnetName "mySubnet" ` 20 | -SecurityGroupName "myNetworkSecurityGroup" ` 21 | -PublicIpAddressName "myPublicIp" ` 22 | -Credential $cred ` 23 | -OpenPorts 3389 24 | -------------------------------------------------------------------------------- /event-grid/subscribe-to-azure-subscription-preview/subscribe-to-azure-subscription-preview.ps1: -------------------------------------------------------------------------------- 1 | # You must have the latest version of the Event Grid PowerShell module. 2 | # To install: 3 | # Install-Module -Name AzureRM.EventGrid -AllowPrerelease -Force -Repository PSGallery 4 | 5 | # Provide an endpoint for handling the events. Must be formatted "https://your-endpoint-URL" 6 | $myEndpoint = "" 7 | 8 | # Get the subscription ID 9 | $subID = (Get-AzureRmSubscription -SubscriptionName "").Id 10 | 11 | # Subscribe to the Azure subscription. The command creates the subscription for the currently selected Azure subscription. 12 | New-AzureRmEventGridSubscription -ResourceId "/subscriptions/$subID" -Endpoint $myEndpoint -EventSubscriptionName demoSubscriptionToAzureSub 13 | -------------------------------------------------------------------------------- /service-fabric/change-rdp-user-and-pw/change-rdp-user-and-pw.ps1: -------------------------------------------------------------------------------- 1 | Login-AzAccount 2 | Get-AzSubscription 3 | Set-AzContext -SubscriptionId 'yourSubscriptionID' 4 | 5 | $nodeTypeName = 'nt1vm' 6 | $resourceGroup = 'sfclustertutorialgroup' 7 | $publicConfig = @{'UserName' = 'newuser'} 8 | $privateConfig = @{'Password' = 'PasSwo0rd$#!'} 9 | $extName = 'VMAccessAgent' 10 | $publisher = 'Microsoft.Compute' 11 | $node = Get-AzVmss -ResourceGroupName $resourceGroup -VMScaleSetName $nodeTypeName 12 | $node = Add-AzVmssExtension -VirtualMachineScaleSet $node -Name $extName -Publisher $publisher -Setting $publicConfig -ProtectedSetting $privateConfig -Type $extName -TypeHandlerVersion '2.0' -AutoUpgradeMinorVersion $true 13 | 14 | Update-AzVmss -ResourceGroupName $resourceGroup -Name $nodeTypeName -VirtualMachineScaleSet $node 15 | -------------------------------------------------------------------------------- /app-service/backup-delete/backup-delete.ps1: -------------------------------------------------------------------------------- 1 | # This sample script creates a web app in App Service with its related resources, and then creates a one-time backup for it. 2 | # To run this script, you need an existing backup for a web app. To create one, see Backup up a web app or Create a scheduled backup for a web app. 3 | 4 | $resourceGroupName = "myResourceGroup" 5 | $webappname = "" 6 | 7 | # List statuses of all backups that are complete or currently executing. 8 | Get-AzWebAppBackupList -ResourceGroupName $resourceGroupName -Name $webappname 9 | 10 | # Note the BackupID property of the backup you want to delete 11 | 12 | # Delete the backup by specifying the BackupID 13 | Remove-AzWebAppBackup -ResourceGroupName $resourceGroupName -Name $webappname ` 14 | -BackupId '' 15 | -------------------------------------------------------------------------------- /managed-applications/apply-policy/apply-policy.ps1: -------------------------------------------------------------------------------- 1 | # Retrieve the resource ID for the managed resource group 2 | $managedRgId = (Get-AzManagedApplication -ResourceGroupName DemoApp).Properties.managedResourceGroupId 3 | 4 | # Retrieve the built-in Azure policy for allowed locations 5 | $locationPolicyDefinition = Get-AzPolicyDefinition -Id /providers/Microsoft.Authorization/policyDefinitions/e56962a6-4747-49cd-b67b-bf8b01975c4c 6 | 7 | # Specify the allowed locations for new Azure resources in the managed resource group 8 | $locationsArray = @("northeurope", "westeurope") 9 | $policyParameters = @{"listOfAllowedLocations"=$locationsArray} 10 | 11 | # Assign the policy to the managed resource group 12 | New-AzPolicyAssignment -Name locationAssignment -Scope $managedRgId -PolicyDefinition $locationPolicyDefinition -PolicyParameterObject $policyParameters 13 | -------------------------------------------------------------------------------- /app-service/scale-manual/scale-manual.ps1: -------------------------------------------------------------------------------- 1 | 2 | # Generates a Random Value 3 | $Random=(New-Guid).ToString().Substring(0,8) 4 | 5 | # Variables 6 | $ResourceGroupName="myResourceGroup$random" 7 | $AppName="AppServiceManualScale$random" 8 | $Location="WestUS" 9 | 10 | # Create a Resource Group 11 | New-AzResourceGroup -Name $ResourceGroupName -Location $Location 12 | 13 | # Create an App Service Plan 14 | New-AzAppservicePlan -Name AppServiceManualScalePlan -ResourceGroupName $ResourceGroupName -Location $Location -Tier Basic 15 | 16 | # Create a Web App in the App Service Plan 17 | New-AzWebApp -Name $AppName -ResourceGroupName $ResourceGroupName -Location $Location -AppServicePlan AppServiceManualScalePlan 18 | 19 | # Scale Web App to 2 Workers 20 | Set-AzAppServicePlan -NumberofWorkers 2 -Name AppServiceManualScalePlan -ResourceGroupName $ResourceGroupName 21 | -------------------------------------------------------------------------------- /azure-migrate/assessment-utility/CommonAssessmentProperties.json: -------------------------------------------------------------------------------- 1 | { 2 | "properties": { 3 | "vmUptime": { 4 | "daysPerMonth": 31, 5 | "hoursPerDay": 24 6 | }, 7 | "discountPercentage": 0, 8 | "azureOfferCode": "MSAZR0003P", 9 | "azureLocation": "WestUs", 10 | "azurePricingTier": "Standard", 11 | "azureStorageRedundancy": "LocallyRedundant", 12 | "scalingFactor": 1, 13 | "stage": "InProgress", 14 | "currency": "USD", 15 | "azureDiskType": "StandardOrPremium", 16 | "timeRange": "Day", 17 | "percentile": "Percentile95", 18 | "sizingCriterion": "", 19 | "reservedInstance": "", 20 | "azureHybridUseBenefit": "", 21 | "azureVmFamilies": [""] 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /virtual-network/peer-two-virtual-networks/peer-two-virtual-networks.ps1: -------------------------------------------------------------------------------- 1 | # Variables for common values 2 | $rgName='MyResourceGroup' 3 | $location='eastus' 4 | 5 | # Create a resource group. 6 | New-AzResourceGroup -Name $rgName -Location $location 7 | 8 | # Create virtual network 1. 9 | $vnet1 = New-AzVirtualNetwork -ResourceGroupName $rgName -Name 'Vnet1' -AddressPrefix '10.0.0.0/16' -Location $location 10 | 11 | # Create virtual network 2. 12 | $vnet2 = New-AzVirtualNetwork -ResourceGroupName $rgName -Name 'Vnet2' -AddressPrefix '10.1.0.0/16' -Location $location 13 | 14 | # Peer VNet1 to VNet2. 15 | Add-AzVirtualNetworkPeering -Name 'LinkVnet1ToVnet2' -VirtualNetwork $vnet1 -RemoteVirtualNetworkId $vnet2.Id 16 | 17 | # Peer VNet2 to VNet1. 18 | Add-AzVirtualNetworkPeering -Name 'LinkVnet2ToVnet1' -VirtualNetwork $vnet2 -RemoteVirtualNetworkId $vnet1.Id 19 | -------------------------------------------------------------------------------- /notification-hubs/create-notification-hub/create-notification-hub.ps1: -------------------------------------------------------------------------------- 1 | # Set appropriate values for these variables 2 | $resourceGroupName = "" 3 | $nhubnamespace = "" 4 | $location = "East US" 5 | 6 | # Create a resource group. 7 | New-AzResourceGroup -Name $resourceGroupName -Location $location 8 | 9 | # Create a namespace for the resource group 10 | New-AzNotificationHubsNamespace -ResourceGroup $resourceGroupName -Namespace $nhubnamespace -Location $location 11 | 12 | # Create an input JSON file that you use with the New-AzNotificationHub command 13 | $text = '{"name": "MyNotificationHub", "Location": "East US", "Properties": { }}' 14 | $text | Out-File "inputfile2.json" 15 | 16 | # Create a notification hub 17 | New-AzNotificationHub -ResourceGroup $resourceGroupName -Namespace $nhubnamespace -InputFile .\inputfile.json 18 | -------------------------------------------------------------------------------- /managed-applications/create-definition/create-definition.ps1: -------------------------------------------------------------------------------- 1 | # Create resource group 2 | New-AzResourceGroup -Name appDefinitionGroup -Location westcentralus 3 | 4 | # Get Azure Active Directory group to manage the application 5 | $groupid=(Get-AzADGroup -SearchString appManagers).Id 6 | 7 | # Get role 8 | $roleid=(Get-AzRoleDefinition -Name Owner).Id 9 | 10 | # Create the definition for a managed application 11 | New-AzManagedApplicationDefinition ` 12 | -Name "ManagedStorage" ` 13 | -Location "westcentralus" ` 14 | -ResourceGroupName appDefinitionGroup ` 15 | -LockLevel ReadOnly ` 16 | -DisplayName "Managed Storage Account" ` 17 | -Description "Managed Az.Storage Account" ` 18 | -Authorization "${groupid}:$roleid" ` 19 | -PackageFileUri "https://raw.githubusercontent.com/Azure/azure-managedapp-samples/master/Managed%20Application%20Sample%20Packages/201-managed-storage-account/managedstorage.zip" 20 | -------------------------------------------------------------------------------- /devtest-lab/add-external-user-to-lab/add-external-user-to-custom-lab.ps1: -------------------------------------------------------------------------------- 1 | # Values to change 2 | $subscriptionId = "" 3 | $labResourceGroup = "" 4 | $labName = "" 5 | $userDisplayName = "" 6 | 7 | # Log into your Azure account 8 | Login-AzAccount 9 | 10 | # Select the Azure subscription that contains the lab. 11 | # This step is optional if you have only one subscription. 12 | Select-AzSubscription -SubscriptionId $subscriptionId 13 | 14 | # Retrieve the user object 15 | $adObject = Get-AzADUser -SearchString $userDisplayName 16 | 17 | # Create the role assignment. 18 | $labId = ('subscriptions/' + $subscriptionId + '/resourceGroups/' + $labResourceGroup + '/providers/Microsoft.DevTestLab/labs/' + $labName) 19 | New-AzRoleAssignment -ObjectId $adObject.Id -RoleDefinitionName 'DevTest Labs User' -Scope $labId 20 | -------------------------------------------------------------------------------- /event-grid/subscribe-to-resource-group-preview/subscribe-to-resource-group-preview.ps1: -------------------------------------------------------------------------------- 1 | # You must have the latest version of the Event Grid PowerShell module. 2 | # To install: 3 | # Install-Module -Name AzureRM.EventGrid -AllowPrerelease -Force -Repository PSGallery 4 | 5 | # Provide an endpoint for handling the events. Must be formatted "https://your-endpoint-URL" 6 | $myEndpoint = "" 7 | 8 | # Provide the name of the resource group to create and subscribe to. 9 | $myResourceGroup = "" 10 | 11 | # Create resource group 12 | $resourceGroupID = (New-AzResourceGroup -Name $myResourceGroup -Location westus2).ResourceId 13 | 14 | # Subscribe to the resource group. Provide the name of the resource group you want to subscribe to. 15 | New-AzEventGridSubscription ` 16 | -ResourceId $resourceGroupID ` 17 | -Endpoint $myEndpoint ` 18 | -EventSubscriptionName demoSubscriptionToResourceGroup 19 | -------------------------------------------------------------------------------- /managed-applications/get-application/get-application.ps1: -------------------------------------------------------------------------------- 1 | # Get managed applications from known resource group 2 | Get-AzManagedApplication -ResourceGroupName "DemoApp" 3 | 4 | # Get ID of managed resource group 5 | (Get-AzManagedApplication -ResourceGroupName "DemoApp").Properties.managedResourceGroupId 6 | 7 | # Get virtual machines in the managed resource group 8 | Get-AzResource -ResourceGroupName DemoApp6zkevchqk7sfq -ResourceType Microsoft.Compute/virtualMachines 9 | 10 | # Get information about virtual machines in managed resource group 11 | Get-AzVM -ResourceGroupName DemoApp6zkevchqk7sfq | ForEach{ $_.Name, $_.storageProfile.osDisk.osType, $_.hardwareProfile.vmSize } 12 | 13 | ## Resize virtual machines in managed resource group 14 | $vm = Get-AzVM -ResourceGroupName DemoApp6zkevchqk7sfq -VMName demoVM 15 | $vm.HardwareProfile.VmSize = "Standard_D2_v2" 16 | Update-AzVM -VM $vm -ResourceGroupName DemoApp6zkevchqk7sfq 17 | -------------------------------------------------------------------------------- /service-fabric/remove-application/remove-application.ps1: -------------------------------------------------------------------------------- 1 | # Variables 2 | $endpoint = 'mysftestcluster.southcentralus.cloudapp.azure.com:19000' 3 | $thumbprint = '2779F0BB9A969FB88E04915FFE7955D0389DA7AF' 4 | $packagepath="C:\Users\sfuser\Documents\Visual Studio 2017\Projects\MyApplication\MyApplication\pkg\Release" 5 | 6 | # Connect to the cluster using a client certificate. 7 | Connect-ServiceFabricCluster -ConnectionEndpoint $endpoint ` 8 | -KeepAliveIntervalInSec 10 ` 9 | -X509Credential -ServerCertThumbprint $thumbprint ` 10 | -FindType FindByThumbprint -FindValue $thumbprint ` 11 | -StoreLocation CurrentUser -StoreName My 12 | 13 | # Remove an application instance 14 | Remove-ServiceFabricApplication -ApplicationName fabric:/MyApplication 15 | 16 | # Unregister the application type 17 | Unregister-ServiceFabricApplicationType -ApplicationTypeName MyApplicationType -ApplicationTypeVersion 1.0.0 18 | -------------------------------------------------------------------------------- /event-grid/subscribe-to-custom-topic/subscribe-to-custom-topic.ps1: -------------------------------------------------------------------------------- 1 | # Provide the name of the topic you are subscribing to 2 | $myTopic = "" 3 | 4 | # Provide an endpoint for handling the events. Must be formatted "https://your-endpoint-URL" 5 | $myEndpoint = "" 6 | 7 | # Provide a name for resource group to create. It will contain the custom event. 8 | $myResourceGroup = "" 9 | 10 | # Create resource group 11 | New-AzResourceGroup -Name $myResourceGroup -Location westus2 12 | 13 | # Create custom topic 14 | New-AzEventGridTopic -ResourceGroupName $myResourceGroup -Name $myTopic -Location westus2 15 | 16 | # Subscribe to the custom event. Include the resource group that contains the custom topic. 17 | New-AzEventGridSubscription ` 18 | -EventSubscriptionName demoSubscription ` 19 | -Endpoint $myEndpoint ` 20 | -ResourceGroupName $myResourceGroup ` 21 | -TopicName $myTopic 22 | -------------------------------------------------------------------------------- /virtual-machine-scale-sets/use-custom-vm-image/use-custom-vm-image.ps1: -------------------------------------------------------------------------------- 1 | # Custom VM image must already exist in your subscription 2 | # See https://docs.microsoft.com/en-us/azure/virtual-machine-scale-sets/tutorial-use-custom-image-powershell 3 | 4 | # Provide your own secure password for use with the VM instances 5 | $cred = Get-Credential 6 | 7 | # Create a virtual machine scale set and supporting resources 8 | # A resource group, virtual network, load balancer, and NAT rules are automatically 9 | # created if they do not already exist 10 | # For -ImageName, specify the name of your own custom VM image 11 | New-AzVmss ` 12 | -ResourceGroupName "myResourceGroup" ` 13 | -VMScaleSetName "myScaleSet" ` 14 | -Location "EastUS" ` 15 | -VirtualNetworkName "myVnet" ` 16 | -SubnetName "mySubnet" ` 17 | -PublicIpAddressName "myPublicIPAddress" ` 18 | -LoadBalancerName "myLoadBalancer" ` 19 | -Credential $cred ` 20 | -ImageName "myImage" 21 | -------------------------------------------------------------------------------- /azure-migrate/migrate-at-scale-vmware-agentles/AzMigrate_AutomationNScale/Input.csv: -------------------------------------------------------------------------------- 1 | AZMIGRATEPROJECT_SUBSCRIPTION_ID,AZMIGRATEPROJECT_RESOURCE_GROUP_NAME,AZMIGRATEPROJECT_NAME,SOURCE_MACHINE_NAME,AZMIGRATEASSESSMENT_NAME,AZMIGRATEGROUP_NAME,TARGET_RESOURCE_GROUP_NAME,TARGET_VNET_NAME,TARGET_SUBNET_NAME,TARGET_MACHINE_NAME,TARGET_MACHINE_SIZE,LICENSE_TYPE,OS_DISK_ID,TARGET_DISKTYPE,AVAILABILITYZONE_NUMBER,AVAILABILITYSET_NAME,TURNOFF_SOURCESERVER,TESTMIGRATE_VNET_NAME,UPDATED_TARGET_RESOURCE_GROUP_NAME,UPDATED_TARGET_VNET_NAME,UPDATED_TARGET_MACHINE_NAME,UPDATED_TARGET_MACHINE_SIZE,UPDATED_AVAILABILITYZONE_NUMBER,UPDATED_AVAILABILITYSET_NAME,UPDATED_NIC1_ID,UPDATED_TARGET_NIC1_SELECTIONTYPE,UPDATED_TARGET_NIC1_SUBNET_NAME,UPDATED_TARGET_NIC1_IP,UPDATED_NIC2_ID,UPDATED_TARGET_NIC2_SELECTIONTYPE,UPDATED_TARGET_NIC2_SUBNET_NAME,UPDATED_TARGET_NIC2_IP,OK_TO_UPDATE,OK_TO_MIGRATE,OK_TO_USE_ASSESSMENT,OK_TO_TESTMIGRATE,OK_TO_RETRIEVE_REPLICATIONSTATUS,OK_TO_CLEANUP,OK_TO_TESTMIGRATE_CLEANUP 2 | -------------------------------------------------------------------------------- /container-registry/README.md: -------------------------------------------------------------------------------- 1 | # Azure Container Registry 2 | 3 | ## PowerShell sample scripts 4 | 5 | The scripts in this directory demonstrate working with [Azure Container Registry][acr-home] using the [Azure PowerShell][azure-psh] cmdlets. 6 | 7 | | Script | Description | 8 | | ------ | ----------- | 9 | |[service-principal-assign-role.ps1][sp-assign]| Assigns a role to an existing Azure Active Directory service principal, granting the service principal access to an Azure Container Registry. | 10 | |[service-principal-create.ps1][sp-create]| Creates a new Azure Active Directory service principal with permissions to an Azure Container Registry. | 11 | 12 | 13 | [sp-assign]: ./service-principal-assign-role/service-principal-assign-role.ps1 14 | [sp-create]: ./service-principal-create/service-principal-create.ps1 15 | 16 | 17 | [acr-home]: https://azure.microsoft.com/services/container-registry/ 18 | [azure-psh]: https://docs.microsoft.com/powershell/azure/overview -------------------------------------------------------------------------------- /cosmosdb/gremlin/ps-gremlin-ru-get.ps1: -------------------------------------------------------------------------------- 1 | # Reference: Az.CosmosDB | https://docs.microsoft.com/powershell/module/az.cosmosdb 2 | # -------------------------------------------------- 3 | # Purpose 4 | # Get database or graph throughput 5 | # -------------------------------------------------- 6 | # Variables - ***** SUBSTITUTE YOUR VALUES ***** 7 | $resourceGroupName = "myResourceGroup" # Resource Group must already exist 8 | $accountName = "myaccount" # Must be all lower case 9 | $databaseName = "myDatabase" 10 | $graphName = "myGraph" 11 | # -------------------------------------------------- 12 | 13 | Write-Host "Get database shared throughput" 14 | Get-AzCosmosDBGremlinDatabaseThroughput -ResourceGroupName $resourceGroupName ` 15 | -AccountName $accountName -Name $databaseName 16 | 17 | Write-Host "Get graph dedicated throughput" 18 | Get-AzCosmosDBGremlinGraphThroughput -ResourceGroupName $resourceGroupName ` 19 | -AccountName $accountName -DatabaseName $databaseName ` 20 | -Name $graphName 21 | -------------------------------------------------------------------------------- /hdinsight/use-pig/use-pig.Tests.ps1: -------------------------------------------------------------------------------- 1 | $here = Split-Path -Parent $MyInvocation.MyCommand.Path 2 | $sut = (Split-Path -Leaf $MyInvocation.MyCommand.Path) -replace '\.Tests', '' 3 | . "$here\$sut" 4 | 5 | $clusterName = $ENV:ClusterName 6 | $httpUserPassword = $ENV:HttpPassword 7 | $securePassword = ConvertTo-SecureString $httpUserPassword -AsPlainText -Force 8 | $creds = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList "admin", $securePassword 9 | 10 | # Mocks don't work for Get-Credential, so we're implementing our own version of it. This is used for tests instead of the real one. 11 | function Get-Credential { return $creds } 12 | 13 | Describe "hdinsight-hadoop-use-pig-powershell" { 14 | It "Runs a Pig query using Start-AzHDInsightJob" { 15 | Mock Read-Host { $clusterName } 16 | # Test that the data we received starts with the expected date column 17 | (Start-PigJob $clusterName $creds)[-1].StartsWith("(TRACE,816)") | Should be True 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /cosmosdb/common/ps-account-failover-priority-update.ps1: -------------------------------------------------------------------------------- 1 | # Reference: Az.CosmosDB | https://docs.microsoft.com/powershell/module/az.cosmosdb 2 | # -------------------------------------------------- 3 | # Purpose 4 | # Update Cosmos DB account: Change region failover priority. 5 | # Note: updating location at priority 0 triggers a failover to the new location 6 | # -------------------------------------------------- 7 | # Variables - ***** SUBSTITUTE YOUR VALUES ***** 8 | $resourceGroupName = "myResourceGroup" # Resource Group must already exist 9 | $accountName = "myaccount" # Must be all lower case 10 | $locations = @("West US", "East US") # Regions ordered by UPDATED failover priority 11 | # -------------------------------------------------- 12 | 13 | # Get existing Cosmos DB account 14 | $account = Get-AzCosmosDBAccount -ResourceGroupName $resourceGroupName -Name $accountName 15 | 16 | # Update account failover priority 17 | Update-AzCosmosDBAccountFailoverPriority -InputObject $account -FailoverPolicy $locations 18 | -------------------------------------------------------------------------------- /service-fabric/add-application-certificate/add-new-application-certificate.ps1: -------------------------------------------------------------------------------- 1 | 2 | # Variables for common values. 3 | $clusterloc="SouthCentralUS" 4 | $groupname="mysfclustergroup" 5 | $clustername = "mysfcluster" 6 | $vaultname = "mykeyvault" 7 | $subname="$clustername.$clusterloc.cloudapp.azure.com" 8 | $subscriptionID = 'subscription ID' 9 | 10 | # Login and select your subscription 11 | Connect-AzAccount 12 | Get-AzSubscription -SubscriptionId $subscriptionID | Select-AzSubscription 13 | 14 | # Certificate variables. 15 | $appcertpwd = ConvertTo-SecureString -String 'Password#1234' -AsPlainText -Force 16 | $appcertfolder="c:\myappcertificates\" 17 | 18 | # Create a new self-signed certificate and add it to all the VMs in the cluster. 19 | Add-AzServiceFabricApplicationCertificate -ResourceGroupName $groupname -Name $clustername ` 20 | -KeyVaultName $vaultname -KeyVaultResouceGroupName $groupname -CertificateSubjectName $subname ` 21 | -CertificateOutputFolder $appcertfolder -CertificatePassword $appcertpwd -------------------------------------------------------------------------------- /maintenance-auto-scheduler/run.ps1: -------------------------------------------------------------------------------- 1 | # This Example is for a Dedicated Host 2 | 3 | # Input bindings are passed in via param block. 4 | param($Timer) 5 | 6 | # Check if any maintenance updates are available for your dedicated host 7 | $isMaintenance = Get-AzMaintenanceUpdate ` 8 | -ResourceGroupName test-scheduler ` 9 | -ResourceName windowscheduler-DHost ` 10 | -ResourceType hosts ` 11 | -ResourceParentName windowScheduler ` 12 | -ResourceParentType hostGroups ` 13 | -ProviderName Microsoft.Compute 14 | 15 | 16 | # if available, apply the update. Else, write that there are "no availabe updates" to the log 17 | if ($isMaintenance -ne $null) 18 | { 19 | New-AzApplyUpdate ` 20 | -ResourceGroupName test-scheduler ` 21 | -ResourceName windowscheduler-DHost ` 22 | -ResourceType hosts ` 23 | -ResourceParentName windowScheduler ` 24 | -ResourceParentType hostGroups ` 25 | -ProviderName Microsoft.Compute 26 | } 27 | else { 28 | Write-Output 'No Updates Available' 29 | 30 | } 31 | -------------------------------------------------------------------------------- /service-fabric/change-rdp-port-range/change-rdp-port-range.ps1: -------------------------------------------------------------------------------- 1 | Login-AzAccount 2 | Get-AzSubscription 3 | Set-AzContext -SubscriptionId 'yourSubscriptionId' 4 | 5 | $groupname = "mysfclustergroup" 6 | $start=3400 7 | $end=4400 8 | 9 | # Get the load balancer resource 10 | $resource = Get-AzResource | Where {$_.ResourceGroupName –eq $groupname -and $_.ResourceType -eq "Microsoft.Network/loadBalancers"} 11 | $lb = Get-AzResource -ResourceGroupName $groupname -ResourceType Microsoft.Network/loadBalancers -ResourceName $resource.Name 12 | 13 | # Update the front end port range 14 | $lb.Properties.inboundNatPools.properties.frontendPortRangeStart = $start 15 | $lb.Properties.inboundNatPools.properties.frontendPortRangeEnd = $end 16 | 17 | # Write the inbound NAT pools properties 18 | Write-Host ($lb.Properties.inboundNatPools | Format-List | Out-String) 19 | 20 | # Update the load balancer 21 | Set-AzResource -PropertyObject $lb.Properties -ResourceGroupName $groupname -ResourceType Microsoft.Network/loadBalancers -ResourceName $lb.name -Force 22 | 23 | -------------------------------------------------------------------------------- /app-service/deploy-github/deploy-github.ps1: -------------------------------------------------------------------------------- 1 | # Replace the following URL with a public GitHub repo URL 2 | $gitrepo="https://github.com/Azure-Samples/app-service-web-dotnet-get-started.git" 3 | $webappname="mywebapp$(Get-Random)" 4 | $location="West Europe" 5 | 6 | # Create a resource group. 7 | New-AzResourceGroup -Name myResourceGroup -Location $location 8 | 9 | # Create an App Service plan in Free tier. 10 | New-AzAppServicePlan -Name $webappname -Location $location -ResourceGroupName myResourceGroup -Tier Free 11 | 12 | # Create a web app. 13 | New-AzWebApp -Name $webappname -Location $location -AppServicePlan $webappname -ResourceGroupName myResourceGroup 14 | 15 | # Configure GitHub deployment from your GitHub repo and deploy once. 16 | $PropertiesObject = @{ 17 | repoUrl = "$gitrepo"; 18 | branch = "master"; 19 | isManualIntegration = "true"; 20 | } 21 | Set-AzResource -Properties $PropertiesObject -ResourceGroupName myResourceGroup -ResourceType Microsoft.Web/sites/sourcecontrols -ResourceName $webappname/web -ApiVersion 2015-08-01 -Force 22 | -------------------------------------------------------------------------------- /cosmosdb/common/ps-account-update.ps1: -------------------------------------------------------------------------------- 1 | # Reference: Az.CosmosDB | https://docs.microsoft.com/powershell/module/az.cosmosdb 2 | # -------------------------------------------------- 3 | # Purpose 4 | # Update Cosmos DB account: Change default consistency level 5 | # -------------------------------------------------- 6 | # Variables - ***** SUBSTITUTE YOUR VALUES ***** 7 | $resourceGroupName = "myResourceGroup" # Resource Group must already exist 8 | $accountName = "myaccount" # Must be all lower case 9 | $consistencyLevel = "BoundedStaleness" 10 | $maxStalenessInterval = 300 11 | $maxStalenessPrefix = 100000 12 | # -------------------------------------------------- 13 | 14 | # Get existing Cosmos DB account 15 | $account = Get-AzCosmosDBAccount -ResourceGroupName $resourceGroupName -Name $accountName 16 | 17 | Write-Host "Updating account $accountName" 18 | Update-AzCosmosDBAccount -InputObject $account ` 19 | -DefaultConsistencyLevel $consistencyLevel ` 20 | -MaxStalenessIntervalInSeconds $maxStalenessInterval ` 21 | -MaxStalenessPrefix $maxStalenessPrefix 22 | -------------------------------------------------------------------------------- /app-service/backup-restore/backup-restore.ps1: -------------------------------------------------------------------------------- 1 | $resourceGroupName = "myResourceGroup" 2 | $webappname = "" 3 | $targetResourceGroupName = "myResourceGroup" 4 | $targetWebappName = "" 5 | 6 | # List statuses of all backups that are complete or currently executing. 7 | Get-AzWebAppBackupList -ResourceGroupName $resourceGroupName -Name $webappname 8 | 9 | # Note the BackupID property of the backup you want to restore 10 | 11 | # Get the backup object that you want to restore by specifying the BackupID 12 | $backup = (Get-AzWebAppBackup -ResourceGroupName $resourceGroupName -Name $webappname -BackupId '') 13 | 14 | # Get the storage account URL of the backup configuration 15 | $url = (Get-AzWebAppBackupConfiguration -ResourceGroupName $resourceGroupName -Name $webappname).StorageAccountUrl 16 | 17 | # Restore the app by overwriting it with the backup data 18 | Restore-AzWebAppBackup -ResourceGroupName $resourceGroupName -Name $webappname -StorageAccountUrl $url -BlobName $backup.BlobName -Overwrite 19 | -------------------------------------------------------------------------------- /cosmosdb/table/ps-table-ru-migrate.ps1: -------------------------------------------------------------------------------- 1 | # Reference: Az.CosmosDB | https://docs.microsoft.com/powershell/module/az.cosmosdb 2 | # -------------------------------------------------- 3 | # Purpose 4 | # Migrate a table to autoscale or standard (manual) throughput 5 | # -------------------------------------------------- 6 | # Variables - ***** SUBSTITUTE YOUR VALUES ***** 7 | $resourceGroupName = "myResourceGroup" # Resource Group must already exist 8 | $accountName = "myaccount" # Must be all lower case 9 | $tableName = "myTable" 10 | # -------------------------------------------------- 11 | 12 | Write-Host "Migrate table with standard throughput to autoscale throughput." 13 | Invoke-AzCosmosDBTableThroughputMigration -ResourceGroupName $resourceGroupName ` 14 | -AccountName $accountName -Name $tableName -ThroughputType Autoscale 15 | 16 | Write-Host "Migrate table with autoscale throughput to standard throughput." 17 | Invoke-AzCosmosDBTableThroughputMigration -ResourceGroupName $resourceGroupName ` 18 | -AccountName $accountName -Name $tableName -ThroughputType Manual 19 | -------------------------------------------------------------------------------- /cosmosdb/cassandra/ps-cassandra-ru-get.ps1: -------------------------------------------------------------------------------- 1 | # Reference: Az.CosmosDB | https://docs.microsoft.com/powershell/module/az.cosmosdb 2 | # -------------------------------------------------- 3 | # Purpose 4 | # Get keyspace or table throughput 5 | # -------------------------------------------------- 6 | # Variables - ***** SUBSTITUTE YOUR VALUES ***** 7 | $resourceGroupName = "myResourceGroup" # Resource Group must already exist 8 | $accountName = "myaccount" # Must be all lower case 9 | $keyspaceName = "mykeyspace" # Keyspace with shared throughput 10 | $tableName = "mytable" # Table with dedicated throughput 11 | # -------------------------------------------------- 12 | 13 | Write-Host "Get keyspace shared throughput" 14 | Get-AzCosmosDBCassandraKeyspaceThroughput -ResourceGroupName $resourceGroupName ` 15 | -AccountName $accountName -Name $keyspaceName 16 | 17 | Write-Host "Get table dedicated throughput" 18 | Get-AzCosmosDBCassandraTableThroughput -ResourceGroupName $resourceGroupName ` 19 | -AccountName $accountName -KeyspaceName $keyspaceName ` 20 | -Name $tableName 21 | -------------------------------------------------------------------------------- /cosmosdb/table/ps-table-ru-migration.ps1: -------------------------------------------------------------------------------- 1 | # Reference: Az.CosmosDB | https://docs.microsoft.com/powershell/module/az.cosmosdb 2 | # -------------------------------------------------- 3 | # Purpose 4 | # Migrate a table to autoscale or standard (manual) throughput 5 | # -------------------------------------------------- 6 | # Variables - ***** SUBSTITUTE YOUR VALUES ***** 7 | $resourceGroupName = "myResourceGroup" # Resource Group must already exist 8 | $accountName = "myaccount" # Must be all lower case 9 | $tableName = "myTable" 10 | # -------------------------------------------------- 11 | 12 | Write-Host "Migrate table with standard throughput to autoscale throughput." 13 | Invoke-AzCosmosDBTableThroughputMigration -ResourceGroupName $resourceGroupName ` 14 | -AccountName $accountName -Name $tableName -ThroughputType Autoscale 15 | 16 | Write-Host "Migrate table with autoscale throughput to standard throughput." 17 | Invoke-AzCosmosDBTableThroughputMigration -ResourceGroupName $resourceGroupName ` 18 | -AccountName $accountName -Name $tableName -ThroughputType Manual 19 | -------------------------------------------------------------------------------- /cosmosdb/sql/ps-sql-ru-get.ps1: -------------------------------------------------------------------------------- 1 | # Reference: Az.CosmosDB | https://docs.microsoft.com/powershell/module/az.cosmosdb 2 | # -------------------------------------------------- 3 | # Purpose 4 | # Get database or container throughput 5 | # -------------------------------------------------- 6 | # Variables - ***** SUBSTITUTE YOUR VALUES ***** 7 | $resourceGroupName = "myResourceGroup" # Resource Group must already exist 8 | $accountName = "myaccount" # Must be all lower case 9 | $databaseName = "myDatabase" 10 | $containerName = "myContainer" 11 | # -------------------------------------------------- 12 | 13 | Write-Host "Get database shared throughput - if none provisioned, will return error." 14 | Get-AzCosmosDBSqlDatabaseThroughput -ResourceGroupName $resourceGroupName ` 15 | -AccountName $accountName -Name $databaseName 16 | 17 | Write-Host "Get container dedicated throughput - if none provisioned, will return error." 18 | Get-AzCosmosDBSqlContainerThroughput -ResourceGroupName $resourceGroupName ` 19 | -AccountName $accountName -DatabaseName $databaseName ` 20 | -Name $containerName 21 | -------------------------------------------------------------------------------- /cosmosdb/mongodb/ps-mongodb-ru-get.ps1: -------------------------------------------------------------------------------- 1 | # Reference: Az.CosmosDB | https://docs.microsoft.com/powershell/module/az.cosmosdb 2 | # -------------------------------------------------- 3 | # Purpose 4 | # Get database or collection throughput 5 | # -------------------------------------------------- 6 | # Variables - ***** SUBSTITUTE YOUR VALUES ***** 7 | $resourceGroupName = "myResourceGroup" # Resource Group must already exist 8 | $accountName = "myaccount" # Must be all lower case 9 | $databaseName = "myDatabase" # Keyspace with shared throughput 10 | $collectionName = "myCollection" # Table with dedicated throughput 11 | # -------------------------------------------------- 12 | 13 | Write-Host "Get database shared throughput" 14 | Get-AzCosmosDBMongoDBDatabaseThroughput -ResourceGroupName $resourceGroupName ` 15 | -AccountName $accountName -Name $databaseName 16 | 17 | Write-Host "Get collection dedicated throughput" 18 | Get-AzCosmosDBMongoDBCollectionThroughput -ResourceGroupName $resourceGroupName ` 19 | -AccountName $accountName -DatabaseName $databaseName ` 20 | -Name $collectionName 21 | -------------------------------------------------------------------------------- /cosmosdb/common/ps-account-keys-connection-strings.ps1: -------------------------------------------------------------------------------- 1 | # Reference: Az.CosmosDB | https://docs.microsoft.com/powershell/module/az.cosmosdb 2 | # -------------------------------------------------- 3 | # Purpose 4 | # List an account's connection strings and keys; regenerate a key. 5 | # -------------------------------------------------- 6 | # Variables - ***** SUBSTITUTE YOUR VALUES ***** 7 | $resourceGroupName = "myResourceGroup" # Resource Group must already exist 8 | $accountName = "myaccount" # Must be all lower case 9 | $keyKind = "primary" # Other key kinds: secondary, primaryReadonly, secondaryReadonly 10 | # -------------------------------------------------- 11 | 12 | Write-Host "List connection strings" 13 | Get-AzCosmosDBAccountKey -ResourceGroupName $resourceGroupName ` 14 | -Name $accountName -Type "ConnectionStrings" 15 | 16 | Write-Host "List keys" 17 | Get-AzCosmosDBAccountKey -ResourceGroupName $resourceGroupName ` 18 | -Name $accountName -Type "Keys" 19 | 20 | Write-Host "Reset key" 21 | New-AzCosmosDBAccountKey -ResourceGroupName $resourceGroupName ` 22 | -Name $accountName -KeyKind $keyKind 23 | -------------------------------------------------------------------------------- /event-grid/subscribe-to-blob-storage/subscribe-to-blob-storage.ps1: -------------------------------------------------------------------------------- 1 | # Provide a unique name for the Blob storage account. 2 | $storageName = "" 3 | 4 | # Provide an endpoint for handling the events. Must be formatted "https://your-endpoint-URL" 5 | $myEndpoint = "" 6 | 7 | # Provide the name of the resource group to create. It will contain the storage account. 8 | $myResourceGroup="" 9 | 10 | # Create resource group 11 | New-AzResourceGroup -Name $myResourceGroup -Location westus2 12 | 13 | # Create the Blob storage account. 14 | New-AzStorageAccount -ResourceGroupName $myResourceGroup ` 15 | -Name $storageName ` 16 | -Location westus2 ` 17 | -SkuName Standard_LRS ` 18 | -Kind BlobStorage ` 19 | -AccessTier Hot 20 | 21 | # Get the resource ID of the Blob storage account. 22 | $storageId = (Get-AzStorageAccount -ResourceGroupName $myResourceGroup -AccountName $storageName).Id 23 | 24 | # Subscribe to the Blob storage account. 25 | New-AzEventGridSubscription ` 26 | -EventSubscriptionName demoSubToStorage ` 27 | -Endpoint $myEndpoint ` 28 | -ResourceId $storageId 29 | -------------------------------------------------------------------------------- /event-grid/subscribe-to-custom-topic-preview/subscribe-to-custom-topic-preview.ps1: -------------------------------------------------------------------------------- 1 | # You must have the latest version of the Event Grid PowerShell module. 2 | # To install: 3 | # Install-Module -Name AzureRM.EventGrid -AllowPrerelease -Force -Repository PSGallery 4 | 5 | # Provide the name of the topic you are subscribing to 6 | $myTopic = "" 7 | 8 | # Provide an endpoint for handling the events. Must be formatted "https://your-endpoint-URL" 9 | $myEndpoint = "" 10 | 11 | # Provide the name of the resource group to create. It will contain the custom topic. 12 | $myResourceGroup = "" 13 | 14 | # Create resource group 15 | New-AzResourceGroup -Name $myResourceGroup -Location westus2 16 | 17 | # Create custom topic and get its resource ID. 18 | $topicID = (New-AzEventGridTopic -ResourceGroupName $myResourceGroup -Name $myTopic -Location westus2).Id 19 | 20 | # Subscribe to the custom event. Include the resource group that contains the custom topic. 21 | New-AzEventGridSubscription ` 22 | -ResourceId $topicID ` 23 | -EventSubscriptionName demoSubscription ` 24 | -Endpoint $myEndpoint 25 | -------------------------------------------------------------------------------- /service-fabric/create-test-cluster/create-test-cluster.ps1: -------------------------------------------------------------------------------- 1 | Login-AzAccount 2 | Get-AzSubscription 3 | Set-AzContext -SubscriptionId "" 4 | 5 | # Certificate variables. 6 | $certpwd="Password#1234" | ConvertTo-SecureString -AsPlainText -Force 7 | $certfolder="c:\mycertificates\" 8 | 9 | # Variables for VM admin. 10 | $adminuser="vmadmin" 11 | $adminpwd="Password#1234" | ConvertTo-SecureString -AsPlainText -Force 12 | 13 | # Variables for common values 14 | $clusterloc="SouthCentralUS" 15 | $clustername = "mysftestcluster" 16 | $groupname="mysfclustergroup" 17 | $vmsku = "Standard_D1_v2" 18 | $subname="$clustername.$clusterloc.cloudapp.azure.com" 19 | 20 | # Set the number of cluster nodes. Possible values: 1, 3-99 21 | $clustersize=3 22 | 23 | # Create the Service Fabric cluster. 24 | New-AzServiceFabricCluster -Name $clustername -ResourceGroupName $groupname -Location $clusterloc ` 25 | -ClusterSize $clustersize -VmUserName $adminuser -VmPassword $adminpwd -CertificateSubjectName $subname ` 26 | -CertificatePassword $certpwd -CertificateOutputFolder $certfolder ` 27 | -OS WindowsServer2016DatacenterwithContainers -VmSku $vmsku 28 | -------------------------------------------------------------------------------- /virtual-machine/create-vm-iis/create-windows-vm-iis.ps1: -------------------------------------------------------------------------------- 1 | # Variables for common values 2 | $resourceGroup = "myResourceGroup" 3 | $location = "westeurope" 4 | $vmName = "myVM" 5 | 6 | # Create user object 7 | $cred = Get-Credential -Message "Enter a username and password for the virtual machine." 8 | 9 | # Create a resource group 10 | New-AzResourceGroup -Name $resourceGroup -Location $location 11 | 12 | # Create a virtual machine 13 | New-AzVM ` 14 | -ResourceGroupName $resourceGroup ` 15 | -Name $vmName ` 16 | -Location $location ` 17 | -ImageName "Win2016Datacenter" ` 18 | -VirtualNetworkName "myVnet" ` 19 | -SubnetName "mySubnet" ` 20 | -SecurityGroupName "myNetworkSecurityGroup" ` 21 | -PublicIpAddressName "myPublicIp" ` 22 | -Credential $cred ` 23 | -OpenPorts 80 24 | 25 | # Install IIS 26 | $PublicSettings = '{"commandToExecute":"powershell Add-WindowsFeature Web-Server"}' 27 | 28 | Set-AzVMExtension -ExtensionName "IIS" -ResourceGroupName $resourceGroup -VMName $vmName ` 29 | -Publisher "Microsoft.Compute" -ExtensionType "CustomScriptExtension" -TypeHandlerVersion 1.4 ` 30 | -SettingString $PublicSettings -Location $location 31 | -------------------------------------------------------------------------------- /app-service/monitor-with-logs/monitor-with-logs.ps1: -------------------------------------------------------------------------------- 1 | 2 | # Generates a Random Value 3 | $Random=(New-Guid).ToString().Substring(0,8) 4 | 5 | # Variables 6 | $ResourceGroupName="myResourceGroup$Random" 7 | $AppName="AppServiceMonitor$Random" 8 | $Location="WestUS" 9 | 10 | # Create a Resource Group 11 | New-AzResourceGroup -Name $ResourceGroupName -Location $Location 12 | 13 | # Create an App Service Plan 14 | New-AzAppservicePlan -Name AppServiceMonitorPlan -ResourceGroupName $ResourceGroupName -Location $Location -Tier Basic 15 | 16 | # Create a Web App in the App Service Plan 17 | New-AzWebApp -Name $AppName -ResourceGroupName $ResourceGroupName -Location $Location -AppServicePlan AppServiceMonitorPlan 18 | 19 | # Enable Logs 20 | Set-AzWebApp -RequestTracingEnabled $True -HttpLoggingEnabled $True -DetailedErrorLoggingEnabled $True -ResourceGroupName $ResourceGroupName -Name $AppName 21 | 22 | # Make a Request 23 | Invoke-WebRequest -Method "Get" -Uri https://$AppName.azurewebsites.net/404 -ErrorAction SilentlyContinue 24 | 25 | # Download the Web App Logs 26 | Write-Host "In your browser, download the logs for your app at https://$AppName.scm.azurewebsites.net/api/dump" 27 | -------------------------------------------------------------------------------- /cosmosdb/table/ps-table-list-get.ps1: -------------------------------------------------------------------------------- 1 | # Reference: Az.CosmosDB | https://docs.microsoft.com/powershell/module/az.cosmosdb 2 | # -------------------------------------------------- 3 | # Purpose 4 | # Show list and get operations for Azure Cosmos DB Table API 5 | # -------------------------------------------------- 6 | # Variables - ***** SUBSTITUTE YOUR VALUES ***** 7 | $resourceGroupName = "myResourceGroup" # Resource Group must already exist 8 | $accountName = "myaccount" # Must be all lower case 9 | $tableName = "myTable" 10 | # -------------------------------------------------- 11 | 12 | Write-Host "List all accounts in a resource group" 13 | Get-AzCosmosDBAccount -ResourceGroupName $resourceGroupName 14 | 15 | Write-Host "Get an account in a resource group" 16 | Get-AzCosmosDBAccount -ResourceGroupName $resourceGroupName ` 17 | -Name $accountName 18 | 19 | Write-Host "List all tables in an account" 20 | Get-AzCosmosDBTable -ResourceGroupName $resourceGroupName ` 21 | -AccountName $accountName 22 | 23 | Write-Host "Get a table in an account including throughput" 24 | Get-AzCosmosDBTable -ResourceGroupName $resourceGroupName ` 25 | -AccountName $accountName -Name $tableName 26 | -------------------------------------------------------------------------------- /hdinsight/use-mapreduce/use-mapreduce.Tests.ps1: -------------------------------------------------------------------------------- 1 | $here = Split-Path -Parent $MyInvocation.MyCommand.Path 2 | $sut = (Split-Path -Leaf $MyInvocation.MyCommand.Path) -replace '\.Tests', '' 3 | . "$here\$sut" 4 | 5 | $clusterName = $ENV:ClusterName 6 | $httpUserPassword = $ENV:HttpPassword 7 | $securePassword = ConvertTo-SecureString $httpUserPassword -AsPlainText -Force 8 | $creds = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList "admin", $securePassword 9 | 10 | 11 | # Mocks don't work for Get-Credential, so we're implementing our own version of it. This is used for tests instead of the real one. 12 | function Get-Credential { return $creds } 13 | 14 | Describe "hdinsight-hadoop-use-mapreduce-powershell" { 15 | # Use testdrive since there is a downloaded file 16 | in $TestDrive { 17 | It "Runs a MapReduce job using Start-AzHDInsightJob" { 18 | Mock Read-host { $clusterName } 19 | # Test that the job succeeded 20 | (Start-MapReduce)[0].State | Should be "SUCCEEDED" 21 | } 22 | It "Downloaded the output file" { 23 | Test-Path .\output.txt | Should be True 24 | } 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /hdinsight/use-csharp-mapreduce/use-csharp-mapreduce.Tests.ps1: -------------------------------------------------------------------------------- 1 | $here = Split-Path -Parent $MyInvocation.MyCommand.Path 2 | $sut = (Split-Path -Leaf $MyInvocation.MyCommand.Path) -replace '\.Tests', '' 3 | . "$here\$sut" 4 | 5 | $clusterName = $ENV:ClusterName 6 | $httpUserPassword = $ENV:HttpPassword 7 | $securePassword = ConvertTo-SecureString $httpUserPassword -AsPlainText -Force 8 | $creds = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList "admin", $securePassword 9 | 10 | 11 | # Mocks don't work for Get-Credential, so we're implementing our own version of it. This is used for tests instead of the real one. 12 | function Get-Credential { return $creds } 13 | 14 | Describe "hdinsight-hadoop-dotnet-csharp-mapreduce" { 15 | # Use testdrive since there is a downloaded file 16 | in $TestDrive { 17 | It "Runs a C# streaming MapReduce job using Start-AzHDInsightJob" { 18 | Mock Read-host { $clusterName } 19 | # Test that the job succeeded 20 | (Start-MapReduce)[0].State | Should be "SUCCEEDED" 21 | } 22 | It "Downloaded the output file" { 23 | Test-Path .\output.txt | Should be True 24 | } 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /app-service/deploy-local-git/deploy-local-git.ps1: -------------------------------------------------------------------------------- 1 | $gitdirectory="" 2 | $webappname="mywebapp$(Get-Random)" 3 | 4 | cd $gitdirectory 5 | 6 | # Create a web app and set up Git deployement. 7 | New-AzWebApp -Name $webappname 8 | 9 | # Configure GitHub deployment from your GitHub repo and deploy once. 10 | $PropertiesObject = @{ 11 | scmType = "LocalGit"; 12 | } 13 | Set-AzResource -Properties $PropertiesObject -ResourceGroupName $webappname ` 14 | -ResourceType Microsoft.Web/sites/config -ResourceName $webappname/web ` 15 | -ApiVersion 2015-08-01 -Force 16 | 17 | # Get publishing profile for the web app 18 | $xml = [xml](Get-AzWebAppPublishingProfile -Name $webappname ` 19 | -ResourceGroupName $webappname ` 20 | -OutputFile null) 21 | 22 | # Extract connection information from publishing profile 23 | $username = $xml.SelectNodes("//publishProfile[@publishMethod=`"MSDeploy`"]/@userName").value 24 | $password = $xml.SelectNodes("//publishProfile[@publishMethod=`"MSDeploy`"]/@userPWD").value 25 | 26 | # Set git remote 27 | git remote add azure https://${username}:$password@$webappname.scm.azurewebsites.net:443/$webappname.git 28 | 29 | # Push your code to the new Azure remote 30 | git push azure master 31 | -------------------------------------------------------------------------------- /application-proxy/get-all-appproxy-apps-basic.ps1: -------------------------------------------------------------------------------- 1 | # This sample script gets all Azure AD Application Proxy applications (AppId, Name of the app, ObjID). 2 | # 3 | # This script requires PowerShell 5.1 (x64) and one of the following modules: 4 | # AzureAD 2.0.2.52 5 | # AzureADPreview 2.0.2.53 6 | # 7 | # Before you begin: 8 | # Run Connect-AzureAD to connect to the tenant domain. 9 | # Required Azure AD role: Global Administrator or Application Administrator or Application Developer 10 | 11 | Write-Host "Reading service principals. This operation might take longer..." -BackgroundColor "Black" -ForegroundColor "Green" 12 | 13 | $aadapServPrinc = Get-AzureADServicePrincipal -Top 100000 | where-object {$_.Tags -Contains "WindowsAzureActiveDirectoryOnPremApp"} 14 | 15 | Write-Host "Displaying the Azure AD Application Proxy applications." -BackgroundColor "Black" -ForegroundColor "Green" 16 | Write-Host " " 17 | 18 | $aadapServPrinc | fl AppId, DisplayName, ObjectId 19 | 20 | Write-Host " " 21 | Write-Host "Number of Azure AD Application Proxy Applications: ", $aadapServPrinc.Count 22 | Write-Host " " 23 | 24 | Write-Host ("") 25 | Write-Host ("Finished.") -BackgroundColor "Black" -ForegroundColor "Green" 26 | Write-Host ("") 27 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) Microsoft Corporation. All rights reserved. 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE 22 | -------------------------------------------------------------------------------- /application-proxy/get-all-connectors.ps1: -------------------------------------------------------------------------------- 1 | # This sample script gets all Azure AD Application Proxy Connector groups with the included connectors. 2 | # 3 | # This script requires PowerShell 5.1 (x64) and one of the following modules: 4 | # AzureAD 2.0.2.52 5 | # AzureADPreview 2.0.2.53 6 | # 7 | # Before you begin: 8 | # Run Connect-AzureAD to connect to the tenant domain. 9 | # Required Azure AD role: Global Administrator or Application Administrator 10 | 11 | Write-Host "Reading connector groups. This operation might take longer..." -BackgroundColor "Black" -ForegroundColor "Green" 12 | 13 | $aadapConnectorGroups = Get-AzureADApplicationProxyConnectorGroup -Top 100000 14 | 15 | Write-Host "Displaying connector groups and connectors..." -BackgroundColor "Black" -ForegroundColor "Green" 16 | Write-Host " " 17 | 18 | foreach ($item in $aadapConnectorGroups) { 19 | 20 | If ($item.ConnectorGroupType -eq "applicationProxy") { 21 | 22 | "Connector group: " + $item.Name, "(Id:" + $item.Id + ")"; 23 | Get-AzureADApplicationProxyConnectorGroupMembers -Id $item.Id; 24 | " "; 25 | 26 | } 27 | } 28 | 29 | Write-Host ("") 30 | Write-Host ("Finished.") -BackgroundColor "Black" -ForegroundColor "Green" 31 | Write-Host ("") 32 | -------------------------------------------------------------------------------- /service-fabric/open-port-in-load-balancer/open-port-in-load-balancer.ps1: -------------------------------------------------------------------------------- 1 | # Variables 2 | $probename = "AppPortProbe6" 3 | $rulename="AppPortLBRule6" 4 | $RGname="mysftestclustergroup" 5 | $port=8303 6 | $subscriptionID = 'subscription ID' 7 | 8 | # Login and select your subscription 9 | Connect-AzAccount 10 | Get-AzSubscription -SubscriptionId $subscriptionID | Select-AzSubscription 11 | 12 | # Get the load balancer resource 13 | $resource = Get-AzResource | Where {$_.ResourceGroupName –eq $RGname -and $_.ResourceType -eq "Microsoft.Network/loadBalancers"} 14 | $slb = Get-AzLoadBalancer -Name $resource.Name -ResourceGroupName $RGname 15 | 16 | # Add a new probe configuration to the load balancer 17 | $slb | Add-AzLoadBalancerProbeConfig -Name $probename -Protocol Tcp -Port $port -IntervalInSeconds 15 -ProbeCount 2 18 | 19 | # Add rule configuration to the load balancer 20 | $probe = Get-AzLoadBalancerProbeConfig -Name $probename -LoadBalancer $slb 21 | $slb | Add-AzLoadBalancerRuleConfig -Name $rulename -BackendAddressPool $slb.BackendAddressPools[0] -FrontendIpConfiguration $slb.FrontendIpConfigurations[0] -Probe $probe -Protocol Tcp -FrontendPort $port -BackendPort $port 22 | 23 | # Set the goal state for the load balancer 24 | $slb | Set-AzLoadBalancer 25 | -------------------------------------------------------------------------------- /app-service/deploy-github-continuous/deploy-github-continuous.ps1: -------------------------------------------------------------------------------- 1 | $gitrepo="" 2 | $gittoken="" 3 | $webappname="mywebapp$(Get-Random)" 4 | $location="West Europe" 5 | 6 | # Create a resource group. 7 | New-AzResourceGroup -Name myResourceGroup -Location $location 8 | 9 | # Create an App Service plan in Free tier. 10 | New-AzAppServicePlan -Name $webappname -Location $location ` 11 | -ResourceGroupName myResourceGroup -Tier Free 12 | 13 | # Create a web app. 14 | New-AzWebApp -Name $webappname -Location $location -AppServicePlan $webappname ` 15 | -ResourceGroupName myResourceGroup 16 | 17 | # SET GitHub 18 | $PropertiesObject = @{ 19 | token = $gittoken; 20 | } 21 | Set-AzResource -PropertyObject $PropertiesObject ` 22 | -ResourceId /providers/Microsoft.Web/sourcecontrols/GitHub -ApiVersion 2015-08-01 -Force 23 | 24 | # Configure GitHub deployment from your GitHub repo and deploy once. 25 | $PropertiesObject = @{ 26 | repoUrl = "$gitrepo"; 27 | branch = "master"; 28 | } 29 | Set-AzResource -PropertyObject $PropertiesObject -ResourceGroupName myResourceGroup ` 30 | -ResourceType Microsoft.Web/sites/sourcecontrols -ResourceName $webappname/web ` 31 | -ApiVersion 2015-08-01 -Force 32 | 33 | -------------------------------------------------------------------------------- /devtest-lab/create-custom-role-in-lab/create-custom-role-in-lab.ps1: -------------------------------------------------------------------------------- 1 | $rgName = 2 | $subscriptionId = 3 | $labName = 4 | 5 | 6 | ‘List all the operations/actions for a resource provider. 7 | Get-AzProviderOperation -OperationSearchString "Microsoft.DevTestLab/*" 8 | 9 | ‘List actions in a particular role. 10 | (Get-AzRoleDefinition "DevTest Labs User").Actions 11 | 12 | ‘Create custom role. 13 | $policyRoleDef = (Get-AzRoleDefinition "DevTest Labs User") 14 | $policyRoleDef.Id = $null 15 | $policyRoleDef.Name = "Policy Contributor" 16 | $policyRoleDef.IsCustom = $true 17 | $policyRoleDef.AssignableScopes.Clear() 18 | $policyRoleDef.AssignableScopes.Add("/subscriptions/" + $subscriptionId) 19 | $policyRoleDef.Actions.Add("Microsoft.DevTestLab/labs/policySets/policies/*") 20 | $policyRoleDef = (New-AzRoleDefinition -Role $policyRoleDef) 21 | 22 | $user=Get-AzADUser -SearchString "SomeUser" 23 | $scope = '/subscriptions/' + subscriptionId + '/resourceGroups/' + $rgName + '/providers/Microsoft.DevTestLab/labs/' + $labName + '/policySets/default/policies/AllowedVmSizesInLab' 24 | New-AzRoleAssignment -ObjectId $user.ObjectId -RoleDefinitionName "Policy Contributor" -Scope $scope 25 | -------------------------------------------------------------------------------- /api-management/create-apim-service/create_apim_service.ps1: -------------------------------------------------------------------------------- 1 | ########################################################## 2 | # Script to create a Developer SKU API Management Service 3 | # 4 | ########################################################### 5 | 6 | $random = (New-Guid).ToString().Substring(0,8) 7 | 8 | #Azure specific details 9 | $subscriptionId = "my-azure-subscription-id" 10 | 11 | # Api Management service specific details 12 | $apimServiceName = "apim-$random" 13 | $resourceGroupName = "apim-rg-$random" 14 | $location = "Japan East" 15 | $organisation = "Contoso" 16 | $adminEmail = "admin@contoso.com" 17 | 18 | # Set the context to the subscription Id where the cluster will be created 19 | Select-AzSubscription -SubscriptionId $subscriptionId 20 | 21 | # Create a resource group. 22 | New-AzResourceGroup -Name $resourceGroupName -Location $location 23 | 24 | # Create the Api Management service. Since the SKU is not specified, it creates a service with Developer SKU. 25 | New-AzApiManagement -ResourceGroupName $resourceGroupName -Name $apimServiceName -Location $location -Organization $organisation -AdminEmail $adminEmail 26 | 27 | # Get an SSO token to login into the Service 28 | Get-AzApiManagementSsoToken -ResourceGroupName $resourceGroupName -Name $apimServiceName 29 | -------------------------------------------------------------------------------- /app-service/connect-to-storage/connect-to-storage.ps1: -------------------------------------------------------------------------------- 1 | 2 | # Generates a Random Value 3 | $Random=(New-Guid).ToString().Substring(0,8) 4 | 5 | # Variables 6 | $ResourceGroup="MyResourceGroup$Random" 7 | $AppName="webappwithStorage$Random" 8 | $StorageName="webappstorage$Random" 9 | $Location="West US" 10 | 11 | # Create a Resource Group 12 | New-AzResourceGroup -Name $ResourceGroup -Location $Location 13 | 14 | # Create an App Service Plan 15 | New-AzAppservicePlan -Name WebAppwithStoragePlan -ResourceGroupName $ResourceGroup -Location $Location -Tier Basic 16 | 17 | # Create a Web App in the App Service Plan 18 | New-AzWebApp -Name $AppName -ResourceGroupName $ResourceGroup -Location $Location -AppServicePlan WebAppwithStoragePlan 19 | 20 | # Create Storage Account 21 | New-AzStorageAccount -Name $StorageName -ResourceGroupName $ResourceGroup -Location $Location -SkuName Standard_LRS 22 | 23 | # Get Connection String for Storage Account 24 | $StorageKey=(Get-AzStorageAccountKey -ResourceGroupName $ResourceGroup -Name $StorageName).Value[0] 25 | 26 | # Assign Connection String to App Setting 27 | Set-AzWebApp -ConnectionStrings @{ MyStorageConnStr = @{ Type="Custom"; Value="DefaultEndpointsProtocol=https;AccountName=$StorageName;AccountKey=$StorageKey;" } } -Name $AppName -ResourceGroupName $ResourceGroup 28 | -------------------------------------------------------------------------------- /service-fabric/create-secure-cluster/create-secure-cluster.ps1: -------------------------------------------------------------------------------- 1 | #Provide the subscription Id 2 | $subscriptionId = 'yourSubscriptionId' 3 | 4 | # Certificate variables. 5 | $certpwd="Password#1234" | ConvertTo-SecureString -AsPlainText -Force 6 | $certfolder="c:\mycertificates\" 7 | 8 | # Variables for VM admin. 9 | $adminuser="vmadmin" 10 | $adminpwd="Password#1234" | ConvertTo-SecureString -AsPlainText -Force 11 | 12 | # Variables for common values 13 | $clusterloc="SouthCentralUS" 14 | $clustername = "mysfcluster" 15 | $groupname="mysfclustergroup" 16 | $vmsku = "Standard_D2_v2" 17 | $vaultname = "mykeyvault" 18 | $subname="$clustername.$clusterloc.cloudapp.azure.com" 19 | 20 | # Set the number of cluster nodes. Possible values: 1, 3-99 21 | $clustersize=5 22 | 23 | # Set the context to the subscription Id where the cluster will be created 24 | Select-AzSubscription -SubscriptionId $subscriptionId 25 | 26 | # Create the Service Fabric cluster. 27 | New-AzServiceFabricCluster -Name $clustername -ResourceGroupName $groupname -Location $clusterloc ` 28 | -ClusterSize $clustersize -VmUserName $adminuser -VmPassword $adminpwd -CertificateSubjectName $subname ` 29 | -CertificatePassword $certpwd -CertificateOutputFolder $certfolder ` 30 | -OS WindowsServer2016DatacenterwithContainers -VmSku $vmsku -KeyVaultName $vaultname -------------------------------------------------------------------------------- /virtual-machine/create-vm-dsc/create-windows-vm-iis-dsc.ps1: -------------------------------------------------------------------------------- 1 | # Variables for common values 2 | $resourceGroup = "myResourceGroup" 3 | $location = "westeurope" 4 | $vmName = "myVM" 5 | 6 | # Create a resource group 7 | New-AzResourceGroup -Name $resourceGroup -Location $location 8 | 9 | # Create user object 10 | $cred = Get-Credential -Message "Enter a username and password for the virtual machine." 11 | 12 | # Create a virtual machine 13 | New-AzVM ` 14 | -ResourceGroupName $resourceGroup ` 15 | -Name $vmName ` 16 | -Location $location ` 17 | -ImageName "Win2016Datacenter" ` 18 | -VirtualNetworkName "myVnet" ` 19 | -SubnetName "mySubnet" ` 20 | -SecurityGroupName "myNetworkSecurityGroup" ` 21 | -PublicIpAddressName "myPublicIp" ` 22 | -Credential $cred ` 23 | -OpenPorts 80 24 | 25 | # Install IIS 26 | $PublicSettings = '{"ModulesURL":"https://github.com/Azure/azure-quickstart-templates/raw/master/dsc-extension-iis-server-windows-vm/ContosoWebsite.ps1.zip", "configurationFunction": "ContosoWebsite.ps1\\ContosoWebsite", "Properties": {"MachineName": "myVM"} }' 27 | 28 | Set-AzVMExtension -ExtensionName "DSC" -ResourceGroupName $resourceGroup -VMName $vmName ` 29 | -Publisher "Microsoft.Powershell" -ExtensionType "DSC" -TypeHandlerVersion 2.19 ` 30 | -SettingString $PublicSettings -Location $location 31 | -------------------------------------------------------------------------------- /storage/rotate-storage-account-keys/rotate-storage-account-keys.ps1: -------------------------------------------------------------------------------- 1 | # this script will show how to rotate one of the access keys for a storage account 2 | 3 | # get list of locations and pick one 4 | Get-AzLocation | select Location 5 | 6 | # save the location you want to use 7 | $location = "eastus" 8 | 9 | # create a resource group 10 | $resourceGroup = "rotatekeystestrg" 11 | New-AzResourceGroup -Name $resourceGroup -Location $location 12 | 13 | # create a standard general-purpose storage account 14 | $storageAccountName = "contosotestkeys" 15 | New-AzStorageAccount -ResourceGroupName $resourceGroup ` 16 | -Name $storageAccountName ` 17 | -Location $location ` 18 | -SkuName Standard_LRS ` 19 | 20 | # retrieve the first storage account key and display it 21 | $storageAccountKey = (Get-AzStorageAccountKey -ResourceGroupName $resourceGroup -Name $storageAccountName).Value[0] 22 | 23 | Write-Host "storage account key 1 = " $storageAccountKey 24 | 25 | # re-generate the key 26 | New-AzStorageAccountKey -ResourceGroupName $resourceGroup ` 27 | -Name $storageAccountName ` 28 | -KeyName key1 29 | 30 | # retrieve it again and display it 31 | $storageAccountKey = (Get-AzStorageAccountKey -ResourceGroupName $resourceGroup -Name $storageAccountName).Value[0] 32 | Write-Host "storage account key 1 = " $storageAccountKey 33 | -------------------------------------------------------------------------------- /site-recovery/dr-at-scale-onpremise-azure/input_template.csv: -------------------------------------------------------------------------------- 1 | VAULT_SUBSCRIPTION_ID,VAULT_NAME,SOURCE_MACHINE_NAME,TARGET_MACHINE_NAME,CONFIGURATION_SERVER,PROCESS_SERVER,TARGET_RESOURCE_GROUP,TARGET_STORAGE_ACCOUNT,TARGET_STORAGE_ACCOUNT_RG,TARGET_VNET,TARGET_VNET_RG,TARGET_SUBNET,REPLICATION_POLICY,ACCOUNT_NAME,AVAILABILITY_SET,PRIVATE_IP,MACHINE_SIZE,TESTFAILOVER_RESOURCE_GROUP,TESTFAILOVER_VNET,TARGET_NSG_NAME,TARGET_NSG_RESOURCE_GROUP 2 | ,,,,,,,,,,,,,,,,,,,, 3 | ,,,,,,,,,,,,,,,,,,,, -------------------------------------------------------------------------------- /event-grid/filter-events/filter-events.ps1: -------------------------------------------------------------------------------- 1 | # Provide an endpoint for handling the events. Must be formatted "https://your-endpoint-URL" 2 | $myEndpoint = "" 3 | 4 | # Provide the name of the resource group to create. It will contain the network security group. 5 | # You will subscribe to events for this resource group. 6 | $myResourceGroup = "" 7 | 8 | # Provide a name for the network security group to create. 9 | $nsgName = "" 10 | 11 | # Create the resource group 12 | New-AzResourceGroup -Name $myResourceGroup -Location westus2 13 | 14 | # Create a network security group. You will filter events to only those that are related to this resource. 15 | New-AzNetworkSecurityGroup -Name $nsgName -ResourceGroupName $myResourceGroup -Location westus2 16 | 17 | # Get the resource ID to filter events. The name of the network security group must not be the same as the other resource names. 18 | $resourceId = (Get-AzResource -ResourceName $nsgName -ResourceGroupName $myResourceGroup).ResourceId 19 | 20 | # Subscribe to the resource group. Provide the name of the resource group you want to subscribe to. 21 | New-AzEventGridSubscription ` 22 | -Endpoint $myEndpoint ` 23 | -EventSubscriptionName demoSubscriptionToResourceGroup ` 24 | -ResourceGroupName $myResourceGroup ` 25 | -SubjectBeginsWith $resourceId 26 | -------------------------------------------------------------------------------- /service-fabric/deploy-application/deploy-application.ps1: -------------------------------------------------------------------------------- 1 | # Variables 2 | $endpoint = 'mysftestcluster.southcentralus.cloudapp.azure.com:19000' 3 | $thumbprint = '2779F0BB9A969FB88E04915FFE7955D0389DA7AF' 4 | $packagepath="C:\Users\sfuser\Documents\Visual Studio 2017\Projects\MyApplication\MyApplication\pkg\Release" 5 | 6 | # Connect to the cluster using a client certificate. 7 | Connect-ServiceFabricCluster -ConnectionEndpoint $endpoint ` 8 | -KeepAliveIntervalInSec 10 ` 9 | -X509Credential -ServerCertThumbprint $thumbprint ` 10 | -FindType FindByThumbprint -FindValue $thumbprint ` 11 | -StoreLocation CurrentUser -StoreName My 12 | 13 | # Copy the application package to the cluster image store. 14 | Copy-ServiceFabricApplicationPackage $packagepath -ImageStoreConnectionString fabric:ImageStore -ApplicationPackagePathInImageStore MyApplication 15 | 16 | # Register the application type. 17 | Register-ServiceFabricApplicationType -ApplicationPathInImageStore MyApplication 18 | 19 | # Remove the application package to free system resources. 20 | Remove-ServiceFabricApplicationPackage -ImageStoreConnectionString fabric:ImageStore -ApplicationPackagePathInImageStore MyApplication 21 | 22 | # Create the application instance. 23 | New-ServiceFabricApplication -ApplicationName fabric:/MyApplication -ApplicationTypeName MyApplicationType -ApplicationTypeVersion 1.0.0 -------------------------------------------------------------------------------- /container-registry/service-principal-assign-role/service-principal-assign-role.ps1: -------------------------------------------------------------------------------- 1 | # Modify for your environment. The 'registryName' is the name of your Azure 2 | # Container Registry, the 'resourceGroup' is the name of the resource group 3 | # in which your registry resides, and the 'servicePrincipalId' is the 4 | # service principal's 'ApplicationId' or one of its 'servicePrincipalNames'. 5 | $registryName = "" 6 | $resourceGroup = "" 7 | $servicePrincipalId = "" 8 | 9 | # Get a reference to the container registry; need its fully qualified ID 10 | # when assigning the role to the principal in a subsequent command. 11 | $registry = Get-AzContainerRegistry -ResourceGroupName $resourceGroup -Name $registryName 12 | 13 | # Get the existing service principal; need its 'ObjectId' value 14 | # when assigning the role to the principal in a subsequent command. 15 | $sp = Get-AzADServicePrincipal -ServicePrincipalName $servicePrincipalId 16 | 17 | # Assign the role to the service principal, identified using 'ObjectId'. Default permissions are for docker 18 | # pull access. Modify the 'RoleDefinitionName' argument value as desired: 19 | # acrpull: pull only 20 | # acrpush: push and pull 21 | # Owner: push, pull, and assign roles 22 | $role = New-AzRoleAssignment -ObjectId $sp.Id -RoleDefinitionName acrpull -Scope $registry.Id 23 | -------------------------------------------------------------------------------- /event-grid/filter-events-preview/filter-events-preview.ps1: -------------------------------------------------------------------------------- 1 | # You must have the latest version of the Event Grid PowerShell module. 2 | # To install: 3 | # Install-Module -Name AzureRM.EventGrid -AllowPrerelease -Force -Repository PSGallery 4 | 5 | # Provide an endpoint for handling the events. Must be formatted "https://your-endpoint-URL" 6 | $myEndpoint = "" 7 | 8 | # Provide the name of the custom topic to create 9 | $topicName = "" 10 | 11 | # Provide the name of the resource group to create. It will contain the custom topic. 12 | $myResourceGroup= "" 13 | 14 | # Create the resource group 15 | New-AzResourceGroup -Name $myResourceGroup -Location westus2 16 | 17 | # Create custom topic 18 | New-AzEventGridTopic -ResourceGroupName $myResourceGroup -Location westus2 -Name $topicName 19 | 20 | # Get resource ID of custom topic 21 | $topicid = (Get-AzEventGridTopic -ResourceGroupName $myResourceGroup -Name $topicName).Id 22 | 23 | # Set the operator type, field and values for the filtering 24 | $AdvFilter1=@{operator="StringIn"; key="Data.color"; Values=@('blue', 'red', 'green')} 25 | 26 | # Subscribe to the custom topic. Filter based on a value in the event data. 27 | New-AzEventGridSubscription ` 28 | -ResourceId $topicid ` 29 | -EventSubscriptionName demoSubWithFilter ` 30 | -Endpoint $myEndpoint ` 31 | -AdvancedFilter @($AdvFilter1) 32 | -------------------------------------------------------------------------------- /hdinsight/use-hive/use-hive.Tests.ps1: -------------------------------------------------------------------------------- 1 | $here = Split-Path -Parent $MyInvocation.MyCommand.Path 2 | $sut = (Split-Path -Leaf $MyInvocation.MyCommand.Path) -replace '\.Tests', '' 3 | . "$here\$sut" 4 | 5 | $clusterName = $ENV:ClusterName 6 | $httpUserPassword = $ENV:HttpPassword 7 | $securePassword = ConvertTo-SecureString $httpUserPassword -AsPlainText -Force 8 | $creds = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList "admin", $securePassword 9 | 10 | # Mocks don't work for Get-Credential, so we're implementing our own version of it. This is used for tests instead of the real one. 11 | function Get-Credential { return $creds } 12 | 13 | Describe "hdinsight-hadoop-use-hive-powershell" { 14 | It "Runs a Hive query using Start-AzHDInsightJob" { 15 | # Since we only read-host to get the cluster name for this script, 16 | # just return it 17 | Mock Read-Host { $clusterName } 18 | 19 | # Test that the data we received starts with the expected date column 20 | (Start-HiveJob)[-1].StartsWith("2012-02-03") | Should be True 21 | } 22 | 23 | It "Runs a Hive query using Invoke-Hive" { 24 | # Since we only read-host to get the cluster name for this script, 25 | # just return it 26 | Mock Read-Host { $clusterName } 27 | 28 | # Test that the data we receive starts with the expected date column 29 | (Start-HiveJobInvoke)[-1].StartsWith("2012-02-03") | Should be True 30 | } 31 | 32 | } 33 | -------------------------------------------------------------------------------- /azure-migrate/automation-script/AzMigrate_ClntScript.ps1: -------------------------------------------------------------------------------- 1 | 2 | Import-Module az 3 | Connect-AzAccount 4 | 5 | $ErrorActionPreference = "Stop" 6 | 7 | $scriptsPath = $PSScriptRoot 8 | if ($PSScriptRoot -eq "") { 9 | $scriptsPath = "." 10 | } 11 | 12 | #Initiate replication 13 | #. "$scriptsPath\AzMigrate_StartReplication.ps1" .\Input.csv 14 | # Get Updated replication Status 15 | . "$scriptsPath\AzMigrate_UpdateReplicationStatus.ps1" .\Input.csv 16 | 17 | # #Start TestMigration 18 | #. "$scriptsPath\AzMigrate_StartTestMigration.ps1" .\Input.csv 19 | # Get Updated replication Status 20 | #. "$scriptsPath\AzMigrate_UpdateReplicationStatus.ps1" .\Input.csv 21 | 22 | # #Cleanup TestMigration 23 | # . "$scriptsPath\AzMigrate_CleanupTestMigration.ps1" .\Input.csv 24 | # Get Updated replication Status 25 | # . "$scriptsPath\AzMigrate_UpdateReplicationStatus.ps1" .\Input.csv 26 | 27 | # #UpdateMachineProperties 28 | #. "$scriptsPath\AzMigrate_UpdateMachineProperties.ps1" .\Input.csv 29 | # Get Updated replication Status 30 | #. "$scriptsPath\AzMigrate_UpdateReplicationStatus.ps1" .\Input.csv 31 | 32 | # #Start Migration 33 | #. "$scriptsPath\AzMigrate_StartMigration.ps1" .\Input.csv 34 | # Get Updated replication Status 35 | #. "$scriptsPath\AzMigrate_UpdateReplicationStatus.ps1" .\Input.csv 36 | 37 | # #Complete Migration 38 | #. "$scriptsPath\AzMigrate_CompleteMigration.ps1" .\Input.csv 39 | # Get Updated replication Status 40 | #. "$scriptsPath\AzMigrate_UpdateReplicationStatus.ps1" .\Input.csv 41 | 42 | Write-host "Done!" -------------------------------------------------------------------------------- /virtual-machine/create-vm-monitor-oms/create-windows-vm-detailed-oms.ps1: -------------------------------------------------------------------------------- 1 | # OMS ID and OMS key 2 | $omsId = "" 3 | $omsKey = "" 4 | 5 | # Variables for common values 6 | $resourceGroup = "myResourceGroup" 7 | $location = "westeurope" 8 | $vmName = "myVM" 9 | 10 | # Create a user object 11 | $cred = Get-Credential -Message "Enter a username and password for the virtual machine." 12 | 13 | # Create a resource group 14 | New-AzResourceGroup -Name $resourceGroup -Location $location 15 | 16 | # Create a virtual machine 17 | New-AzVM ` 18 | -ResourceGroupName $resourceGroup ` 19 | -Name $vmName ` 20 | -Location $location ` 21 | -ImageName "Win2016Datacenter" ` 22 | -VirtualNetworkName "myVnet" ` 23 | -SubnetName "mySubnet" ` 24 | -SecurityGroupName "myNetworkSecurityGroup" ` 25 | -PublicIpAddressName "myPublicIp" ` 26 | -Credential $cred ` 27 | -OpenPorts 3389 28 | 29 | # Install and configure the OMS agent 30 | $PublicSettings = New-Object psobject | Add-Member -PassThru NoteProperty workspaceId $omsId | ConvertTo-Json 31 | $protectedSettings = New-Object psobject | Add-Member -PassThru NoteProperty workspaceKey $omsKey | ConvertTo-Json 32 | 33 | Set-AzVMExtension -ExtensionName "OMS" -ResourceGroupName $resourceGroup -VMName $vmName ` 34 | -Publisher "Microsoft.EnterpriseCloud.Monitoring" -ExtensionType "MicrosoftMonitoringAgent" ` 35 | -TypeHandlerVersion 1.0 -SettingString $PublicSettings -ProtectedSettingString $protectedSettings ` 36 | -Location $location 37 | -------------------------------------------------------------------------------- /storage/calculate-container-size/calculate-container-size.ps1: -------------------------------------------------------------------------------- 1 | # this script will show how to get the total size of the blobs in a container 2 | # before running this, you need to create a storage account, create a container, 3 | # and upload some blobs into the container 4 | # note: this retrieves all of the blobs in the container in one command. 5 | # if you are going to run this against a container with a lot of blobs 6 | # (more than a couple hundred), use continuation tokens to retrieve 7 | # the list of blobs. 8 | 9 | # these are for the storage account to be used 10 | $resourceGroup = "bloblisttestrg" 11 | $storageAccountName = "contosobloblisttest" 12 | $containerName = "listtestblobs" 13 | 14 | # get a reference to the storage account and the context 15 | $storageAccount = Get-AzStorageAccount ` 16 | -ResourceGroupName $resourceGroup ` 17 | -Name $storageAccountName 18 | $ctx = $storageAccount.Context 19 | 20 | # get a list of all of the blobs in the container 21 | $listOfBlobs = Get-AzStorageBlob -Container $containerName -Context $ctx 22 | 23 | # zero out our total 24 | $length = 0 25 | 26 | # this loops through the list of blobs and retrieves the length for each blob 27 | # and adds it to the total 28 | $listOfBlobs | ForEach-Object {$length = $length + $_.Length} 29 | 30 | # output the blobs and their sizes and the total 31 | Write-Host "List of Blobs and their size (length)" 32 | Write-Host " " 33 | $listOfBlobs | select Name, Length 34 | Write-Host " " 35 | Write-Host "Total Length = " $length 36 | -------------------------------------------------------------------------------- /app-service/map-custom-domain/map-custom-domain.ps1: -------------------------------------------------------------------------------- 1 | $fqdn="" 2 | $webappname="mywebapp$(Get-Random)" 3 | $location="West Europe" 4 | 5 | # Create a resource group. 6 | New-AzResourceGroup -Name $webappname -Location $location 7 | 8 | # Create an App Service plan in Free tier. 9 | New-AzAppServicePlan -Name $webappname -Location $location ` 10 | -ResourceGroupName $webappname -Tier Free 11 | 12 | # Create a web app. 13 | $webapp = New-AzWebApp -Name $webappname -Location $location -AppServicePlan $webappname ` 14 | -ResourceGroupName $webappname 15 | 16 | Write-Host "Sign in to your domain provider's website and configure the following records:" 17 | Write-Host "A CNAME record that maps $fqdn to $webappname.azurewebsites.net" 18 | Write-Host "A TXT record that maps asuid.$fqdn to the domain verification ID $($webapp.CustomDomainVerificationId)" 19 | Read-Host "Press [Enter] key when ready ..." 20 | 21 | # Before continuing, go to your DNS configuration UI for your custom domain and follow the 22 | # instructions at https://aka.ms/appservicecustomdns to configure a CNAME record for the 23 | # hostname "www" and point it your web app's default domain name. 24 | 25 | # Upgrade App Service plan to Shared tier (minimum required by custom domains) 26 | Set-AzAppServicePlan -Name $webappname -ResourceGroupName $webappname ` 27 | -Tier Shared 28 | 29 | # Add a custom domain name to the web app. 30 | Set-AzWebApp -Name $webappname -ResourceGroupName $webappname ` 31 | -HostNames @($fqdn,"$webappname.azurewebsites.net") 32 | -------------------------------------------------------------------------------- /cosmosdb/common/ps-account-firewall-create.ps1: -------------------------------------------------------------------------------- 1 | # Reference: Az.CosmosDB | https://docs.microsoft.com/powershell/module/az.cosmosdb 2 | # -------------------------------------------------- 3 | # Purpose 4 | # Create Cosmos DB SQL API account with firewall 5 | # -------------------------------------------------- 6 | Function New-RandomString{Param ([Int]$Length = 10) return $(-join ((97..122) + (48..57) | Get-Random -Count $Length | ForEach-Object {[char]$_}))} 7 | # -------------------------------------------------- 8 | $uniqueId = New-RandomString -Length 7 # Random alphanumeric string for unique resource names 9 | $apiKind = "Sql" 10 | # -------------------------------------------------- 11 | # Variables - ***** SUBSTITUTE YOUR VALUES ***** 12 | $locations = @("East US", "West US") # Regions ordered by failover priority 13 | $resourceGroupName = "myResourceGroup" # Resource Group must already exist 14 | $accountName = "cosmos-$uniqueId" # Must be all lower case 15 | $consistencyLevel = "Session" 16 | $ipFilter = @("10.0.0.0/8", "11.0.1.0/24") 17 | $allowAzureAccess = $true # Allow access to Azure networks and portal 18 | # -------------------------------------------------- 19 | 20 | if ($true -eq $allowAzureAccess) { 21 | $ipFilter += "0.0.0.0" 22 | } 23 | 24 | Write-Host "Creating account $accountName" 25 | $account = New-AzCosmosDBAccount -ResourceGroupName $resourceGroupName ` 26 | -Location $locations -Name $accountName -ApiKind $apiKind ` 27 | -DefaultConsistencyLevel $consistencyLevel -IpRangeFilter $ipFilter ` 28 | -EnableAutomaticFailover:$true 29 | -------------------------------------------------------------------------------- /cosmosdb/table/ps-table-ru-update.ps1: -------------------------------------------------------------------------------- 1 | # Reference: Az.CosmosDB | https://docs.microsoft.com/powershell/module/az.cosmosdb 2 | # -------------------------------------------------- 3 | # Purpose 4 | # Update Table throughput 5 | # -------------------------------------------------- 6 | # Variables - ***** SUBSTITUTE YOUR VALUES ***** 7 | $resourceGroupName = "myResourceGroup" # Resource Group must already exist 8 | $accountName = "myaccount" # Must be all lower case 9 | $tableName = "myTable" 10 | $newRUs = 500 11 | # -------------------------------------------------- 12 | 13 | $throughput = Get-AzCosmosDBTableThroughput -ResourceGroupName $resourceGroupName ` 14 | -AccountName $accountName -Name $tableName 15 | 16 | $currentRUs = $throughput.Throughput 17 | $minimumRUs = $throughput.MinimumThroughput 18 | 19 | Write-Host "Current throughput is $currentRUs. Minimum allowed throughput is $minimumRUs." 20 | 21 | if ([int]$newRUs -lt [int]$minimumRUs) { 22 | Write-Host "Requested new throughput of $newRUs is less than minimum allowed throughput of $minimumRUs." 23 | Write-Host "Using minimum allowed throughput of $minimumRUs instead." 24 | $newRUs = $minimumRUs 25 | } 26 | 27 | if ([int]$newRUs -eq [int]$currentRUs) { 28 | Write-Host "New throughput is the same as current throughput. No change needed." 29 | } 30 | else { 31 | Write-Host "Updating throughput to $newRUs." 32 | 33 | Update-AzCosmosDBTableThroughput -ResourceGroupName $resourceGroupName ` 34 | -AccountName $accountName -Name $tableName ` 35 | -Throughput $newRUs 36 | } 37 | -------------------------------------------------------------------------------- /azure-migrate/migrate-at-scale-with-site-recovery/input_template.csv: -------------------------------------------------------------------------------- 1 | VAULT_SUBSCRIPTION_ID,VAULT_NAME,SOURCE_MACHINE_NAME,TARGET_MACHINE_NAME,CONFIGURATION_SERVER,PROCESS_SERVER,TARGET_RESOURCE_GROUP,TARGET_STORAGE_ACCOUNT,TARGET_STORAGE_ACCOUNT_RG,TARGET_LOGSTORAGE_ACCOUNT,TARGET_LOGSTORAGE_ACCOUNT_RG,TARGET_VNET,TARGET_VNET_RG,TARGET_SUBNET,REPLICATION_POLICY,ACCOUNT_NAME,AVAILABILITY_SET,PRIVATE_IP,MACHINE_SIZE,TESTFAILOVER_RESOURCE_GROUP,TESTFAILOVER_VNET,TARGET_NSG_NAME,TARGET_NSG_RESOURCE_GROUP,RECOVERY_VM_MANAGED_DISK_TYPE 2 | ,,,,,,,,,,,,,,,,,,,,,,, 3 | ,,,,,,,,,,,,,,,,,,,,,,, 4 | -------------------------------------------------------------------------------- /cosmosdb/gremlin/ps-gremlin-list-get.ps1: -------------------------------------------------------------------------------- 1 | # Reference: Az.CosmosDB | https://docs.microsoft.com/powershell/module/az.cosmosdb 2 | # -------------------------------------------------- 3 | # Purpose 4 | # List and get operations for accounts, databases, and graphs 5 | # -------------------------------------------------- 6 | # Variables - ***** SUBSTITUTE YOUR VALUES ***** 7 | $resourceGroupName = "myResourceGroup" # Resource Group must already exist 8 | $accountName = "myaccount" # Must be all lower case 9 | $databaseName = "myDatabase" 10 | $graphName = "myGraph" 11 | # -------------------------------------------------- 12 | 13 | Write-Host "List all accounts in a resource group" 14 | Get-AzCosmosDBAccount -ResourceGroupName $resourceGroupName 15 | 16 | Write-Host "Get an account in a resource group" 17 | Get-AzCosmosDBAccount -ResourceGroupName $resourceGroupName ` 18 | -Name $accountName 19 | 20 | Write-Host "List all databases in an account" 21 | Get-AzCosmosDBGremlinDatabase -ResourceGroupName $resourceGroupName ` 22 | -AccountName $accountName 23 | 24 | Write-Host "Get a database in an account" 25 | Get-AzCosmosDBGremlinDatabase -ResourceGroupName $resourceGroupName ` 26 | -AccountName $accountName -Name $databaseName 27 | 28 | Write-Host "List all graphs in a database" 29 | Get-AzCosmosDBGremlinGraph -ResourceGroupName $resourceGroupName ` 30 | -AccountName $accountName -DatabaseName $databaseName 31 | 32 | Write-Host "Get a graph in a database" 33 | Get-AzCosmosDBGremlinGraph -ResourceGroupName $resourceGroupName ` 34 | -AccountName $accountName -DatabaseName $databaseName ` 35 | -Name $graphName 36 | -------------------------------------------------------------------------------- /virtual-machine/copy-managed-disks-to-same-or-different-subscription/copy-managed-disks-to-same-or-different-subscription.ps1: -------------------------------------------------------------------------------- 1 | #Provide the subscription Id of the subscription where managed disk exists 2 | $sourceSubscriptionId='yourSourceSubscriptionId' 3 | 4 | #Provide the name of your resource group where managed disk exists 5 | $sourceResourceGroupName='mySourceResourceGroupName' 6 | 7 | #Provide the name of the managed disk 8 | $managedDiskName='myDiskName' 9 | 10 | #Set the context to the subscription Id where Managed Disk exists 11 | Select-AzSubscription -SubscriptionId $sourceSubscriptionId 12 | 13 | #Get the source managed disk 14 | $managedDisk= Get-AzDisk -ResourceGroupName $sourceResourceGroupName -DiskName $managedDiskName 15 | 16 | #Provide the subscription Id of the subscription where managed disk will be copied to 17 | #If managed disk is copied to the same subscription then you can skip this step 18 | $targetSubscriptionId='yourTargetSubscriptionId' 19 | 20 | #Name of the resource group where snapshot will be copied to 21 | $targetResourceGroupName='myTargetResourceGroupName' 22 | 23 | #Set the context to the subscription Id where managed disk will be copied to 24 | #If snapshot is copied to the same subscription then you can skip this step 25 | Select-AzSubscription -SubscriptionId $targetSubscriptionId 26 | 27 | $diskConfig = New-AzDiskConfig -SourceResourceId $managedDisk.Id -Location $managedDisk.Location -CreateOption Copy 28 | 29 | #Create a new managed disk in the target subscription and resource group 30 | New-AzDisk -Disk $diskConfig -DiskName $managedDiskName -ResourceGroupName $targetResourceGroupName 31 | -------------------------------------------------------------------------------- /cosmosdb/sql/ps-sql-list-get.ps1: -------------------------------------------------------------------------------- 1 | # Reference: Az.CosmosDB | https://docs.microsoft.com/powershell/module/az.cosmosdb 2 | # -------------------------------------------------- 3 | # Purpose 4 | # Show list and get operations for accounts, databases, and containers 5 | # -------------------------------------------------- 6 | # Variables - ***** SUBSTITUTE YOUR VALUES ***** 7 | $resourceGroupName = "myResourceGroup" # Resource Group must already exist 8 | $accountName = "myaccount" # Must be all lower case 9 | $databaseName = "myDatabase" 10 | $containerName = "myContainer" 11 | # -------------------------------------------------- 12 | 13 | Write-Host "List all accounts in a resource group" 14 | Get-AzCosmosDBAccount -ResourceGroupName $resourceGroupName 15 | 16 | Write-Host "Get an account in a resource group" 17 | Get-AzCosmosDBAccount -ResourceGroupName $resourceGroupName ` 18 | -Name $accountName 19 | 20 | Write-Host "List all databases in an account" 21 | Get-AzCosmosDBSqlDatabase -ResourceGroupName $resourceGroupName ` 22 | -AccountName $accountName 23 | 24 | Write-Host "Get a database in an account" 25 | Get-AzCosmosDBSqlDatabase -ResourceGroupName $resourceGroupName ` 26 | -AccountName $accountName -Name $databaseName 27 | 28 | Write-Host "List all containers in an database" 29 | Get-AzCosmosDBSqlContainer -ResourceGroupName $resourceGroupName ` 30 | -AccountName $accountName -DatabaseName $databaseName 31 | 32 | Write-Host "Get a container in a database" 33 | Get-AzCosmosDBSqlContainer -ResourceGroupName $resourceGroupName ` 34 | -AccountName $accountName -DatabaseName $databaseName ` 35 | -Name $containerName 36 | -------------------------------------------------------------------------------- /cosmosdb/cassandra/ps-cassandra-list-get.ps1: -------------------------------------------------------------------------------- 1 | # Reference: Az.CosmosDB | https://docs.microsoft.com/powershell/module/az.cosmosdb 2 | # -------------------------------------------------- 3 | # Purpose 4 | # Show list and get operations for accounts, keyspaces, and tables 5 | # -------------------------------------------------- 6 | # Variables - ***** SUBSTITUTE YOUR VALUES ***** 7 | $resourceGroupName = "myResourceGroup" # Resource Group must already exist 8 | $accountName = "myaccount" # Must be all lower case 9 | $keyspaceName = "mykeyspace" 10 | $tableName = "mytable" 11 | # -------------------------------------------------- 12 | 13 | Write-Host "List all accounts in a resource group" 14 | Get-AzCosmosDBAccount -ResourceGroupName $resourceGroupName 15 | 16 | Write-Host "Get an account in a resource group" 17 | Get-AzCosmosDBAccount -ResourceGroupName $resourceGroupName ` 18 | -Name $accountName 19 | 20 | Write-Host "List all keyspaces in an account" 21 | Get-AzCosmosDBCassandraKeyspace -ResourceGroupName $resourceGroupName ` 22 | -AccountName $accountName 23 | 24 | Write-Host "Get a keyspace in an account" 25 | Get-AzCosmosDBCassandraKeyspace -ResourceGroupName $resourceGroupName ` 26 | -AccountName $accountName -Name $keyspaceName 27 | 28 | Write-Host "List all tables in a keyspace" 29 | Get-AzCosmosDBCassandraTable -ResourceGroupName $resourceGroupName ` 30 | -AccountName $accountName -KeyspaceName $keyspaceName 31 | 32 | Write-Host "Get a table in a keyspace" 33 | Get-AzCosmosDBCassandraTable -ResourceGroupName $resourceGroupName ` 34 | -AccountName $accountName -KeyspaceName $keyspaceName ` 35 | -Name $tableName 36 | -------------------------------------------------------------------------------- /devtest-lab/create-custom-image-from-vhd/create-custom-image-from-vhd.ps1: -------------------------------------------------------------------------------- 1 | 2 | # Select the desired Azure subscription. 3 | $subscriptionId = '' 4 | Select-AzSubscription -SubscriptionId $subscriptionId 5 | 6 | # Get the lab object. 7 | $labRg = '' 8 | $labName = '' 9 | $lab = Get-AzResource -ResourceId ('/subscriptions/' + $subscriptionId + '/resourceGroups/' + $labRg + '/providers/Microsoft.DevTestLab/labs/' + $labName) 10 | 11 | # Get the lab storage account and lab storage account key values. 12 | $labStorageAccount = Get-AzResource -ResourceId $lab.Properties.defaultStorageAccount 13 | $labStorageAccountKey = (Get-AzStorageAccountKey -ResourceGroupName $labStorageAccount.ResourceGroupName -Name $labStorageAccount.ResourceName)[0].Value 14 | 15 | # Set the URI of the VHD file. 16 | $vhdUri = '' 17 | 18 | # Set the custom image name and description values. 19 | $customImageName = '' 20 | $customImageDescription = '' 21 | 22 | # Set up the parameters object. 23 | $parameters = @{existingLabName="$($lab.Name)"; existingVhdUri=$vhdUri; imageOsType='windows'; isVhdSysPrepped=$false; imageName=$customImageName; imageDescription=$customImageDescription} 24 | 25 | # Create the custom image. 26 | New-AzResourceGroupDeployment -ResourceGroupName $lab.ResourceGroupName -Name CreateCustomImage -TemplateUri 'https://raw.githubusercontent.com/Azure/azure-devtestlab/master/Samples/201-dtl-create-customimage-from-vhd/azuredeploy.json' -TemplateParameterObject $parameters 27 | -------------------------------------------------------------------------------- /cosmosdb/mongodb/ps-mongodb-list-get.ps1: -------------------------------------------------------------------------------- 1 | # Reference: Az.CosmosDB | https://docs.microsoft.com/powershell/module/az.cosmosdb 2 | # -------------------------------------------------- 3 | # Purpose 4 | # Show list and get operations for accounts, databases, and collections 5 | # -------------------------------------------------- 6 | # Variables - ***** SUBSTITUTE YOUR VALUES ***** 7 | $resourceGroupName = "myResourceGroup" # Resource Group must already exist 8 | $accountName = "myaccount" # Must be all lower case 9 | $databaseName = "myDatabase" 10 | $collectionName = "myCollection" 11 | # -------------------------------------------------- 12 | 13 | Write-Host "List all accounts in a resource group" 14 | Get-AzCosmosDBAccount -ResourceGroupName $resourceGroupName 15 | 16 | Write-Host "Get an account in a resource group" 17 | Get-AzCosmosDBAccount -ResourceGroupName $resourceGroupName ` 18 | -Name $accountName 19 | 20 | Write-Host "List all databases in an account" 21 | Get-AzCosmosDBMongoDBDatabase -ResourceGroupName $resourceGroupName ` 22 | -AccountName $accountName 23 | 24 | Write-Host "Get a database in an account" 25 | Get-AzCosmosDBMongoDBDatabase -ResourceGroupName $resourceGroupName ` 26 | -AccountName $accountName -Name $databaseName 27 | 28 | Write-Host "List all collections in a database" 29 | Get-AzCosmosDBMongoDBCollection -ResourceGroupName $resourceGroupName ` 30 | -AccountName $accountName -DatabaseName $databaseName 31 | 32 | Write-Host "Get a collection in a database" 33 | Get-AzCosmosDBMongoDBCollection -ResourceGroupName $resourceGroupName ` 34 | -AccountName $accountName -DatabaseName $databaseName ` 35 | -Name $collectionName 36 | -------------------------------------------------------------------------------- /cosmosdb/cassandra/ps-cassandra-ru-update.ps1: -------------------------------------------------------------------------------- 1 | # Reference: Az.CosmosDB | https://docs.microsoft.com/powershell/module/az.cosmosdb 2 | # -------------------------------------------------- 3 | # Purpose 4 | # Update table throughput 5 | # -------------------------------------------------- 6 | # Variables - ***** SUBSTITUTE YOUR VALUES ***** 7 | $resourceGroupName = "myResourceGroup" # Resource Group must already exist 8 | $accountName = "myaccount" # Must be all lower case 9 | $keyspaceName = "mykeyspace" 10 | $tableName = "mytable" 11 | $newRUs = 500 12 | # -------------------------------------------------- 13 | $throughput = Get-AzCosmosDBCassandraTableThroughput -ResourceGroupName $resourceGroupName ` 14 | -AccountName $accountName -KeyspaceName $keyspaceName -Name $tableName 15 | 16 | $currentRUs = $throughput.Throughput 17 | $minimumRUs = $throughput.MinimumThroughput 18 | 19 | Write-Host "Current throughput is $currentRUs. Minimum allowed throughput is $minimumRUs." 20 | 21 | if ([int]$newRUs -lt [int]$minimumRUs) { 22 | Write-Host "Requested new throughput of $newRUs is less than minimum allowed throughput of $minimumRUs." 23 | Write-Host "Using minimum allowed throughput of $minimumRUs instead." 24 | $newRUs = $minimumRUs 25 | } 26 | 27 | if ([int]$newRUs -eq [int]$currentRUs) { 28 | Write-Host "New throughput is the same as current throughput. No change needed." 29 | } 30 | else { 31 | Write-Host "Updating throughput to $newRUs." 32 | 33 | Update-AzCosmosDBCassandraTableThroughput -ResourceGroupName $resourceGroupName ` 34 | -AccountName $accountName -KeyspaceName $keyspaceName ` 35 | -Name $tableName -Throughput $newRUs 36 | } 37 | -------------------------------------------------------------------------------- /azure-migrate/SQL Migration/Update-ClusterConfig.ps1: -------------------------------------------------------------------------------- 1 | <# 2 | .PERMISSIONS REQUIRED 3 | Cluster administrator 4 | .USE CASES 5 | Run this scripts on any cluster node to update the cluster IPs to the new configuration from the config file path. 6 | .Parameters 7 | $configFilePath - path to the configuration file previously created from the cluster 8 | 9 | .NOTES 10 | AUTHOR: Microsoft Services 11 | AUTHOR DATE: 2021-04-23 12 | .CHANGE LOG 13 | #> 14 | param( 15 | [Parameter(Mandatory=$true)] 16 | [string] 17 | $configFilePath) 18 | $resourcelist=Import-Csv -Path $configFilePath 19 | 20 | import-module Failoverclusters 21 | $Networks=Get-ClusterNetwork 22 | If ($Networks.Count -gt 1) 23 | { 24 | $ClusterNetworkName=($Networks | out-gridview -passthru).Name 25 | } 26 | else 27 | { 28 | $ClusterNetworkName = $Networks.Name 29 | } 30 | foreach ($resource in $resourcelist) 31 | { 32 | "Configuring $($resource.ResourceName) with $($resource.NewIP) IP : $($resource.ProbePort) on network $ClusterNetworkName." 33 | Get-ClusterResource $resource.ResourceName | stop-ClusterResource 34 | Get-ClusterResource $resource.ResourceName | Set-ClusterParameter -Multiple @{"Address"="$($resource.NewIP)";"ProbePort"=$resource.ProbePort;"SubnetMask"="255.255.255.255";"Network"="$ClusterNetworkName";"EnableDhcp"=0} 35 | Get-ClusterResource $resource.ResourceName | stop-ClusterResource 36 | Get-ClusterResource $resource.ResourceName | Set-ClusterParameter -Multiple @{"Address"="$($resource.NewIP)";"ProbePort"=$resource.ProbePort;"SubnetMask"="255.255.255.255";"Network"="$ClusterNetworkName";"EnableDhcp"=0} 37 | Get-ClusterResource $resource.ResourceName | start-ClusterResource 38 | } 39 | -------------------------------------------------------------------------------- /cosmosdb/sql/ps-sql-ru-update.ps1: -------------------------------------------------------------------------------- 1 | # Reference: Az.CosmosDB | https://docs.microsoft.com/powershell/module/az.cosmosdb 2 | # -------------------------------------------------- 3 | # Purpose 4 | # Update container throughput 5 | # -------------------------------------------------- 6 | # Variables - ***** SUBSTITUTE YOUR VALUES ***** 7 | $resourceGroupName = "myResourceGroup" # Resource Group must already exist 8 | $accountName = "myaccount" # Must be all lower case 9 | $databaseName = "myDatabase" 10 | $containerName = "myContainer" 11 | $newRUs = 500 12 | # -------------------------------------------------- 13 | 14 | $throughput = Get-AzCosmosDBSqlContainerThroughput -ResourceGroupName $resourceGroupName ` 15 | -AccountName $accountName -DatabaseName $databaseName -Name $containerName 16 | 17 | $currentRUs = $throughput.Throughput 18 | $minimumRUs = $throughput.MinimumThroughput 19 | 20 | Write-Host "Current throughput is $currentRUs. Minimum allowed throughput is $minimumRUs." 21 | 22 | if ([int]$newRUs -lt [int]$minimumRUs) { 23 | Write-Host "Requested new throughput of $newRUs is less than minimum allowed throughput of $minimumRUs." 24 | Write-Host "Using minimum allowed throughput of $minimumRUs instead." 25 | $newRUs = $minimumRUs 26 | } 27 | 28 | if ([int]$newRUs -eq [int]$currentRUs) { 29 | Write-Host "New throughput is the same as current throughput. No change needed." 30 | } 31 | else { 32 | Write-Host "Updating throughput to $newRUs." 33 | 34 | Update-AzCosmosDBSqlContainerThroughput -ResourceGroupName $resourceGroupName ` 35 | -AccountName $accountName -DatabaseName $databaseName ` 36 | -Name $containerName -Throughput $newRUs 37 | } 38 | -------------------------------------------------------------------------------- /cosmosdb/gremlin/ps-gremlin-ru-update.ps1: -------------------------------------------------------------------------------- 1 | # Reference: Az.CosmosDB | https://docs.microsoft.com/powershell/module/az.cosmosdb 2 | # -------------------------------------------------- 3 | # Purpose 4 | # Update graph throughput 5 | # -------------------------------------------------- 6 | # Variables - ***** SUBSTITUTE YOUR VALUES ***** 7 | $resourceGroupName = "myResourceGroup" # Resource Group must already exist 8 | $accountName = "myaccount" # Must be all lower case 9 | $databaseName = "myDatabase" 10 | $graphName = "myGraph" 11 | $newRUs = 500 12 | # -------------------------------------------------- 13 | 14 | $throughput = Get-AzCosmosDBGremlinGraphThroughput ` 15 | -ResourceGroupName $resourceGroupName ` 16 | -AccountName $accountName -DatabaseName $databaseName ` 17 | -Name $graphName 18 | 19 | $currentRUs = $throughput.Throughput 20 | $minimumRUs = $throughput.MinimumThroughput 21 | 22 | Write-Host "Current throughput is $currentRUs. Minimum allowed throughput is $minimumRUs." 23 | 24 | if ([int]$newRUs -lt [int]$minimumRUs) { 25 | Write-Host "Requested new throughput of $newRUs is less than minimum allowed throughput of $minimumRUs." 26 | Write-Host "Using minimum allowed throughput of $minimumRUs instead." 27 | $newRUs = $minimumRUs 28 | } 29 | 30 | if ([int]$newRUs -eq [int]$currentRUs) { 31 | Write-Host "New throughput is the same as current throughput. No change needed." 32 | } 33 | else { 34 | Write-Host "Updating throughput to $newRUs." 35 | 36 | Update-AzCosmosDBGremlinGraphThroughput -ResourceGroupName $resourceGroupName ` 37 | -AccountName $accountName -DatabaseName $databaseName ` 38 | -Name $graphName -Throughput $newRUs 39 | } 40 | -------------------------------------------------------------------------------- /cosmosdb/mongodb/ps-mongodb-ru-update.ps1: -------------------------------------------------------------------------------- 1 | # Reference: Az.CosmosDB | https://docs.microsoft.com/powershell/module/az.cosmosdb 2 | # -------------------------------------------------- 3 | # Purpose 4 | # Update collection throughput 5 | # -------------------------------------------------- 6 | # Variables - ***** SUBSTITUTE YOUR VALUES ***** 7 | $resourceGroupName = "myResourceGroup" # Resource Group must already exist 8 | $accountName = "myaccount" # Must be all lower case 9 | $databaseName = "myDatabase" 10 | $collectionName = "myCollection" 11 | $newRUs = 500 12 | # -------------------------------------------------- 13 | 14 | $throughput = Get-AzCosmosDBMongoDBCollectionThroughput -ResourceGroupName $resourceGroupName ` 15 | -AccountName $accountName -DatabaseName $databaseName -Name $collectionName 16 | 17 | $currentRUs = $throughput.Throughput 18 | $minimumRUs = $throughput.MinimumThroughput 19 | 20 | Write-Host "Current throughput is $currentRUs. Minimum allowed throughput is $minimumRUs." 21 | 22 | if ([int]$newRUs -lt [int]$minimumRUs) { 23 | Write-Host "Requested new throughput of $newRUs is less than minimum allowed throughput of $minimumRUs." 24 | Write-Host "Using minimum allowed throughput of $minimumRUs instead." 25 | $newRUs = $minimumRUs 26 | } 27 | 28 | if ([int]$newRUs -eq [int]$currentRUs) { 29 | Write-Host "New throughput is the same as current throughput. No change needed." 30 | } 31 | else { 32 | Write-Host "Updating throughput to $newRUs." 33 | 34 | Update-AzCosmosDBMongoDBCollectionThroughput -ResourceGroupName $resourceGroupName ` 35 | -AccountName $accountName -DatabaseName $databaseName ` 36 | -Name $collectionName -Throughput $newRUs 37 | } 38 | -------------------------------------------------------------------------------- /cosmosdb/gremlin/ps-gremlin-ru-migrate.ps1: -------------------------------------------------------------------------------- 1 | # Reference: Az.CosmosDB | https://docs.microsoft.com/powershell/module/az.cosmosdb 2 | # -------------------------------------------------- 3 | # Purpose 4 | # Migrate a database or graph to autoscale or standard (manual) throughput 5 | # -------------------------------------------------- 6 | # Variables - ***** SUBSTITUTE YOUR VALUES ***** 7 | $resourceGroupName = "myResourceGroup" # Resource Group must already exist 8 | $accountName = "myaccount" # Must be all lower case 9 | $databaseName = "myDatabase" 10 | $graphName = "myGraph" 11 | # -------------------------------------------------- 12 | 13 | Write-Host "Migrate database with standard throughput to autoscale throughput." 14 | Invoke-AzCosmosDBGremlinDatabaseThroughputMigration -ResourceGroupName $resourceGroupName ` 15 | -AccountName $accountName -Name $databaseName -ThroughputType Autoscale 16 | 17 | Write-Host "Migrate database with autoscale throughput to standard throughput." 18 | Invoke-AzCosmosDBGremlinDatabaseThroughputMigration -ResourceGroupName $resourceGroupName ` 19 | -AccountName $accountName -Name $databaseName -ThroughputType Manual 20 | 21 | Write-Host "Migrate graph with standard throughput to autoscale throughput." 22 | Invoke-AzCosmosDBGremlinGraphThroughputMigration -ResourceGroupName $resourceGroupName ` 23 | -AccountName $accountName -DatabaseName $databaseName -Name $graphName -ThroughputType Autoscale 24 | 25 | Write-Host "Migrate graph with autoscale throughput to standard throughput." 26 | Invoke-AzCosmosDBGremlinGraphThroughputMigration -ResourceGroupName $resourceGroupName ` 27 | -AccountName $accountName -DatabaseName $databaseName -Name $graphName -ThroughputType Manual 28 | -------------------------------------------------------------------------------- /cosmosdb/common/ps-account-update-region.ps1: -------------------------------------------------------------------------------- 1 | # Reference: Az.CosmosDB | https://docs.microsoft.com/powershell/module/az.cosmosdb 2 | # -------------------------------------------------- 3 | # Purpose 4 | # Update Cosmos DB account: Add an Azure region (location) 5 | # NOTE: if adding a region to a single master account, do not change the first 6 | # region in the same operation. Change failover priority order in a 7 | # separate operation. 8 | # NOTE: this operation will return, but account updates may still be 9 | # occurring. Check the account or Resource Group's activity log for status. 10 | # -------------------------------------------------- 11 | # Variables - ***** SUBSTITUTE YOUR VALUES ***** 12 | $resourceGroupName = "myResourceGroup" # Resource Group must already exist 13 | $accountName = "myaccount" # Must be all lower case 14 | 15 | # Regions ordered by failover priority, with each indicating whether AZ-enabled 16 | # Region AZ status can be checked at https://azure.microsoft.com/global-infrastructure/regions/ 17 | $locations = @( 18 | @{name = "East US"; azEnabled = $true}; 19 | @{name = "West US"; azEnabled = $false}; 20 | ) 21 | # -------------------------------------------------- 22 | 23 | Write-Host "Get Cosmos DB account" 24 | $account = Get-AzCosmosDBAccount -ResourceGroupName $resourceGroupName -Name $accountName 25 | 26 | $i = 0 27 | $locationObjects = @() 28 | 29 | ForEach ($location in $locations) { 30 | $locationObjects += New-AzCosmosDBLocationObject -LocationName $location.name -IsZoneRedundant $location.azEnabled -FailoverPriority ($i++) 31 | } 32 | 33 | Write-Host "Update Cosmos DB account region(s)" 34 | Update-AzCosmosDBAccountRegion -InputObject $account -LocationObject $locationObjects 35 | -------------------------------------------------------------------------------- /cosmosdb/sql/ps-sql-ru-migrate.ps1: -------------------------------------------------------------------------------- 1 | # Reference: Az.CosmosDB | https://docs.microsoft.com/powershell/module/az.cosmosdb 2 | # -------------------------------------------------- 3 | # Purpose 4 | # Migrate a database or container to autoscale or standard (manual) throughput 5 | # -------------------------------------------------- 6 | # Variables - ***** SUBSTITUTE YOUR VALUES ***** 7 | $resourceGroupName = "myResourceGroup" # Resource Group must already exist 8 | $accountName = "myaccount" # Must be all lower case 9 | $databaseName = "myDatabase" 10 | $containerName = "myContainer" 11 | # -------------------------------------------------- 12 | 13 | Write-Host "Migrate database with standard throughput to autoscale throughput." 14 | Invoke-AzCosmosDBSqlDatabaseThroughputMigration -ResourceGroupName $resourceGroupName ` 15 | -AccountName $accountName -Name $databaseName -ThroughputType Autoscale 16 | 17 | Write-Host "Migrate database with autoscale throughput to standard throughput." 18 | Invoke-AzCosmosDBSqlDatabaseThroughputMigration -ResourceGroupName $resourceGroupName ` 19 | -AccountName $accountName -Name $databaseName -ThroughputType Manual 20 | 21 | Write-Host "Migrate container with standard throughput to autoscale throughput." 22 | Invoke-AzCosmosDBSqlContainerThroughputMigration -ResourceGroupName $resourceGroupName ` 23 | -AccountName $accountName -DatabaseName $databaseName -Name $containerName -ThroughputType Autoscale 24 | 25 | Write-Host "Migrate container with autoscale throughput to standard throughput." 26 | Invoke-AzCosmosDBSqlContainerThroughputMigration -ResourceGroupName $resourceGroupName ` 27 | -AccountName $accountName -DatabaseName $databaseName -Name $containerName -ThroughputType Manual 28 | -------------------------------------------------------------------------------- /cosmosdb/cassandra/ps-cassandra-ru-migrate.ps1: -------------------------------------------------------------------------------- 1 | # Reference: Az.CosmosDB | https://docs.microsoft.com/powershell/module/az.cosmosdb 2 | # -------------------------------------------------- 3 | # Purpose 4 | # Migrate a keyspace or table to autoscale or standard (manual) throughput 5 | # -------------------------------------------------- 6 | # Variables - ***** SUBSTITUTE YOUR VALUES ***** 7 | $resourceGroupName = "myResourceGroup" # Resource Group must already exist 8 | $accountName = "myaccount" # Must be all lower case 9 | $keyspaceName = "myKeyspace" 10 | $tableName = "myTable" 11 | # -------------------------------------------------- 12 | 13 | Write-Host "Migrate keyspace with standard throughput to autoscale throughput." 14 | Invoke-AzCosmosDBCassandraKeyspaceThroughputMigration -ResourceGroupName $resourceGroupName ` 15 | -AccountName $accountName -Name $keyspaceName -ThroughputType Autoscale 16 | 17 | Write-Host "Migrate keyspace with autoscale throughput to standard throughput." 18 | 19 | Invoke-AzCosmosDBCassandraKeyspaceThroughputMigration -ResourceGroupName $resourceGroupName ` 20 | -AccountName $accountName -Name $keyspaceName -ThroughputType Manual 21 | 22 | Write-Host "Migrate table with standard throughput to autoscale throughput." 23 | Invoke-AzCosmosDBCassandraTableThroughputMigration -ResourceGroupName $resourceGroupName ` 24 | -AccountName $accountName -KeyspaceName $keyspaceName -Name $tableName -ThroughputType Autoscale 25 | 26 | Write-Host "Migrate table with autoscale throughput to standard throughput." 27 | Invoke-AzCosmosDBCassandraTableThroughputMigration -ResourceGroupName $resourceGroupName ` 28 | -AccountName $accountName -KeyspaceName $keyspaceName -Name $tableName -ThroughputType Manual 29 | -------------------------------------------------------------------------------- /virtual-machine-scale-sets/use-data-disks/use-data-disks.ps1: -------------------------------------------------------------------------------- 1 | # Provide your own secure password for use with the VM instances 2 | $cred = Get-Credential 3 | 4 | # Create a virtual machine scale set and supporting resources 5 | # A resource group, virtual network, load balancer, and NAT rules are automatically 6 | # created if they do not already exist 7 | New-AzVmss ` 8 | -ResourceGroupName "myResourceGroup" ` 9 | -VMScaleSetName "myScaleSet" ` 10 | -Location "EastUS" ` 11 | -VirtualNetworkName "myVnet" ` 12 | -SubnetName "mySubnet" ` 13 | -PublicIpAddressName "myPublicIPAddress" ` 14 | -LoadBalancerName "myLoadBalancer" ` 15 | -Credential $cred ` 16 | -UpgradePolicyMode "Automatic" ` 17 | -DataDiskSizeInGb 64,128 18 | 19 | # Get scale set object 20 | $vmss = Get-AzVmss ` 21 | -ResourceGroupName "myResourceGroup" ` 22 | -VMScaleSetName "myScaleSet" 23 | 24 | # Set the URI of a custom script that prepares any attached disks 25 | $publicSettings = @{ 26 | "fileUris" = (,"https://raw.githubusercontent.com/Azure-Samples/compute-automation-configurations/master/prepare_vm_disks.ps1"); 27 | "commandToExecute" = "powershell -ExecutionPolicy Unrestricted -File prepare_vm_disks.ps1" 28 | } 29 | 30 | # Use Custom Script Extension to prepare the attached data disks 31 | Add-AzVmssExtension -VirtualMachineScaleSet $vmss ` 32 | -Name "customScript" ` 33 | -Publisher "Microsoft.Compute" ` 34 | -Type "CustomScriptExtension" ` 35 | -TypeHandlerVersion 1.8 ` 36 | -Setting $publicSettings 37 | 38 | # Update the scale set and apply the Custom Script Extension to the VM instances 39 | Update-AzVmss ` 40 | -ResourceGroupName "myResourceGroup" ` 41 | -Name "myScaleSet" ` 42 | -VirtualMachineScaleSet $vmss 43 | -------------------------------------------------------------------------------- /site-recovery/dr-at-scale-onpremise-azure/asr_template.ps1: -------------------------------------------------------------------------------- 1 | Param( 2 | [parameter(Mandatory=$true)] 3 | $CsvFilePath 4 | ) 5 | 6 | $ErrorActionPreference = "Stop" 7 | 8 | $scriptsPath = $PSScriptRoot 9 | if ($PSScriptRoot -eq "") { 10 | $scriptsPath = "." 11 | } 12 | 13 | . "$scriptsPath\asr_logger.ps1" 14 | . "$scriptsPath\asr_common.ps1" 15 | . "$scriptsPath\asr_csv_processor.ps1" 16 | 17 | Function ProcessItemImpl($processor, $csvItem, $reportItem) { 18 | #Add additional fields to the $reportItem object to report execution details 19 | #It will be included in the out....csv reporting file 20 | $reportItem | Add-Member NoteProperty "AdditionalInfoForReporting" $null 21 | $processor.Logger.LogTrace("Sample log - $($csvItem.SOURCE_MACHINE_NAME)") 22 | $reportItem.AdditionalInfoForReporting = "test_info" 23 | } 24 | 25 | Function ProcessItem($processor, $csvItem, $reportItem) { 26 | try { 27 | #This method will be invoked for each row in the CSV file 28 | ProcessItemImpl $processor $csvItem $reportItem 29 | } 30 | catch { 31 | $exceptionMessage = $_ | Out-String 32 | $processor.Logger.LogError($exceptionMessage) 33 | throw 34 | } 35 | } 36 | 37 | #logger to report information in file 'out...txt' 38 | $logger = New-AsrLoggerInstance -CommandPath $PSCommandPath 39 | 40 | #common functions to interact with Azure Site Recovery cmdlets 41 | $asrCommon = New-AsrCommonInstance -Logger $logger 42 | 43 | #Common implementation to process the CsvFile and invoke the function for each row 44 | $processor = New-CsvProcessorInstance -Logger $logger -ProcessItemFunction $function:ProcessItem 45 | $processor.ProcessFile($CsvFilePath) 46 | -------------------------------------------------------------------------------- /container-registry/service-principal-create/service-principal-create.ps1: -------------------------------------------------------------------------------- 1 | # This sample requires the Az PowerShell module version 7.x or higher. 2 | 3 | # Modify for your environment. The 'registryName' is the name of your Azure 4 | # Container Registry, the 'resourceGroup' is the name of the resource group 5 | # in which your registry resides, and the 'servicePrincipalName' can be any 6 | # unique name within your subscription (you can use the default below). 7 | $registryName = '' 8 | $resourceGroup = '' 9 | $servicePrincipalName = 'acr-service-principal' 10 | 11 | # Get a reference to the container registry; need its fully qualified ID 12 | # when assigning the role to the principal in a subsequent command. 13 | $registry = Get-AzContainerRegistry -ResourceGroupName $resourceGroup -Name $registryName 14 | 15 | # Create the service principal 16 | $sp = New-AzADServicePrincipal -DisplayName $servicePrincipalName 17 | 18 | # Sleep a few seconds to allow the service principal to propagate throughout 19 | # Azure Active Directory 20 | Start-Sleep -Seconds 30 21 | 22 | # Assign the role to the service principal. Default permissions are for docker 23 | # pull access. Modify the 'RoleDefinitionName' argument value as desired: 24 | # acrpull: pull only 25 | # acrpush: push and pull 26 | # Owner: push, pull, and assign roles 27 | New-AzRoleAssignment -ObjectId $sp.Id -RoleDefinitionName acrpull -Scope $registry.Id 28 | 29 | # Output the service principal's credentials; use these in your services and 30 | # applications to authenticate to the container registry. 31 | Write-Output "Service principal App ID: $($sp.AppId)" 32 | Write-Output "Service principal password: $($sp.PasswordCredentials.SecretText)" 33 | -------------------------------------------------------------------------------- /cosmosdb/mongodb/ps-mongodb-ru-migrate.ps1: -------------------------------------------------------------------------------- 1 | # Reference: Az.CosmosDB | https://docs.microsoft.com/powershell/module/az.cosmosdb 2 | # -------------------------------------------------- 3 | # Purpose 4 | # Migrate a database or collection to autoscale or standard (manual) throughput 5 | # -------------------------------------------------- 6 | # Variables - ***** SUBSTITUTE YOUR VALUES ***** 7 | $resourceGroupName = "myResourceGroup" # Resource Group must already exist 8 | $accountName = "myaccount" # Must be all lower case 9 | $databaseName = "myDatabase" 10 | $collectionName = "myCollection" 11 | # -------------------------------------------------- 12 | 13 | Write-Host "Migrate database with standard throughput to autoscale throughput." 14 | Invoke-AzCosmosDBMongoDBDatabaseThroughputMigration -ResourceGroupName $resourceGroupName ` 15 | -AccountName $accountName -Name $databaseName -ThroughputType Autoscale 16 | 17 | Write-Host "Migrate database with autoscale throughput to standard throughput." 18 | Invoke-AzCosmosDBMongoDBDatabaseThroughputMigration -ResourceGroupName $resourceGroupName ` 19 | -AccountName $accountName -Name $databaseName -ThroughputType Manual 20 | 21 | Write-Host "Migrate collection with standard throughput to autoscale throughput." 22 | Invoke-AzCosmosDBMongoDBCollectionThroughputMigration -ResourceGroupName $resourceGroupName ` 23 | -AccountName $accountName -DatabaseName $databaseName -Name $collectionName -ThroughputType Autoscale 24 | 25 | Write-Host "Migrate collection with autoscale throughput to standard throughput." 26 | Invoke-AzCosmosDBMongoDBCollectionThroughputMigration -ResourceGroupName $resourceGroupName ` 27 | -AccountName $accountName -DatabaseName $databaseName -Name $collectionName -ThroughputType Manual 28 | -------------------------------------------------------------------------------- /azure-migrate/migrate-at-scale-with-site-recovery/asr_template.ps1: -------------------------------------------------------------------------------- 1 | Param( 2 | [parameter(Mandatory=$true)] 3 | $CsvFilePath 4 | ) 5 | 6 | $ErrorActionPreference = "Stop" 7 | 8 | $scriptsPath = $PSScriptRoot 9 | if ($PSScriptRoot -eq "") { 10 | $scriptsPath = "." 11 | } 12 | 13 | . "$scriptsPath\asr_logger.ps1" 14 | . "$scriptsPath\asr_common.ps1" 15 | . "$scriptsPath\asr_csv_processor.ps1" 16 | 17 | Function ProcessItemImpl($processor, $csvItem, $reportItem) { 18 | #Add additional fields to the $reportItem object to report execution details 19 | #It will be included in the out....csv reporting file 20 | $reportItem | Add-Member NoteProperty "AdditionalInfoForReporting" $null 21 | $processor.Logger.LogTrace("Sample log - $($csvItem.SOURCE_MACHINE_NAME)") 22 | $reportItem.AdditionalInfoForReporting = "test_info" 23 | } 24 | 25 | Function ProcessItem($processor, $csvItem, $reportItem) { 26 | try { 27 | #This method will be invoked for each row in the CSV file 28 | ProcessItemImpl $processor $csvItem $reportItem 29 | } 30 | catch { 31 | $exceptionMessage = $_ | Out-String 32 | $processor.Logger.LogError($exceptionMessage) 33 | throw 34 | } 35 | } 36 | 37 | #logger to report information in file 'out...txt' 38 | $logger = New-AsrLoggerInstance -CommandPath $PSCommandPath 39 | 40 | #common functions to interact with Azure Site Recovery cmdlets 41 | $asrCommon = New-AsrCommonInstance -Logger $logger 42 | 43 | #Common implementation to process the CsvFile and invoke the function for each row 44 | $processor = New-CsvProcessorInstance -Logger $logger -ProcessItemFunction $function:ProcessItem 45 | $processor.ProcessFile($CsvFilePath) 46 | -------------------------------------------------------------------------------- /app-service/deploy-deployment-slot/deploy-deployment-slot.ps1: -------------------------------------------------------------------------------- 1 | # Replace the following URL with a public GitHub repo URL 2 | $gitrepo="https://github.com/Azure-Samples/app-service-web-dotnet-get-started.git" 3 | $webappname="mywebapp$(Get-Random)" 4 | $location="West Europe" 5 | 6 | # Create a resource group. 7 | New-AzResourceGroup -Name myResourceGroup -Location $location 8 | 9 | # Create an App Service plan in Free tier. 10 | New-AzAppServicePlan -Name $webappname -Location $location ` 11 | -ResourceGroupName myResourceGroup -Tier Free 12 | 13 | # Create a web app. 14 | New-AzWebApp -Name $webappname -Location $location ` 15 | -AppServicePlan $webappname -ResourceGroupName myResourceGroup 16 | 17 | # Upgrade App Service plan to Standard tier (minimum required by deployment slots) 18 | Set-AzAppServicePlan -Name $webappname -ResourceGroupName myResourceGroup ` 19 | -Tier Standard 20 | 21 | #Create a deployment slot with the name "staging". 22 | New-AzWebAppSlot -Name $webappname -ResourceGroupName myResourceGroup ` 23 | -Slot staging 24 | 25 | # Configure GitHub deployment to the staging slot from your GitHub repo and deploy once. 26 | $PropertiesObject = @{ 27 | repoUrl = "$gitrepo"; 28 | branch = "master"; 29 | isManualIntegration = "true"; #remove isManualIntegration for continuous deployment from a GitHub repo you own 30 | } 31 | Set-AzResource -PropertyObject $PropertiesObject -ResourceGroupName myResourceGroup ` 32 | -ResourceType Microsoft.Web/sites/slots/sourcecontrols ` 33 | -ResourceName $webappname/staging/web -ApiVersion 2015-08-01 -Force 34 | 35 | # Swap the verified/warmed up staging slot into production. 36 | Switch-AzWebAppSlot -Name $webappname -ResourceGroupName myResourceGroup ` 37 | -SourceSlotName staging -DestinationSlotName production 38 | -------------------------------------------------------------------------------- /virtual-machine/create-managed-disk-from-snapshot/create-managed-disk-from-snapshot.ps1: -------------------------------------------------------------------------------- 1 | #Provide the subscription Id 2 | $subscriptionId = 'yourSubscriptionId' 3 | 4 | #Provide the name of your resource group 5 | $resourceGroupName ='yourResourceGroupName' 6 | 7 | #Provide the name of the snapshot that will be used to create Managed Disks 8 | $snapshotName = 'yourSnapshotName' 9 | 10 | #Provide the name of the Managed Disk 11 | $diskName = 'yourManagedDiskName' 12 | 13 | #Provide the size of the disks in GB. It should be greater than the VHD file size. 14 | $diskSize = '128' 15 | 16 | #Provide the storage type for Managed Disk. Acceptable values are Standard_LRS, Premium_LRS, PremiumV2_LRS, StandardSSD_LRS, UltraSSD_LRS, Premium_ZRS and StandardSSD_ZRS. 17 | $storageType = 'Premium_LRS' 18 | 19 | #Required for Premium SSD v2 and Ultra Disks 20 | #Provide the Availability Zone you'd like the disk to be created in, default is 1 21 | $zone=1 22 | 23 | #Provide the Azure region (e.g. westus) where Managed Disks will be located. 24 | #This location should be same as the snapshot location 25 | #Get all the Azure location using command below: 26 | #Get-AzLocation 27 | $location = 'westus' 28 | 29 | #Set the context to the subscription Id where Managed Disk will be created 30 | Select-AzSubscription -SubscriptionId $SubscriptionId 31 | 32 | $snapshot = Get-AzSnapshot -ResourceGroupName $resourceGroupName -SnapshotName $snapshotName 33 | 34 | #If you're creating a Premium SSD v2 or an Ultra Disk, add "-Zone $zone" to the end of the command 35 | $diskConfig = New-AzDiskConfig -SkuName $storageType -Location $location -CreateOption Copy -SourceResourceId $snapshot.Id -DiskSizeGB $diskSize 36 |   37 | New-AzDisk -Disk $diskConfig -ResourceGroupName $resourceGroupName -DiskName $diskName 38 | -------------------------------------------------------------------------------- /cosmosdb/table/ps-table-create.ps1: -------------------------------------------------------------------------------- 1 | # Reference: Az.CosmosDB | https://docs.microsoft.com/powershell/module/az.cosmosdb 2 | # -------------------------------------------------- 3 | # Purpose 4 | # Create Cosmos Table API account and a Table with dedicated throughput 5 | # -------------------------------------------------- 6 | Function New-RandomString{Param ([Int]$Length = 10) return $(-join ((97..122) + (48..57) | Get-Random -Count $Length | ForEach-Object {[char]$_}))} 7 | # -------------------------------------------------- 8 | $uniqueId = New-RandomString -Length 7 # Random alphanumeric string for unique resource names 9 | $apiKind = "Table" 10 | # -------------------------------------------------- 11 | # Variables - ***** SUBSTITUTE YOUR VALUES ***** 12 | $locations = @() 13 | $locations += New-AzCosmosDBLocationObject -LocationName "East Us" -FailoverPriority 0 -IsZoneRedundant 0 14 | $locations += New-AzCosmosDBLocationObject -LocationName "West Us" -FailoverPriority 1 -IsZoneRedundant 0 15 | 16 | $resourceGroupName = "myResourceGroup" # Resource Group must already exist 17 | $accountName = "cosmos-$uniqueId" # Must be all lower case 18 | $consistencyLevel = "Session" 19 | $tags = @{Tag1 = "MyTag1"; Tag2 = "MyTag2"; Tag3 = "MyTag3"} 20 | $tableName = "myTable" 21 | $tableRUs = 400 22 | # -------------------------------------------------- 23 | Write-Host "Creating account $accountName" 24 | $account = New-AzCosmosDBAccount -ResourceGroupName $resourceGroupName ` 25 | -LocationObject $locations -Name $accountName -ApiKind $apiKind -Tag $tags ` 26 | -DefaultConsistencyLevel $consistencyLevel ` 27 | -EnableAutomaticFailover:$true 28 | 29 | Write-Host "Creating Table $tableName" 30 | New-AzCosmosDBTable -ParentObject $account ` 31 | -Name $tableName -Throughput $tableRUs 32 | -------------------------------------------------------------------------------- /cosmosdb/table/ps-table-autoscale.ps1: -------------------------------------------------------------------------------- 1 | # Reference: Az.CosmosDB | https://docs.microsoft.com/powershell/module/az.cosmosdb 2 | # -------------------------------------------------- 3 | # Purpose 4 | # Create Cosmos Table API account and a Table with autoscale throughput 5 | # -------------------------------------------------- 6 | Function New-RandomString{Param ([Int]$Length = 10) return $(-join ((97..122) + (48..57) | Get-Random -Count $Length | ForEach-Object {[char]$_}))} 7 | # -------------------------------------------------- 8 | $uniqueId = New-RandomString -Length 7 # Random alphanumeric string for unique resource names 9 | $apiKind = "Table" 10 | # -------------------------------------------------- 11 | # Variables - ***** SUBSTITUTE YOUR VALUES ***** 12 | $locations = @() 13 | $locations += New-AzCosmosDBLocationObject -LocationName "East Us" -FailoverPriority 0 -IsZoneRedundant 0 14 | $locations += New-AzCosmosDBLocationObject -LocationName "West Us" -FailoverPriority 1 -IsZoneRedundant 0 15 | 16 | $resourceGroupName = "mjbArmTest"#"myResourceGroup" # Resource Group must already exist 17 | $accountName = "cosmos-$uniqueId" # Must be all lower case 18 | $consistencyLevel = "Session" 19 | $tableName = "myTable" 20 | $autoscaleMaxThroughput = 4000 #minimum = 4000 21 | # -------------------------------------------------- 22 | Write-Host "Creating account $accountName" 23 | $account = New-AzCosmosDBAccount -ResourceGroupName $resourceGroupName ` 24 | -LocationObject $locations -Name $accountName -ApiKind $apiKind ` 25 | -DefaultConsistencyLevel $consistencyLevel ` 26 | -EnableAutomaticFailover:$true 27 | 28 | Write-Host "Creating Table $tableName" 29 | $table = New-AzCosmosDBTable -ParentObject $account ` 30 | -Name $tableName -AutoscaleMaxThroughput $autoscaleMaxThroughput 31 | -------------------------------------------------------------------------------- /app-service/scale-geographic/scale-geographic.ps1: -------------------------------------------------------------------------------- 1 | 2 | # Generates a Random Value 3 | $Random=(New-Guid).ToString().Substring(0,8) 4 | 5 | # Variables 6 | $ResourceGroupName="myResourceGroup$Random" 7 | $App1Name="AppServiceTM1$Random" 8 | $App2Name="AppServiceTM2$Random" 9 | $Location1="WestUS" 10 | $Location2="EastUS" 11 | 12 | # Create a Resource Group 13 | New-AzResourceGroup -Name $ResourceGroupName -Location $Location1 14 | 15 | # Create Traffic Manager Profile 16 | New-AzTrafficManagerProfile -Name "$ResourceGroupName-tmp" -ResourceGroupName $ResourceGroupName -TrafficRoutingMethod Performance -MonitorPath '/' -MonitorProtocol "HTTP" -RelativeDnsName $ResourceGroupName -Ttl 30 -MonitorPort 80 17 | 18 | # Create an App Service Plan 19 | New-AzAppservicePlan -Name "$App1Name-Plan" -ResourceGroupName $ResourceGroupName -Location $Location1 -Tier Standard 20 | New-AzAppservicePlan -Name "$App2Name-Plan" -ResourceGroupName $ResourceGroupName -Location $Location2 -Tier Standard 21 | 22 | # Create a Web App in the App Service Plan 23 | $App1ResourceId=(New-AzWebApp -Name $App1Name -ResourceGroupName $ResourceGroupName -Location $Location1 -AppServicePlan "$App1Name-Plan").Id 24 | $App2ResourceId=(New-AzWebApp -Name $App2Name -ResourceGroupName $ResourceGroupName -Location $Location2 -AppServicePlan "$App2Name-Plan").Id 25 | 26 | # Create Traffic Manager Endpoints for Web Apps 27 | New-AzTrafficManagerEndpoint -Name "$App1Name-$Location1" -ResourceGroupName $ResourceGroupName -ProfileName "$ResourceGroupName-tmp" -Type AzureEndpoints -TargetResourceId $App1ResourceId -EndpointStatus "Enabled" 28 | New-AzTrafficManagerEndpoint -Name "$App2Name-$Location2" -ResourceGroupName $ResourceGroupName -ProfileName "$ResourceGroupName-tmp" -Type AzureEndpoints -TargetResourceId $App2ResourceId -EndpointStatus "Enabled" 29 | -------------------------------------------------------------------------------- /api-management/scale-and-addregion-apim-service/scale_and_addregion_apim_service.ps1: -------------------------------------------------------------------------------- 1 | ########################################################## 2 | # Script to create an apim service and scale to premium 3 | # with an additional region. 4 | ########################################################### 5 | 6 | $random = (New-Guid).ToString().Substring(0,8) 7 | 8 | #Azure specific details 9 | $subscriptionId = "my-azure-subscription-id" 10 | 11 | # Api Management service specific details 12 | $apimServiceName = "apim-$random" 13 | $resourceGroupName = "apim-rg-$random" 14 | $location = "Japan East" 15 | $organisation = "Contoso" 16 | $adminEmail = "admin@contoso.com" 17 | 18 | # Set the context to the subscription Id where the cluster will be created 19 | Select-AzSubscription -SubscriptionId $subscriptionId 20 | 21 | # Create a resource group. 22 | New-AzResourceGroup -Name $resourceGroupName -Location $location 23 | 24 | # Create the Api Management service. Since the SKU is not specified, it creates a service with Developer SKU. 25 | New-AzApiManagement -ResourceGroupName $resourceGroupName -Name $apimServiceName -Location $location -Organization $organisation -AdminEmail $adminEmail 26 | 27 | # Scale master region to 'Premium' 1 28 | $sku = "Premium" 29 | $capacity = 1 30 | 31 | # Add new 'Premium' region 1 unit 32 | $additionLocation = Get-ProviderLocations "Microsoft.ApiManagement/service" | Where-Object {$_ -ne $location} | Select-Object -First 1 33 | 34 | Get-AzApiManagement -ResourceGroupName $resourceGroupName -Name $apimServiceName | 35 | Update-AzApiManagementRegion -Sku $sku -Capacity $capacity | 36 | Add-AzApiManagementRegion -Location $additionLocation -Sku $sku | 37 | Update-AzApiManagementDeployment 38 | 39 | Get-AzApiManagement -ResourceGroupName $resourceGroupName -Name $apimServiceName 40 | -------------------------------------------------------------------------------- /hdinsight/mahout/use-mahout.Tests.ps1: -------------------------------------------------------------------------------- 1 | $here = Split-Path -Parent $MyInvocation.MyCommand.Path 2 | $sut = (Split-Path -Leaf $MyInvocation.MyCommand.Path) -replace '\.Tests', '' 3 | . "$here\$sut" 4 | 5 | $clusterName = $ENV:ClusterName 6 | $httpUserPassword = $ENV:HttpPassword 7 | $securePassword = ConvertTo-SecureString $httpUserPassword -AsPlainText -Force 8 | $creds = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList "admin", $securePassword 9 | 10 | 11 | # Mocks don't work for Get-Credential, so we're implementing our own version of it. This is used for tests instead of the real one. 12 | function Get-Credential { return $creds } 13 | 14 | Describe "hdinsight-mahout" { 15 | # Use testdrive since there is a downloaded file 16 | in $TestDrive { 17 | It "Runs a MapReduce job using Start-AzHDInsightJob" { 18 | Mock Read-host { $clusterName } 19 | # Test that the job succeeded 20 | (Start-MahoutJob)[0].State | Should be "SUCCEEDED" 21 | } 22 | It "Downloaded the output file" { 23 | Test-Path .\output.txt | Should be True 24 | } 25 | It "Downloaded the moviedb file" { 26 | Test-Path .\moviedb.txt | Should be True 27 | } 28 | It "Downloaded the ratings file" { 29 | Test-Path .\user-ratings.txt | Should be True 30 | } 31 | 32 | # This isn't a great test, but we don't really know what the 33 | # Mahout ML will generate as movies in the output. It can be different 34 | # across different runs and if the data is updated on the cluster. 35 | It "Displays user-readable output" { 36 | { Format-MahoutOutput -userId 4 -userDataFile .\user-ratings.txt -movieFile .\moviedb.txt -recommendationFile .\output.txt } | Should not throw 37 | } 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /virtual-machine-scale-sets/create-single-availability-zone/create-single-availability-zone.ps1: -------------------------------------------------------------------------------- 1 | # Provide your own secure password for use with the VM instances 2 | $cred = Get-Credential 3 | 4 | # Create a virtual machine scale set and supporting resources 5 | # A resource group, virtual network, load balancer, and NAT rules are automatically 6 | # created if they do not already exist 7 | New-AzVmss ` 8 | -ResourceGroupName "myResourceGroup" ` 9 | -VMScaleSetName "myScaleSet" ` 10 | -Location "EastUS2" ` 11 | -VirtualNetworkName "myVnet" ` 12 | -SubnetName "mySubnet" ` 13 | -PublicIpAddressName "myPublicIPAddress" ` 14 | -LoadBalancerName "myLoadBalancer" ` 15 | -UpgradePolicyMode "Automatic" ` 16 | -Credential $cred ` 17 | -Zone "1" 18 | 19 | # Define the script for your Custom Script Extension to run 20 | $publicSettings = @{ 21 | "fileUris" = (,"https://raw.githubusercontent.com/Azure-Samples/compute-automation-configurations/master/automate-iis.ps1"); 22 | "commandToExecute" = "powershell -ExecutionPolicy Unrestricted -File automate-iis.ps1" 23 | } 24 | 25 | # Get information about the scale set 26 | $vmss = Get-AzVmss ` 27 | -ResourceGroupName "myResourceGroup" ` 28 | -VMScaleSetName "myScaleSet" 29 | 30 | # Use Custom Script Extension to install IIS and configure basic website 31 | Add-AzVmssExtension -VirtualMachineScaleSet $vmss ` 32 | -Name "customScript" ` 33 | -Publisher "Microsoft.Compute" ` 34 | -Type "CustomScriptExtension" ` 35 | -TypeHandlerVersion 1.8 ` 36 | -Setting $publicSettings 37 | 38 | # Update the scale set and apply the Custom Script Extension to the VM instances 39 | Update-AzVmss ` 40 | -ResourceGroupName "myResourceGroup" ` 41 | -Name "myScaleSet" ` 42 | -VirtualMachineScaleSet $vmss 43 | 44 | Get-AzPublicIpAddress -ResourceGroupName "myResourceGroup" | Select IpAddress 45 | -------------------------------------------------------------------------------- /virtual-machine-scale-sets/create-zone-redundant-scale-set/create-zone-redundant-scale-set.ps1: -------------------------------------------------------------------------------- 1 | # Provide your own secure password for use with the VM instances 2 | $cred = Get-Credential 3 | 4 | # Create a virtual machine scale set and supporting resources 5 | # A resource group, virtual network, load balancer, and NAT rules are automatically 6 | # created if they do not already exist 7 | New-AzVmss ` 8 | -ResourceGroupName "myResourceGroup" ` 9 | -VMScaleSetName "myScaleSet" ` 10 | -Location "EastUS2" ` 11 | -VirtualNetworkName "myVnet" ` 12 | -SubnetName "mySubnet" ` 13 | -PublicIpAddressName "myPublicIPAddress" ` 14 | -LoadBalancerName "myLoadBalancer" ` 15 | -UpgradePolicyMode "Automatic" ` 16 | -Credential $cred ` 17 | -Zone "1", "2", "3" 18 | 19 | # Define the script for your Custom Script Extension to run 20 | $publicSettings = @{ 21 | "fileUris" = (,"https://raw.githubusercontent.com/Azure-Samples/compute-automation-configurations/master/automate-iis.ps1"); 22 | "commandToExecute" = "powershell -ExecutionPolicy Unrestricted -File automate-iis.ps1" 23 | } 24 | 25 | # Get information about the scale set 26 | $vmss = Get-AzVmss ` 27 | -ResourceGroupName "myResourceGroup" ` 28 | -VMScaleSetName "myScaleSet" 29 | 30 | # Use Custom Script Extension to install IIS and configure basic website 31 | Add-AzVmssExtension -VirtualMachineScaleSet $vmss ` 32 | -Name "customScript" ` 33 | -Publisher "Microsoft.Compute" ` 34 | -Type "CustomScriptExtension" ` 35 | -TypeHandlerVersion 1.8 ` 36 | -Setting $publicSettings 37 | 38 | # Update the scale set and apply the Custom Script Extension to the VM instances 39 | Update-AzVmss ` 40 | -ResourceGroupName "myResourceGroup" ` 41 | -Name "myScaleSet" ` 42 | -VirtualMachineScaleSet $vmss 43 | 44 | Get-AzPublicIpAddress -ResourceGroupName "myResourceGroup" | Select IpAddress 45 | -------------------------------------------------------------------------------- /api-management/setup-rate-limit-policy/setup_rate_limit_policy.ps1: -------------------------------------------------------------------------------- 1 | ########################################################## 2 | # Script to apply Rate Limit to Policy at the Product Level 3 | ########################################################### 4 | 5 | $random = (New-Guid).ToString().Substring(0,8) 6 | 7 | #Azure specific details 8 | $subscriptionId = "my-azure-subscription-id" 9 | 10 | # Api Management service specific details 11 | $apimServiceName = "apim-$random" 12 | $resourceGroupName = "apim-rg-$random" 13 | $location = "Japan East" 14 | $organisation = "Contoso" 15 | $adminEmail = "admin@contoso.com" 16 | 17 | # Set the context to the subscription Id where the cluster will be created 18 | Select-AzSubscription -SubscriptionId $subscriptionId 19 | 20 | # Create a resource group. 21 | New-AzResourceGroup -Name $resourceGroupName -Location $location 22 | 23 | # Create the Api Management service. Since the SKU is not specified, it creates a service with Developer SKU. 24 | New-AzApiManagement -ResourceGroupName $resourceGroupName -Name $apimServiceName -Location $location -Organization $organisation -AdminEmail $adminEmail 25 | 26 | # Set context to newly created service 27 | $context = New-AzApiManagementContext -ResourceGroupName $resourceGroupName -ServiceName $apimServiceName 28 | 29 | # create a rate-limit product level policy 30 | $productValid = '' 31 | $product = Get-AzApiManagementProduct -Context $context -Title 'Unlimited' 32 | 33 | # setup Policy at the Product Level. Policies can be applied at entire API Management Service Scope, Api Scope, Product Scope and Api Operation Scope 34 | Set-AzApiManagementPolicy -Context $context -Policy $productValid -ProductId $product.ProductId -PassThru 35 | 36 | -------------------------------------------------------------------------------- /azure-migrate/automation-script/AzMigrate_Template.ps1: -------------------------------------------------------------------------------- 1 | Param( 2 | [parameter(Mandatory=$true)] 3 | $CsvFilePath 4 | ) 5 | 6 | $ErrorActionPreference = "Stop" 7 | 8 | $scriptsPath = $PSScriptRoot 9 | if ($PSScriptRoot -eq "") { 10 | $scriptsPath = "." 11 | } 12 | 13 | . "$scriptsPath\AzMigrate_Logger.ps1" 14 | . "$scriptsPath\AzMigrate_Shared.ps1" 15 | . "$scriptsPath\AzMigrate_CSV_Processor.ps1" 16 | 17 | Function ProcessItemImpl($processor, $csvItem, $reportItem) { 18 | #Add additional fields to the $reportItem object to report execution details 19 | #It will be included in the out....csv reporting file 20 | $reportItem | Add-Member NoteProperty "AdditionalInfoForReporting" $null 21 | $processor.Logger.LogTrace("Sample log - $($csvItem.SOURCE_MACHINE_NAME)") 22 | $reportItem.AdditionalInfoForReporting = "test_info" 23 | } 24 | 25 | Function ProcessItem($processor, $csvItem, $reportItem) { 26 | try { 27 | #This method will be invoked for each row in the CSV file 28 | ProcessItemImpl $processor $csvItem $reportItem 29 | } 30 | catch { 31 | $exceptionMessage = $_ | Out-String 32 | $processor.Logger.LogErrorAndThrow($exceptionMessage) 33 | #throw 34 | } 35 | } 36 | 37 | #logger to report information in file 'out...txt' 38 | $logger = New-AzMigrate_LoggerInstance -CommandPath $PSCommandPath 39 | 40 | #Shared functions to interact commonly or frequently used cmdlets 41 | $AzMigrateShared = New-AzMigrate_SharedInstance -Logger $logger 42 | 43 | #Common implementation to process the CsvFile and invoke the function for each row. 44 | #passing the logger and ProcessItem function which is stored in the Function: drive. 45 | $processor = New-CsvProcessorInstance -Logger $logger -ProcessItemFunction $function:ProcessItem 46 | $processor.ProcessFile($CsvFilePath) 47 | -------------------------------------------------------------------------------- /application-proxy/get-all-appproxy-apps-with-policy.ps1: -------------------------------------------------------------------------------- 1 | # This sample script gets all Azure AD Proxy applications that have assigned an Azure AD policy (token lifetime) with policy details. 2 | # Reference: 3 | # Configurable token lifetimes in Azure Active Directory (Preview) 4 | # https://docs.microsoft.com/en-us/azure/active-directory/develop/active-directory-configurable-token-lifetimes 5 | # 6 | # This script requires PowerShell 5.1 (x64) and the following module: 7 | # AzureADPreview 2.0.2.53 8 | # 9 | # Before you begin: 10 | # Run Connect-AzureAD to connect to the tenant domain. 11 | # Required Azure AD role: Global Administrator or Application Administrator 12 | 13 | Write-Host "Reading service principals. This operation might take longer..." -BackgroundColor "Black" -ForegroundColor "Green" 14 | 15 | $aadapServPrinc = Get-AzureADServicePrincipal -Top 100000 | where-object {$_.Tags -Contains "WindowsAzureActiveDirectoryOnPremApp"} 16 | 17 | Write-Host "Reading Azure AD applications. This operation might take longer..." -BackgroundColor "Black" -ForegroundColor "Green" 18 | 19 | $allApps = Get-AzureADApplication -Top 100000 20 | 21 | Write-Host "Displaying Azure AD Application Proxy applications with assigned Azure AD policies" -BackgroundColor "Black" -ForegroundColor "Green" 22 | Write-Host " " 23 | 24 | foreach ($item in $aadapServPrinc) { 25 | 26 | $policy=Get-AzureADServicePrincipalPolicy -Id $item.ObjectId 27 | 28 | If (!([string]::IsNullOrEmpty($policy.Id))) { 29 | 30 | Write-Host ("") 31 | 32 | $item.DisplayName + " (AppId: " + $item.AppId + ")" 33 | 34 | Write-Host ("") 35 | Write-Host ("Policy") 36 | 37 | Get-AzureADPolicy -Id $policy.id | fl 38 | 39 | Write-Host ("") 40 | 41 | } 42 | } 43 | 44 | Write-Host ("") 45 | Write-Host ("Finished.") -BackgroundColor "Black" -ForegroundColor "Green" 46 | Write-Host ("") 47 | -------------------------------------------------------------------------------- /app-service/connect-to-sql/connect-to-sql.ps1: -------------------------------------------------------------------------------- 1 | 2 | # Generates a Random Value 3 | $Random=(New-Guid).ToString().Substring(0,8) 4 | 5 | # Variables 6 | $ResourceGroup="MyResourceGroup$Random" 7 | $AppName="webappwithSQL$Random" 8 | $Location="West US" 9 | $ServerName="webappwithsql$Random" 10 | $StartIP="0.0.0.0" 11 | $EndIP="0.0.0.0" 12 | $Username="ServerAdmin" 13 | $Password="" 14 | $SqlServerPassword=New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $Username,(ConvertTo-SecureString -String $Password -AsPlainText -Force) 15 | 16 | # Create a Resource Group 17 | New-AzResourceGroup -Name $ResourceGroup -Location $Location 18 | 19 | # Create an App Service Plan 20 | New-AzAppservicePlan -Name WebAppwithSQLPlan -ResourceGroupName $ResourceGroup -Location $Location -Tier Basic 21 | 22 | # Create a Web App in the App Service Plan 23 | New-AzWebApp -Name $AppName -ResourceGroupName $ResourceGroup -Location $Location -AppServicePlan WebAppwithSQLPlan 24 | 25 | # Create a SQL Database Server 26 | New-AzSQLServer -ServerName $ServerName -Location $Location -SqlAdministratorCredentials $SqlServerPassword -ResourceGroupName $ResourceGroup 27 | 28 | # Create Firewall Rule for SQL Database Server 29 | New-AzSqlServerFirewallRule -FirewallRuleName "AllowYourIp" -StartIpAddress $StartIP -EndIPAddress $EndIP -ServerName $ServerName -ResourceGroupName $ResourceGroup 30 | 31 | # Create SQL Database in SQL Database Server 32 | New-AzSQLDatabase -ServerName $ServerName -DatabaseName MySampleDatabase -ResourceGroupName $ResourceGroup 33 | 34 | # Assign Connection String to Connection String 35 | Set-AzWebApp -ConnectionStrings @{ MyConnectionString = @{ Type="SQLAzure"; Value ="Server=tcp:$ServerName.database.windows.net;Database=MySampleDatabase;User ID=$Username@$ServerName;Password=$password;Trusted_Connection=False;Encrypt=True;" } } -Name $AppName -ResourceGroupName $ResourceGroup 36 | -------------------------------------------------------------------------------- /app-service/backup-restore-diff-sub/backup-restore-diff-sub.ps1: -------------------------------------------------------------------------------- 1 | # This sample script retrieves a previously completed backup from an existing web app and restores it to a web app in another subscription. 2 | # If needed, install the Azure PowerShell using the instruction found in the Azure PowerShell guide, and then run Connect-AzAccount to create a connection with Azure. 3 | 4 | $resourceGroupNameSub1 = "" 5 | $resourceGroupNameSub2 = "" 6 | $webAppNameSub1 = "" 7 | $webAppNameSub2 = "" 8 | $appServicePlanSub2 = "" 9 | $locationSub2 = "West Europe" 10 | 11 | 12 | # Log into the subscription with the backup 13 | Add-AzAccount 14 | 15 | # List statuses of all backups that are complete or currently executing. 16 | Get-AzWebAppBackupList -ResourceGroupName $resourceGroupNameSub1 -Name $webAppNameSub1 17 | 18 | # Note the BackupID property of the backup you want to restore 19 | 20 | # Get the backup object that you want to restore by specifying the BackupID 21 | $backup = (Get-AzWebAppBackup -ResourceGroupName $resourceGroupNameSub1 -Name $webAppNameSub1 -BackupId '') 22 | 23 | # Get the storage account URL of the backup configuration 24 | $url = (Get-AzWebAppBackupConfiguration -ResourceGroupName $resourceGroupNameSub1 -Name $webAppNameSub1).StorageAccountUrl 25 | 26 | # Log into the subscription that you want to restore the app to 27 | Add-AzAccount 28 | 29 | # Create a new web app 30 | New-AzWebApp -ResourceGroupName $resourceGroupNameSub2 -AppServicePlan $appServicePlanSub2 -Name $webAppNameSub2 -Location $locationSub2 31 | 32 | # Restore the app by overwriting it with the backup data 33 | Restore-AzWebAppBackup -ResourceGroupName $resourceGroupNameSub2 -Name $webAppNameSub2 -StorageAccountUrl $url -BlobName $backup.BlobName -Overwrite 34 | -------------------------------------------------------------------------------- /application-proxy/get-all-wildcard-apps.ps1: -------------------------------------------------------------------------------- 1 | # This sample script gets all Azure AD Application Proxy application wildcard published apps. 2 | # 3 | # This script requires PowerShell 5.1 (x64) and one of the following modules: 4 | # AzureAD 2.0.2.52 5 | # AzureADPreview 2.0.2.53 6 | # 7 | # Before you begin: 8 | # Run Connect-AzureAD to connect to the tenant domain. 9 | # Required Azure AD role: Global Administrator or Application Administrator or Application Developer 10 | 11 | Write-Host "Reading service principals. This operation might take longer..." -BackgroundColor "Black" -ForegroundColor "Green" 12 | 13 | $aadapServPrinc = Get-AzureADServicePrincipal -Top 100000 | where-object {$_.Tags -Contains "WindowsAzureActiveDirectoryOnPremApp"} 14 | 15 | Write-Host "Reading Azure AD applications. This operation might take longer..." -BackgroundColor "Black" -ForegroundColor "Green" 16 | 17 | $allApps = Get-AzureADApplication -Top 100000 18 | 19 | Write-Host "Reading application. This operation might take longer..." -BackgroundColor "Black" -ForegroundColor "Green" 20 | 21 | $aadapApp = $aadapServPrinc | ForEach-Object { $allApps -match $_.AppId} 22 | 23 | Write-Host "Displaying wildcard Azure AD Application Proxy applications..." -BackgroundColor "Black" -ForegroundColor "Green" 24 | Write-Host " " 25 | 26 | foreach ($item in $aadapApp) { 27 | 28 | $tempApps = Get-AzureADApplicationProxyApplication -ObjectId $item.ObjectId 29 | 30 | If ($tempApps.ExternalUrl -match "\*.") { 31 | 32 | $aadapServPrinc[$aadapApp.IndexOf($item)].DisplayName + " (AppId: " + $aadapServPrinc[$aadapApp.IndexOf($item)].AppId + ")"; 33 | 34 | $tempApps | select ExternalUrl,InternalUrl,ExternalAuthenticationType, VerifiedCustomDomainCertificatesMetadata | fl 35 | } 36 | } 37 | 38 | Write-Host ("") 39 | Write-Host ("Finished.") -BackgroundColor "Black" -ForegroundColor "Green" 40 | Write-Host ("") 41 | -------------------------------------------------------------------------------- /app-service/configure-ssl-certificate/configure-ssl-certificate.ps1: -------------------------------------------------------------------------------- 1 | $fqdn="" 2 | $pfxPath="" 3 | $pfxPassword="" 4 | $webappname="mywebapp$(Get-Random)" 5 | $location="West Europe" 6 | 7 | # Create a resource group. 8 | New-AzResourceGroup -Name $webappname -Location $location 9 | 10 | # Create an App Service plan in Free tier. 11 | New-AzAppServicePlan -Name $webappname -Location $location ` 12 | -ResourceGroupName $webappname -Tier Free 13 | 14 | # Create a web app. 15 | $webapp = New-AzWebApp -Name $webappname -Location $location -AppServicePlan $webappname ` 16 | -ResourceGroupName $webappname 17 | 18 | Write-Host "Sign in to your domain provider's website and configure the following records:" 19 | Write-Host "A CNAME record that maps $fqdn to $webappname.azurewebsites.net" 20 | Write-Host "A TXT record that maps asuid.$fqdn to the domain verification ID $($webapp.CustomDomainVerificationId)" 21 | Read-Host "Press [Enter] key when ready ..." 22 | 23 | # Before continuing, go to your DNS configuration UI for your custom domain and follow the 24 | # instructions at https://aka.ms/appservicecustomdns to configure a CNAME record for the 25 | # hostname "www" and point it your web app's default domain name. 26 | 27 | # Upgrade App Service plan to Basic tier (minimum required by custom SSL certificates) 28 | Set-AzAppServicePlan -Name $webappname -ResourceGroupName $webappname ` 29 | -Tier Basic 30 | 31 | # Add a custom domain name to the web app. 32 | Set-AzWebApp -Name $webappname -ResourceGroupName $webappname ` 33 | -HostNames @($fqdn,"$webappname.azurewebsites.net") 34 | 35 | # Upload and bind the SSL certificate to the web app. 36 | New-AzWebAppSSLBinding -WebAppName $webappname -ResourceGroupName $webappname -Name $fqdn ` 37 | -CertificateFilePath $pfxPath -CertificatePassword $pfxPassword -SslState SniEnabled 38 | -------------------------------------------------------------------------------- /application-proxy/get-all-default-domain-apps.ps1: -------------------------------------------------------------------------------- 1 | # This sample script gets all Azure AD Application Proxy application "non-custom domain" apps (.msappproxy.net). 2 | # 3 | # This script requires PowerShell 5.1 (x64) and one of the following modules: 4 | # AzureAD 2.0.2.52 5 | # AzureADPreview 2.0.2.53 6 | # 7 | # Before you begin: 8 | # Run Connect-AzureAD to connect to the tenant domain. 9 | # Required Azure AD role: Global Administrator or Application Administrator or Application Developer 10 | 11 | Write-Host "Reading service principals. This operation might take longer..." -BackgroundColor "Black" -ForegroundColor "Green" 12 | 13 | $aadapServPrinc = Get-AzureADServicePrincipal -Top 100000 | where-object {$_.Tags -Contains "WindowsAzureActiveDirectoryOnPremApp"} 14 | 15 | Write-Host "Reading Azure AD applications. This operation might take longer..." -BackgroundColor "Black" -ForegroundColor "Green" 16 | 17 | $allApps = Get-AzureADApplication -Top 100000 18 | 19 | Write-Host "Reading application. This operation might take longer..." -BackgroundColor "Black" -ForegroundColor "Green" 20 | 21 | $aadapApp = $aadapServPrinc | ForEach-Object { $allApps -match $_.AppId} 22 | 23 | Write-Host "Displaying all non-custom domain apps (.msappproxy) applications..." -BackgroundColor "Black" -ForegroundColor "Green" 24 | Write-Host " " 25 | 26 | foreach ($item in $aadapApp) { 27 | 28 | $tempApps = Get-AzureADApplicationProxyApplication -ObjectId $item.ObjectId 29 | 30 | If ($tempApps.ExternalUrl -match ".msappproxy.net") { 31 | 32 | $aadapServPrinc[$aadapApp.IndexOf($item)].DisplayName + " (AppId: " + $aadapServPrinc[$aadapApp.IndexOf($item)].AppId + ")" 33 | 34 | $tempApps | select ExternalUrl,InternalUrl,ExternalAuthenticationType | fl 35 | 36 | } 37 | } 38 | 39 | Write-Host ("") 40 | Write-Host ("Finished.") -BackgroundColor "Black" -ForegroundColor "Green" 41 | Write-Host ("") 42 | -------------------------------------------------------------------------------- /azure-migrate/migrate-at-scale-vmware-agentles/Agentless VMware automation/AzMigrate_Template.ps1: -------------------------------------------------------------------------------- 1 | Param( 2 | [parameter(Mandatory=$true)] 3 | $CsvFilePath 4 | ) 5 | 6 | $ErrorActionPreference = "Stop" 7 | 8 | $scriptsPath = $PSScriptRoot 9 | if ($PSScriptRoot -eq "") { 10 | $scriptsPath = "." 11 | } 12 | 13 | . "$scriptsPath\AzMigrate_Logger.ps1" 14 | . "$scriptsPath\AzMigrate_Shared.ps1" 15 | . "$scriptsPath\AzMigrate_CSV_Processor.ps1" 16 | 17 | Function ProcessItemImpl($processor, $csvItem, $reportItem) { 18 | #Add additional fields to the $reportItem object to report execution details 19 | #It will be included in the out....csv reporting file 20 | $reportItem | Add-Member NoteProperty "AdditionalInfoForReporting" $null 21 | $processor.Logger.LogTrace("Sample log - $($csvItem.SOURCE_MACHINE_NAME)") 22 | $reportItem.AdditionalInfoForReporting = "test_info" 23 | } 24 | 25 | Function ProcessItem($processor, $csvItem, $reportItem) { 26 | try { 27 | #This method will be invoked for each row in the CSV file 28 | ProcessItemImpl $processor $csvItem $reportItem 29 | } 30 | catch { 31 | $exceptionMessage = $_ | Out-String 32 | $processor.Logger.LogErrorAndThrow($exceptionMessage) 33 | #throw 34 | } 35 | } 36 | 37 | #logger to report information in file 'out...txt' 38 | $logger = New-AzMigrate_LoggerInstance -CommandPath $PSCommandPath 39 | 40 | #Shared functions to interact commonly or frequently used cmdlets 41 | $AzMigrateShared = New-AzMigrate_SharedInstance -Logger $logger 42 | 43 | #Common implementation to process the CsvFile and invoke the function for each row. 44 | #passing the logger and ProcessItem function which is stored in the Function: drive. 45 | $processor = New-CsvProcessorInstance -Logger $logger -ProcessItemFunction $function:ProcessItem 46 | $processor.ProcessFile($CsvFilePath) 47 | -------------------------------------------------------------------------------- /azure-migrate/migrate-at-scale-vmware-agentles/AzMigrate_AutomationNScale/AzMigrate_Template.txt: -------------------------------------------------------------------------------- 1 | Param( 2 | [parameter(Mandatory=$true)] 3 | $CsvFilePath 4 | ) 5 | 6 | $ErrorActionPreference = "Stop" 7 | 8 | $scriptsPath = $PSScriptRoot 9 | if ($PSScriptRoot -eq "") { 10 | $scriptsPath = "." 11 | } 12 | 13 | . "$scriptsPath\AzMigrate_Logger.ps1" 14 | . "$scriptsPath\AzMigrate_Shared.ps1" 15 | . "$scriptsPath\AzMigrate_CSV_Processor.ps1" 16 | 17 | Function ProcessItemImpl($processor, $csvItem, $reportItem) { 18 | #Add additional fields to the $reportItem object to report execution details 19 | #It will be included in the out....csv reporting file 20 | $reportItem | Add-Member NoteProperty "AdditionalInfoForReporting" $null 21 | $processor.Logger.LogTrace("Sample log - $($csvItem.SOURCE_MACHINE_NAME)") 22 | $reportItem.AdditionalInfoForReporting = "test_info" 23 | } 24 | 25 | Function ProcessItem($processor, $csvItem, $reportItem) { 26 | try { 27 | #This method will be invoked for each row in the CSV file 28 | ProcessItemImpl $processor $csvItem $reportItem 29 | } 30 | catch { 31 | $exceptionMessage = $_ | Out-String 32 | $processor.Logger.LogErrorAndThrow($exceptionMessage) 33 | #throw 34 | } 35 | } 36 | 37 | #logger to report information in file 'out...txt' 38 | $logger = New-AzMigrate_LoggerInstance -CommandPath $PSCommandPath 39 | 40 | #Shared functions to interact commonly or frequently used cmdlets 41 | $AzMigrateShared = New-AzMigrate_SharedInstance -Logger $logger 42 | 43 | #Common implementation to process the CsvFile and invoke the function for each row. 44 | #passing the logger and ProcessItem function which is stored in the Function: drive. 45 | $processor = New-CsvProcessorInstance -Logger $logger -ProcessItemFunction $function:ProcessItem 46 | $processor.ProcessFile($CsvFilePath) 47 | -------------------------------------------------------------------------------- /virtual-machine/copy-snapshot-to-storage-account/copy-snapshot-to-storage-account.ps1: -------------------------------------------------------------------------------- 1 | #Provide the subscription Id of the subscription where snapshot is created 2 | $subscriptionId = "yourSubscriptionId" 3 | 4 | #Provide the name of your resource group where snapshot is created 5 | $resourceGroupName ="yourResourceGroupName" 6 | 7 | #Provide the snapshot name 8 | $snapshotName = "yourSnapshotName" 9 | 10 | #Provide Shared Access Signature (SAS) expiry duration in seconds e.g. 3600. 11 | #Know more about SAS here: https://docs.microsoft.com/en-us/Az.Storage/storage-dotnet-shared-access-signature-part-1 12 | $sasExpiryDuration = "3600" 13 | 14 | #Provide storage account name where you want to copy the snapshot. 15 | $storageAccountName = "yourstorageaccountName" 16 | 17 | #Name of the storage container where the downloaded snapshot will be stored 18 | $storageContainerName = "yourstoragecontainername" 19 | 20 | #Provide the key of the storage account where you want to copy snapshot. 21 | $storageAccountKey = 'yourStorageAccountKey' 22 | 23 | #Provide the name of the VHD file to which snapshot will be copied. 24 | $destinationVHDFileName = "yourvhdfilename" 25 | 26 | 27 | # Set the context to the subscription Id where Snapshot is created 28 | Select-AzSubscription -SubscriptionId $SubscriptionId 29 | 30 | #Generate the SAS for the snapshot 31 | $sas = Grant-AzSnapshotAccess -ResourceGroupName $ResourceGroupName -SnapshotName $SnapshotName  -DurationInSecond $sasExpiryDuration -Access Read 32 | #Create the context for the storage account which will be used to copy snapshot to the storage account 33 | $destinationContext = New-AzStorageContext -StorageAccountName $storageAccountName -StorageAccountKey $storageAccountKey 34 | 35 | #Copy the snapshot to the storage account 36 | Start-AzStorageBlobCopy -AbsoluteUri $sas.AccessSAS -DestContainer $storageContainerName -DestContext $destinationContext -DestBlob $destinationVHDFileName 37 | -------------------------------------------------------------------------------- /app-service/backup-onetime/backup-onetime.ps1: -------------------------------------------------------------------------------- 1 | # This sample script creates a web app in App Service with its related resources, and then creates a one-time backup for it. 2 | # If needed, install the Azure PowerShell using the instruction found in the Azure PowerShell guide, and then run Connect-AzAccount to create a connection with Azure. 3 | 4 | $webappname="mywebapp$(Get-Random -Minimum 100000 -Maximum 999999)" 5 | $storagename="$($webappname)storage" 6 | $container="appbackup" 7 | $location="West Europe" 8 | $backupname="backup1" 9 | 10 | # Create a resource group. 11 | New-AzResourceGroup -Name myResourceGroup -Location $location 12 | 13 | # Create a storage account. 14 | $storage = New-AzStorageAccount -ResourceGroupName myResourceGroup ` 15 | -Name $storagename -SkuName Standard_LRS -Location $location 16 | 17 | # Create a storage container. 18 | New-AzStorageContainer -Name $container -Context $storage.Context 19 | 20 | # Generates an SAS token for the storage container, valid for one month. 21 | # NOTE: You can use the same SAS token to make backups in Web Apps until -ExpiryTime 22 | $sasUrl = New-AzStorageContainerSASToken -Name $container -Permission rwdl ` 23 | -Context $storage.Context -ExpiryTime (Get-Date).AddMonths(1) -FullUri 24 | 25 | # Create an App Service plan in Standard tier. Standard tier allows one backup per day. 26 | New-AzAppServicePlan -ResourceGroupName myResourceGroup -Name $webappname ` 27 | -Location $location -Tier Standard 28 | 29 | # Create a web app. 30 | New-AzWebApp -ResourceGroupName myResourceGroup -Name $webappname ` 31 | -Location $location -AppServicePlan $webappname 32 | 33 | # Create a one-time backup 34 | New-AzWebAppBackup -ResourceGroupName myResourceGroup -Name $webappname ` 35 | -StorageAccountUrl $sasUrl -BackupName $backupname 36 | 37 | # List statuses of all backups that are complete or currently executing. 38 | Get-AzWebAppBackupList -ResourceGroupName myResourceGroup -Name $webappname 39 | -------------------------------------------------------------------------------- /virtual-machine-scale-sets/install-apps/install-apps.ps1: -------------------------------------------------------------------------------- 1 | # Provide your own secure password for use with the VM instances 2 | $cred = Get-Credential 3 | 4 | # Create a virtual machine scale set and supporting resources 5 | # A resource group, virtual network, load balancer, and NAT rules are automatically 6 | # created if they do not already exist 7 | New-AzVmss ` 8 | -ResourceGroupName "myResourceGroup" ` 9 | -VMScaleSetName "myScaleSet" ` 10 | -Location "EastUS" ` 11 | -VirtualNetworkName "myVnet" ` 12 | -SubnetName "mySubnet" ` 13 | -PublicIpAddressName "myPublicIPAddress" ` 14 | -LoadBalancerName "myLoadBalancer" ` 15 | -UpgradePolicyMode "Automatic" ` 16 | -Credential $cred 17 | 18 | # Create a configuration object to store the Custom Script Extension definition 19 | $customConfig = @{ 20 | "fileUris" = (,"https://raw.githubusercontent.com/Azure-Samples/compute-automation-configurations/master/automate-iis.ps1"); 21 | "commandToExecute" = "powershell -ExecutionPolicy Unrestricted -File automate-iis.ps1" 22 | } 23 | 24 | # Get information about the scale set 25 | $vmss = Get-AzVmss ` 26 | -ResourceGroupName "myResourceGroup" ` 27 | -VMScaleSetName "myScaleSet" 28 | 29 | # Add the Custom Script Extension to install IIS and configure basic website 30 | $vmss = Add-AzVmssExtension ` 31 | -VirtualMachineScaleSet $vmss ` 32 | -Name "customScript" ` 33 | -Publisher "Microsoft.Compute" ` 34 | -Type "CustomScriptExtension" ` 35 | -TypeHandlerVersion 1.8 ` 36 | -Setting $customConfig 37 | 38 | # Update the scale set and apply the Custom Script Extension to the VM instances 39 | Update-AzVmss ` 40 | -ResourceGroupName "myResourceGroup" ` 41 | -Name "myScaleSet" ` 42 | -VirtualMachineScaleSet $vmss 43 | 44 | # Get the public IP address of your load balancer. To see your scale set in action, open this address in a web browser 45 | Get-AzPublicIpAddress -ResourceGroupName "myResourceGroup" | Select IpAddress 46 | -------------------------------------------------------------------------------- /storage/delete-containers-by-prefix/delete-containers-by-prefix.ps1: -------------------------------------------------------------------------------- 1 | # this script will show how to delete containers with a specific prefix 2 | # the prefix this will search for is "image". 3 | # before running this, you need to create a storage account, create some containers, 4 | # some having the same prefix so you can test this 5 | # note: this retrieves all of the matching containers in one command 6 | # if you are going to run this against a storage account with a lot of containers 7 | # (more than a couple hundred), use continuation tokens to retrieve 8 | # the list of containers. We will be adding a sample showing that scenario in the future. 9 | 10 | # these are for the storage account to be used 11 | # and the prefix for which to search 12 | $resourceGroup = "containerdeletetestrg" 13 | $storageAccountName = "containerdeletetest" 14 | $prefix = "image" 15 | 16 | # get a reference to the storage account and the context 17 | $storageAccount = Get-AzStorageAccount ` 18 | -ResourceGroupName $resourceGroup ` 19 | -Name $storageAccountName 20 | $ctx = $storageAccount.Context 21 | 22 | # list all containers in the storage account 23 | Write-Host "All containers" 24 | Get-AzStorageContainer -Context $ctx | select Name 25 | 26 | # retrieve list of containers to delete 27 | $listOfContainersToDelete = Get-AzStorageContainer -Context $ctx -Prefix $prefix 28 | 29 | # write list of containers to be deleted 30 | Write-Host "Containers to be deleted" 31 | $listOfContainersToDelete | select Name 32 | 33 | # delete the containers; this pipes the result of the listing of the containers to delete 34 | # into the Remove-AzStorageContainer command. It handles all of the containers in the list. 35 | Write-Host "Deleting containers" 36 | $listOfContainersToDelete | Remove-AzStorageContainer -Context $ctx 37 | 38 | # show list of containers not deleted 39 | Write-Host "All containers not deleted" 40 | Get-AzStorageContainer -Context $ctx | select Name 41 | -------------------------------------------------------------------------------- /virtual-machine/copy-snapshot-to-same-or-different-subscription/copy-snapshot-to-same-or-different-subscription.ps1: -------------------------------------------------------------------------------- 1 | #Provide the subscription Id of the subscription where snapshot exists 2 | $sourceSubscriptionId='yourSourceSubscriptionId' 3 | 4 | #Provide the name of your resource group where snapshot exists 5 | $sourceResourceGroupName='yourResourceGroupName' 6 | 7 | #Provide the name of the snapshot 8 | $snapshotName='yourSnapshotName' 9 | 10 | #Set the context to the subscription Id where snapshot exists 11 | Select-AzSubscription -SubscriptionId $sourceSubscriptionId 12 | 13 | #Get the source snapshot 14 | $snapshot= Get-AzSnapshot -ResourceGroupName $sourceResourceGroupName -Name $snapshotName 15 | 16 | #Provide the subscription Id of the subscription where snapshot will be copied to 17 | #If snapshot is copied to the same subscription then you can skip this step 18 | $targetSubscriptionId='yourTargetSubscriptionId' 19 | 20 | #Name of the resource group where snapshot will be copied to 21 | $targetResourceGroupName='yourTargetResourceGroupName' 22 | 23 | #Set the context to the subscription Id where snapshot will be copied to 24 | #If snapshot is copied to the same subscription then you can skip this step 25 | Select-AzSubscription -SubscriptionId $targetSubscriptionId 26 | 27 | #We recommend you to store your snapshots in Standard storage to reduce cost. Please use Standard_ZRS in regions where zone redundant storage (ZRS) is available, otherwise use Standard_LRS 28 | #Please check out the availability of ZRS here: https://docs.microsoft.com/en-us/Az.Storage/common/storage-redundancy-zrs#support-coverage-and-regional-availability 29 | $snapshotConfig = New-AzSnapshotConfig -SourceResourceId $snapshot.Id -Location $snapshot.Location -CreateOption Copy -SkuName Standard_LRS 30 | 31 | #Create a new snapshot in the target subscription and resource group 32 | New-AzSnapshot -Snapshot $snapshotConfig -SnapshotName $snapshotName -ResourceGroupName $targetResourceGroupName 33 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | --- 2 | page_type: sample 3 | description: "A collection of Azure PowerShell code samples used in Microsoft's official Azure PowerShell Documentation." 4 | languages: 5 | - powershell 6 | products: 7 | - azure 8 | --- 9 | 10 | # Sample code for Azure PowerShell documentation 11 | 12 | The sample code in this repo for Azure PowerShell documentation is being transitioned to a new 13 | repository. 14 | 15 | > All future contributions and updates to sample code for Azure PowerShell documentation should be 16 | > directed to: 17 | > [github.com/Azure-Samples/azure-docs-powershell-samples](https://github.com/Azure-Samples/azure-docs-powershell-samples). 18 | 19 | All code in this repository is non-production samples used in Microsoft's official Azure PowerShell 20 | documentation and is designed to be used by our customers for learning and experimentation purposes. 21 | 22 | ## Feedback 23 | 24 | If you have any questions or comments, log an issue in the 25 | [Azure-Samples/azure-docs-powershell-samples](https://github.com/Azure-Samples/azure-docs-powershell-samples/issues) 26 | repo. 27 | 28 | ## Contributing 29 | 30 | New contributions to this repo are no longer accepted. Please submit new sample code contributions 31 | for Azure PowerShell documentation to the 32 | [Azure-Samples/azure-docs-powershell-samples](https://github.com/Azure-Samples/azure-docs-powershell-samples) 33 | repo. 34 | 35 | ## License 36 | 37 | The MIT License applies to the code contained in this repo. For more information, see 38 | [LICENSE](LICENSE). 39 | 40 | ## Microsoft Open Source Code of Conduct 41 | 42 | This repository has adopted the 43 | [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). For more 44 | information see the [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or 45 | contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with any additional questions or 46 | comments. 47 | -------------------------------------------------------------------------------- /sql-database/create-and-configure-database/create-and-configure-database.ps1: -------------------------------------------------------------------------------- 1 | # Connect-AzAccount 2 | # The SubscriptionId in which to create these objects 3 | $SubscriptionId = '' 4 | # Set the resource group name and location for your server 5 | $resourceGroupName = "myResourceGroup-$(Get-Random)" 6 | $location = "westus2" 7 | # Set an admin login and password for your server 8 | $adminSqlLogin = "SqlAdmin" 9 | $password = "ChangeYourAdminPassword1" 10 | # Set server name - the logical server name has to be unique in the system 11 | $serverName = "server-$(Get-Random)" 12 | # The sample database name 13 | $databaseName = "mySampleDatabase" 14 | # The ip address range that you want to allow to access your server 15 | $startIp = "0.0.0.0" 16 | $endIp = "0.0.0.0" 17 | 18 | # Set subscription 19 | Set-AzContext -SubscriptionId $subscriptionId 20 | 21 | # Create a resource group 22 | $resourceGroup = New-AzResourceGroup -Name $resourceGroupName -Location $location 23 | 24 | # Create a server with a system wide unique server name 25 | $server = New-AzSqlServer -ResourceGroupName $resourceGroupName ` 26 | -ServerName $serverName ` 27 | -Location $location ` 28 | -SqlAdministratorCredentials $(New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $adminSqlLogin, $(ConvertTo-SecureString -String $password -AsPlainText -Force)) 29 | 30 | # Create a server firewall rule that allows access from the specified IP range 31 | $serverFirewallRule = New-AzSqlServerFirewallRule -ResourceGroupName $resourceGroupName ` 32 | -ServerName $serverName ` 33 | -FirewallRuleName "AllowedIPs" -StartIpAddress $startIp -EndIpAddress $endIp 34 | 35 | # Create a blank database with an S0 performance level 36 | $database = New-AzSqlDatabase -ResourceGroupName $resourceGroupName ` 37 | -ServerName $serverName ` 38 | -DatabaseName $databaseName ` 39 | -RequestedServiceObjectiveName "S0" ` 40 | -SampleName "AdventureWorksLT" 41 | 42 | # Clean up deployment 43 | # Remove-AzResourceGroup -ResourceGroupName $resourceGroupName -------------------------------------------------------------------------------- /app-service/backup-scheduled/backup-scheduled.ps1: -------------------------------------------------------------------------------- 1 | $webappname="mywebapp$(Get-Random -Minimum 100000 -Maximum 999999)" 2 | $storagename="$($webappname)storage" 3 | $container="appbackup" 4 | $location="West Europe" 5 | 6 | # Create a resource group. 7 | New-AzResourceGroup -Name myResourceGroup -Location $location 8 | 9 | # Create a storage account. 10 | $storage = New-AzStorageAccount -ResourceGroupName myResourceGroup ` 11 | -Name $storagename -SkuName Standard_LRS -Location $location 12 | 13 | # Create a storage container. 14 | New-AzStorageContainer -Name $container -Context $storage.Context 15 | 16 | # Generates an SAS token for the storage container, valid for 1 year. 17 | # NOTE: You can use the same SAS token to make backups in Web Apps until -ExpiryTime 18 | $sasUrl = New-AzStorageContainerSASToken -Name $container -Permission rwdl ` 19 | -Context $storage.Context -ExpiryTime (Get-Date).AddYears(1) -FullUri 20 | 21 | # Create an App Service plan in Standard tier. Standard tier allows one backup per day. 22 | New-AzAppServicePlan -ResourceGroupName myResourceGroup -Name $webappname ` 23 | -Location $location -Tier Standard 24 | 25 | # Create a web app. 26 | New-AzWebApp -ResourceGroupName myResourceGroup -Name $webappname ` 27 | -Location $location -AppServicePlan $webappname 28 | 29 | # Schedule a backup every day, beginning in one hour, and retain for 10 days 30 | Edit-AzWebAppBackupConfiguration -ResourceGroupName myResourceGroup -Name $webappname ` 31 | -StorageAccountUrl $sasUrl -FrequencyInterval 1 -FrequencyUnit Day -KeepAtLeastOneBackup ` 32 | -StartTime (Get-Date).AddHours(1) -RetentionPeriodInDays 10 33 | 34 | # List statuses of all backups that are complete or currently executing. 35 | Get-AzWebAppBackupList -ResourceGroupName myResourceGroup -Name $webappname 36 | 37 | # (OPTIONAL) Change the backup schedule to every 2 days 38 | $configuration = Get-AzWebAppBackupConfiguration -ResourceGroupName myResourceGroup ` 39 | -Name $webappname 40 | $configuration.FrequencyInterval = 2 41 | $configuration | Edit-AzWebAppBackupConfiguration 42 | -------------------------------------------------------------------------------- /hdinsight/use-pig/use-pig.ps1: -------------------------------------------------------------------------------- 1 | function Start-PigJob { 2 | # Script should stop on failures 3 | $ErrorActionPreference = "Stop" 4 | 5 | # Login to your Azure subscription 6 | $context = Get-AzContext 7 | if ($context -eq $null) 8 | { 9 | Connect-AzAccount 10 | } 11 | $context 12 | 13 | # Get cluster info 14 | $clusterName = Read-Host -Prompt "Enter the HDInsight cluster name" 15 | $creds=Get-Credential -Message "Enter the login for the cluster" 16 | 17 | #Store the Pig Latin into $QueryString 18 | $QueryString = "LOGS = LOAD '/example/data/sample.log';" + 19 | "LEVELS = foreach LOGS generate REGEX_EXTRACT(`$0, '(TRACE|DEBUG|INFO|WARN|ERROR|FATAL)', 1) as LOGLEVEL;" + 20 | "FILTEREDLEVELS = FILTER LEVELS by LOGLEVEL is not null;" + 21 | "GROUPEDLEVELS = GROUP FILTEREDLEVELS by LOGLEVEL;" + 22 | "FREQUENCIES = foreach GROUPEDLEVELS generate group as LOGLEVEL, COUNT(FILTEREDLEVELS.LOGLEVEL) as COUNT;" + 23 | "RESULT = order FREQUENCIES by COUNT desc;" + 24 | "DUMP RESULT;" 25 | 26 | 27 | #Create a new HDInsight Pig Job definition 28 | $pigJobDefinition = New-AzHDInsightPigJobDefinition ` 29 | -Query $QueryString ` 30 | -Arguments "-w" 31 | 32 | # Start the Pig job on the HDInsight cluster 33 | Write-Host "Start the Pig job ..." -ForegroundColor Green 34 | $pigJob = Start-AzHDInsightJob ` 35 | -ClusterName $clusterName ` 36 | -JobDefinition $pigJobDefinition ` 37 | -HttpCredential $creds 38 | 39 | # Wait for the Pig job to complete 40 | Write-Host "Wait for the Pig job to complete ..." -ForegroundColor Green 41 | Wait-AzHDInsightJob ` 42 | -ClusterName $clusterName ` 43 | -JobId $pigJob.JobId ` 44 | -HttpCredential $creds 45 | 46 | # Display the output of the Pig job. 47 | Write-Host "Display the standard output ..." -ForegroundColor Green 48 | Get-AzHDInsightJobOutput ` 49 | -ClusterName $clusterName ` 50 | -JobId $pigJob.JobId ` 51 | -HttpCredential $creds 52 | } -------------------------------------------------------------------------------- /cosmosdb/sql/ps-sql-autoscale.ps1: -------------------------------------------------------------------------------- 1 | # Reference: Az.CosmosDB | https://docs.microsoft.com/powershell/module/az.cosmosdb 2 | # -------------------------------------------------- 3 | # Purpose 4 | # Create Cosmos SQL API account, database, and container with autoscale throughput, 5 | # -------------------------------------------------- 6 | Function New-RandomString{Param ([Int]$Length = 10) return $(-join ((97..122) + (48..57) | Get-Random -Count $Length | ForEach-Object {[char]$_}))} 7 | # -------------------------------------------------- 8 | $uniqueId = New-RandomString -Length 7 # Random alphanumeric string for unique resource names 9 | $apiKind = "Sql" 10 | # -------------------------------------------------- 11 | # Variables - ***** SUBSTITUTE YOUR VALUES ***** 12 | $locations = @() 13 | $locations += New-AzCosmosDBLocationObject -LocationName "East Us" -FailoverPriority 0 -IsZoneRedundant 0 14 | $locations += New-AzCosmosDBLocationObject -LocationName "West Us" -FailoverPriority 1 -IsZoneRedundant 0 15 | 16 | $resourceGroupName = "myResourceGroup" # Resource Group must already exist 17 | $accountName = "cosmos-$uniqueId" # Must be all lower case 18 | $consistencyLevel = "Session" 19 | $databaseName = "myDatabase" 20 | $containerName = "myContainer" 21 | $autoscaleMaxThroughput = 4000 #minimum = 4000 22 | $partitionKeyPath = "/myPartitionKey" 23 | 24 | # -------------------------------------------------- 25 | Write-Host "Creating account $accountName" 26 | $account = New-AzCosmosDBAccount -ResourceGroupName $resourceGroupName ` 27 | -LocationObject $locations -Name $accountName -ApiKind $apiKind ` 28 | -DefaultConsistencyLevel $consistencyLevel ` 29 | -EnableAutomaticFailover:$true 30 | 31 | Write-Host "Creating database $databaseName" 32 | $database = New-AzCosmosDBSqlDatabase -ParentObject $account -Name $databaseName 33 | 34 | Write-Host "Creating container $containerName" 35 | $container = New-AzCosmosDBSqlContainer ` 36 | -ParentObject $database -Name $containerName ` 37 | -PartitionKeyKind Hash -PartitionKeyPath $partitionKeyPath ` 38 | -AutoscaleMaxThroughput $autoscaleMaxThroughput 39 | -------------------------------------------------------------------------------- /application-proxy/get-all-custom-domain-no-cert.ps1: -------------------------------------------------------------------------------- 1 | # This sample script gets all Azure AD Application Proxy applications using custom domain with no certificate. 2 | # 3 | # This script requires PowerShell 5.1 (x64) and one of the following modules: 4 | # AzureAD 2.0.2.52 5 | # AzureADPreview 2.0.2.53 6 | # 7 | # Before you begin: 8 | # Run Connect-AzureAD to connect to the tenant domain. 9 | # Required Azure AD role: Global Administrator or Application Administrator or Application Developer 10 | 11 | Write-Host "Reading service principals. This operation might take longer..." -BackgroundColor "Black" -ForegroundColor "Green" 12 | 13 | $aadapServPrinc = Get-AzureADServicePrincipal -Top 100000 | where-object {$_.Tags -Contains "WindowsAzureActiveDirectoryOnPremApp"} 14 | 15 | Write-Host "Reading Azure AD applications. This operation might take longer..." -BackgroundColor "Black" -ForegroundColor "Green" 16 | 17 | $allApps = Get-AzureADApplication -Top 100000 18 | 19 | Write-Host "Reading application. This operation might take longer..." -BackgroundColor "Black" -ForegroundColor "Green" 20 | 21 | $aadapApp = $aadapServPrinc | ForEach-Object { $allApps -match $_.AppId} 22 | 23 | Write-Host "Displaying custom domain Azure AD Application Proxy applications with no uploaded certificates..." -BackgroundColor "Black" -ForegroundColor "Green" 24 | Write-Host " " 25 | 26 | foreach ($item in $aadapApp) { 27 | 28 | $tempApps = Get-AzureADApplicationProxyApplication -ObjectId $item.ObjectId 29 | 30 | If ($tempApps.ExternalUrl -notmatch ".msappproxy.net") { 31 | 32 | If ($tempApps.VerifiedCustomDomainCertificatesMetadata -notmatch "class") { 33 | 34 | $aadapServPrinc[$aadapApp.IndexOf($item)].DisplayName + " (AppId: " + $aadapServPrinc[$aadapApp.IndexOf($item)].AppId + ")"; 35 | 36 | $tempApps | select ExternalUrl,InternalUrl,ExternalAuthenticationType, VerifiedCustomDomainCertificatesMetadata | fl 37 | 38 | } 39 | } 40 | } 41 | 42 | Write-Host ("") 43 | Write-Host ("Finished.") -BackgroundColor "Black" -ForegroundColor "Green" 44 | Write-Host ("") 45 | -------------------------------------------------------------------------------- /cosmosdb/gremlin/ps-gremlin-autoscale.ps1: -------------------------------------------------------------------------------- 1 | # Reference: Az.CosmosDB | https://docs.microsoft.com/powershell/module/az.cosmosdb 2 | # -------------------------------------------------- 3 | # Purpose 4 | # Create Cosmos Gremlin API account, database, and graph 5 | # with autoscale throughput 6 | # -------------------------------------------------- 7 | Function New-RandomString{Param ([Int]$Length = 10) return $(-join ((97..122) + (48..57) | Get-Random -Count $Length | ForEach-Object {[char]$_}))} 8 | # -------------------------------------------------- 9 | $uniqueId = New-RandomString -Length 7 # Random alphanumeric string for unique resource names 10 | $apiKind = "Gremlin" 11 | # -------------------------------------------------- 12 | # Variables - ***** SUBSTITUTE YOUR VALUES ***** 13 | $locations = @() 14 | $locations += New-AzCosmosDBLocationObject -LocationName "East Us" -FailoverPriority 0 -IsZoneRedundant 0 15 | $locations += New-AzCosmosDBLocationObject -LocationName "West Us" -FailoverPriority 1 -IsZoneRedundant 0 16 | 17 | $resourceGroupName = "myResourceGroup" # Resource Group must already exist 18 | $accountName = "cosmos-$uniqueId" # Must be all lower case 19 | $consistencyLevel = "Session" 20 | $databaseName = "myDatabase" 21 | $graphName = "myGraph" 22 | $autoscaleMaxThroughput = 4000 #minimum = 4000 23 | $partitionKeys = @("/myPartitionKey") 24 | # -------------------------------------------------- 25 | 26 | Write-Host "Creating account $accountName" 27 | $account = New-AzCosmosDBAccount -ResourceGroupName $resourceGroupName ` 28 | -LocationObject $locations -Name $accountName -ApiKind $apiKind ` 29 | -DefaultConsistencyLevel $consistencyLevel ` 30 | -EnableAutomaticFailover:$true 31 | 32 | Write-Host "Creating database $databaseName" 33 | $database = New-AzCosmosDBGremlinDatabase -ParentObject $account ` 34 | -Name $databaseName 35 | 36 | Write-Host "Creating graph $graphName" 37 | $graph = New-AzCosmosDBGremlinGraph -ParentObject $database ` 38 | -Name $graphName -AutoscaleMaxThroughput $autoscaleMaxThroughput ` 39 | -PartitionKeyKind Hash -PartitionKeyPath $partitionKeys 40 | -------------------------------------------------------------------------------- /cosmosdb/table/ps-table-lock.ps1: -------------------------------------------------------------------------------- 1 | # References: 2 | # Az.CosmosDB | https://docs.microsoft.com/powershell/module/az.cosmosdb 3 | # Az.Resources | https://docs.microsoft.com/powershell/module/az.resources 4 | # -------------------------------------------------- 5 | # Purpose 6 | # 7 | # -------------------------------------------------- 8 | # Variables 9 | # ***** SUBSTITUTE YOUR VALUES ***** 10 | $resourceGroupName = "myResourceGroup" 11 | $accountName = "myaccount" 12 | $databaseName = "myDatabase" 13 | # ***** 14 | $apiVersion = "2020-04-01" # Cosmos DB RP API version 15 | $lockLevel = "CanNotDelete" # CanNotDelete or ReadOnly 16 | 17 | $resourceTypeAccount = "Microsoft.DocumentDB/databaseAccounts" 18 | $resourceTypeDatabase = "$resourceTypeAccount/tables" 19 | 20 | $resourceNameDatabase = "$accountName/$databaseName" 21 | $lockNameDatabase = "$accountName-$databaseName-Lock" 22 | # -------------------------------------------------- 23 | 24 | Write-Host "Create a $lockLevel lock on resource $resourceNameDatabase" 25 | New-AzResourceLock ` 26 | -ApiVersion $apiVersion ` 27 | -ResourceGroupName $resourceGroupName ` 28 | -ResourceType $resourceTypeDatabase ` 29 | -ResourceName $resourceNameDatabase ` 30 | -LockName $lockNameDatabase ` 31 | -LockLevel $lockLevel ` 32 | -Force 33 | 34 | Write-Host "List all locks on Cosmos DB account $accountName to confirm lock creation" 35 | Get-AzResourceLock ` 36 | -ApiVersion $apiVersion ` 37 | -ResourceGroupName $resourceGroupName ` 38 | -ResourceType $resourceTypeAccount ` 39 | -ResourceName $accountName 40 | 41 | Write-Host "Delete lock on resource $resourceNameDatabase" 42 | Remove-AzResourceLock ` 43 | -ApiVersion $apiVersion ` 44 | -ResourceGroupName $resourceGroupName ` 45 | -ResourceType $resourceTypeDatabase ` 46 | -ResourceName $resourceNameDatabase ` 47 | -LockName $lockNameDatabase ` 48 | -Force 49 | 50 | Write-Host "List all locks on Cosmos DB account $accountName to confirm lock removal" 51 | Get-AzResourceLock ` 52 | -ApiVersion $apiVersion ` 53 | -ResourceGroupName $resourceGroupName ` 54 | -ResourceType $resourceTypeAccount ` 55 | -ResourceName $accountName 56 | -------------------------------------------------------------------------------- /virtual-machine/create-snapshots-from-vhd-in-different-subscription/create-snapshots-from-vhd-in-different-subscription.ps1: -------------------------------------------------------------------------------- 1 | #Provide the subscription Id where snapshot will be created 2 | $subscriptionId = 'yourSubscriptionId' 3 | 4 | #Provide the name of your resource group where snapshot will be created. 5 | $resourceGroupName ='yourResourceGroupName' 6 | 7 | #Provide the name of the snapshot 8 | $snapshotName = 'yourSnapshotName' 9 | 10 | #Provide the storage type for snapshot. PremiumLRS or StandardLRS. 11 | $storageType = 'StandardLRS' 12 | 13 | #Provide the Azure region (e.g. westus) where snapshot will be located. 14 | #This location should be same as the storage account location where VHD file is stored 15 | #Get all the Azure location using command below: 16 | #Get-AzLocation 17 | $location = 'westus' 18 | 19 | #Provide the URI of the VHD file (page blob) in a storage account. Please not that this is NOT the SAS URI of the storage container where VHD file is stored. 20 | #e.g. https://contosostorageaccount1.blob.core.windows.net/vhds/contosovhd123.vhd 21 | #Note: VHD file can be deleted as soon as Managed Disk is created. 22 | $sourceVHDURI = 'https://yourStorageAccountName.blob.core.windows.net/vhds/yourVHDName.vhd' 23 | 24 | #Provide the resource Id of the storage account where VHD file is stored. 25 | #e.g. /subscriptions/6582b1g7-e212-446b-b509-314e17e1efb0/resourceGroups/MDDemo/providers/Microsoft.Storage/storageAccounts/contosostorageaccount1 26 | #This is an optional parameter if you are creating snapshot in the same subscription 27 | $storageAccountId = '/subscriptions/yourSubscriptionId/resourceGroups/yourResourceGroupName/providers/Microsoft.Storage/storageAccounts/yourStorageAccountName' 28 | 29 | #Set the context to the subscription Id where Managed Disk will be created 30 | Select-AzSubscription -SubscriptionId $SubscriptionId 31 | 32 | $snapshotConfig = New-AzSnapshotConfig -AccountType $storageType -Location $location -CreateOption Import -StorageAccountId $storageAccountId -SourceUri $sourceVHDURI 33 | 34 | New-AzSnapshot -Snapshot $snapshotConfig -ResourceGroupName $resourceGroupName -SnapshotName $snapshotName 35 | 36 | -------------------------------------------------------------------------------- /cosmosdb/sql/ps-container-large-partition-key.ps1: -------------------------------------------------------------------------------- 1 | # Reference: Az.CosmosDB | https://docs.microsoft.com/powershell/module/az.cosmosdb 2 | # -------------------------------------------------- 3 | # Purpose 4 | # Create Cosmos DB SQL API account, database, and container with dedicated throughput and no indexing policy 5 | # -------------------------------------------------- 6 | Function New-RandomString{Param ([Int]$Length = 10) return $(-join ((97..122) + (48..57) | Get-Random -Count $Length | ForEach-Object {[char]$_}))} 7 | # -------------------------------------------------- 8 | $uniqueId = New-RandomString -Length 7 # Random alphanumeric string for unique resource names 9 | $apiKind = "Sql" 10 | # -------------------------------------------------- 11 | # Variables - ***** SUBSTITUTE YOUR VALUES ***** 12 | $locations = @() 13 | $locations += New-AzCosmosDBLocationObject -LocationName "East Us" -FailoverPriority 0 -IsZoneRedundant 0 14 | $locations += New-AzCosmosDBLocationObject -LocationName "West Us" -FailoverPriority 1 -IsZoneRedundant 0 15 | 16 | $resourceGroupName = "myResourceGroup" # Resource Group must already exist 17 | $accountName = "cosmos-$uniqueId" # Must be all lower case 18 | $consistencyLevel = "Session" 19 | $tags = @{Tag1 = "MyTag1"; Tag2 = "MyTag2"; Tag3 = "MyTag3"} 20 | $databaseName = "myDatabase" 21 | $containerName = "myContainer" 22 | $containerRUs = 400 23 | $partitionKeyPath = "/myPartitionKey" 24 | # -------------------------------------------------- 25 | Write-Host "Creating account $accountName" 26 | $account = New-AzCosmosDBAccount -ResourceGroupName $resourceGroupName ` 27 | -LocationObject $locations -Name $accountName -ApiKind $apiKind -Tag $tags ` 28 | -DefaultConsistencyLevel $consistencyLevel ` 29 | -EnableAutomaticFailover:$true 30 | 31 | Write-Host "Creating database $databaseName" 32 | $database = New-AzCosmosDBSqlDatabase -ParentObject $account -Name $databaseName 33 | 34 | Write-Host "Creating container $containerName" 35 | $container = New-AzCosmosDBSqlContainer ` 36 | -ParentObject $database -Name $containerName ` 37 | -Throughput $containerRUs -PartitionKeyVersion 2 ` 38 | -PartitionKeyKind Hash -PartitionKeyPath $partitionKeyPath 39 | -------------------------------------------------------------------------------- /app-service/deploy-ftp/deploy-ftp.ps1: -------------------------------------------------------------------------------- 1 | $filePath="" 2 | $webappname="mywebapp$(Get-Random)" 3 | $location="West Europe" 4 | 5 | # Create a resource group. 6 | New-AzResourceGroup -Name myResourceGroup -Location $location 7 | 8 | # Create an App Service plan in `Free` tier. 9 | New-AzAppServicePlan -Name $webappname -Location $location ` 10 | -ResourceGroupName myResourceGroup -Tier Free 11 | 12 | # Create a web app. 13 | New-AzWebApp -Name $webappname -Location $location -AppServicePlan $webappname ` 14 | -ResourceGroupName myResourceGroup 15 | 16 | # Get publishing profile for the web app 17 | $xml = [xml](Get-AzWebAppPublishingProfile -Name $webappname ` 18 | -ResourceGroupName myResourceGroup ` 19 | -OutputFile null) 20 | 21 | # Extract connection information from publishing profile 22 | $username = $xml.SelectNodes("//publishProfile[@publishMethod=`"FTP`"]/@userName").value 23 | $password = $xml.SelectNodes("//publishProfile[@publishMethod=`"FTP`"]/@userPWD").value 24 | $url = $xml.SelectNodes("//publishProfile[@publishMethod=`"FTP`"]/@publishUrl").value 25 | 26 | # Upload file 27 | $file = Get-Item -Path $filePath 28 | $uri = New-Object System.Uri("$url/$($file.Name)") 29 | 30 | $request = [System.Net.FtpWebRequest]([System.net.WebRequest]::Create($uri)) 31 | $request.Method = [System.Net.WebRequestMethods+Ftp]::UploadFile 32 | $request.Credentials = New-Object System.Net.NetworkCredential($username,$password) 33 | 34 | # Enable SSL for FTPS. Should be $false if FTP. 35 | $request.EnableSsl = $true; 36 | 37 | # Write the file to the request object. 38 | $fileBytes = [System.IO.File]::ReadAllBytes($filePath) 39 | $request.ContentLength = $fileBytes.Length; 40 | $requestStream = $request.GetRequestStream() 41 | 42 | try { 43 | $requestStream.Write($fileBytes, 0, $fileBytes.Length) 44 | } 45 | finally { 46 | $requestStream.Dispose() 47 | } 48 | 49 | Write-Host "Uploading to $($uri.AbsoluteUri)" 50 | 51 | try { 52 | $response = [System.Net.FtpWebResponse]($request.GetResponse()) 53 | Write-Host "Status: $($response.StatusDescription)" 54 | } 55 | finally { 56 | if ($null -ne $response) { 57 | $response.Close() 58 | } 59 | } -------------------------------------------------------------------------------- /api-management/backup-restore-apim-service/backup_restore_apim_service.ps1: -------------------------------------------------------------------------------- 1 | ########################################################## 2 | # Script to backup and restore api management service. 3 | ########################################################### 4 | 5 | $random = (New-Guid).ToString().Substring(0,8) 6 | 7 | # Azure specific details 8 | $subscriptionId = "my-azure-subscription-id" 9 | 10 | # Api Management service specific details 11 | $apiManagementName = "apim-$random" 12 | $resourceGroupName = "apim-rg-$random" 13 | $location = "Japan East" 14 | $organisation = "Contoso" 15 | $adminEmail = "admin@contoso.com" 16 | 17 | # Storage Account details 18 | $storageAccountName = "backup$random" 19 | $containerName = "backups" 20 | $backupName = $apiManagementName + "-apimbackup" 21 | 22 | # Select default azure subscription 23 | Select-AzSubscription -SubscriptionId $subscriptionId 24 | 25 | # Create a Resource Group 26 | New-AzResourceGroup -Name $resourceGroupName -Location $location -Force 27 | 28 | # Create storage account 29 | New-AzStorageAccount -StorageAccountName $storageAccountName -Location $location -ResourceGroupName $resourceGroupName -Type Standard_LRS 30 | $storageKey = (Get-AzStorageAccountKey -ResourceGroupName $resourceGroupName -StorageAccountName $storageAccountName)[0].Value 31 | $storageContext = New-AzStorageContext -StorageAccountName $storageAccountName -StorageAccountKey $storageKey 32 | 33 | # Create blob container 34 | New-AzStorageContainer -Name $containerName -Context $storageContext -Permission blob 35 | 36 | # Create API Management service 37 | New-AzApiManagement -ResourceGroupName $resourceGroupName -Location $location -Name $apiManagementName -Organization $organisation -AdminEmail $adminEmail 38 | 39 | # Backup API Management service. 40 | Backup-AzApiManagement -ResourceGroupName $resourceGroupName -Name $apiManagementName -StorageContext $storageContext -TargetContainerName $containerName -TargetBlobName $backupName 41 | 42 | # Restore API Management service 43 | Restore-AzApiManagement -ResourceGroupName $resourceGroupName -Name $apiManagementName -StorageContext $storageContext -SourceContainerName $containerName -SourceBlobName $backupName 44 | -------------------------------------------------------------------------------- /site-recovery/dr-at-scale-onpremise-azure/asr_failover.ps1: -------------------------------------------------------------------------------- 1 | Param( 2 | [parameter(Mandatory=$true)] 3 | $CsvFilePath 4 | ) 5 | 6 | $ErrorActionPreference = "Stop" 7 | 8 | $scriptsPath = $PSScriptRoot 9 | if ($PSScriptRoot -eq "") { 10 | $scriptsPath = "." 11 | } 12 | 13 | . "$scriptsPath\asr_logger.ps1" 14 | . "$scriptsPath\asr_common.ps1" 15 | . "$scriptsPath\asr_csv_processor.ps1" 16 | 17 | Function ProcessItemImpl($processor, $csvItem, $reportItem) { 18 | $reportItem | Add-Member NoteProperty "FailoverJobId" $null 19 | 20 | $vaultName = $csvItem.VAULT_NAME 21 | $sourceMachineName = $csvItem.SOURCE_MACHINE_NAME 22 | $sourceConfigurationServer = $csvItem.CONFIGURATION_SERVER 23 | 24 | $protectedItem = $asrCommon.GetProtectedItemFromVault($vaultName, $sourceMachineName, $sourceConfigurationServer) 25 | if ($protectedItem -ne $null) { 26 | if ($protectedItem.AllowedOperations.Contains('UnplannedFailover')) { 27 | $processor.Logger.LogTrace("Starting UnplannedFailover operation for item '$($sourceMachineName)'") 28 | $targetFailoverJob = Start-AzureRmRecoveryServicesAsrUnplannedFailoverJob ` 29 | -ReplicationProtectedItem $protectedItem ` 30 | -Direction PrimaryToRecovery 31 | 32 | $reportItem.FailoverJobId = $targetFailoverJob.ID 33 | } else { 34 | $processor.Logger.LogTrace("UnplannedFailover operation not allowed for item '$($sourceMachineName)'") 35 | } 36 | } else { 37 | $processor.Logger.LogTrace("'$($sourceMachineName)' item is not in a protected state ready for replication") 38 | } 39 | } 40 | 41 | Function ProcessItem($processor, $csvItem, $reportItem) { 42 | try { 43 | ProcessItemImpl $processor $csvItem $reportItem 44 | } 45 | catch { 46 | $exceptionMessage = $_ | Out-String 47 | $processor.Logger.LogError($exceptionMessage) 48 | throw 49 | } 50 | } 51 | 52 | $logger = New-AsrLoggerInstance -CommandPath $PSCommandPath 53 | $asrCommon = New-AsrCommonInstance -Logger $logger 54 | $processor = New-CsvProcessorInstance -Logger $logger -ProcessItemFunction $function:ProcessItem 55 | $processor.ProcessFile($CsvFilePath) 56 | -------------------------------------------------------------------------------- /azure-migrate/migrate-at-scale-with-site-recovery/asr_migration.ps1: -------------------------------------------------------------------------------- 1 | Param( 2 | [parameter(Mandatory=$true)] 3 | $CsvFilePath 4 | ) 5 | 6 | $ErrorActionPreference = "Stop" 7 | 8 | $scriptsPath = $PSScriptRoot 9 | if ($PSScriptRoot -eq "") { 10 | $scriptsPath = "." 11 | } 12 | 13 | . "$scriptsPath\asr_logger.ps1" 14 | . "$scriptsPath\asr_common.ps1" 15 | . "$scriptsPath\asr_csv_processor.ps1" 16 | 17 | Function ProcessItemImpl($processor, $csvItem, $reportItem) { 18 | $reportItem | Add-Member NoteProperty "FailoverJobId" $null 19 | 20 | $vaultName = $csvItem.VAULT_NAME 21 | $sourceMachineName = $csvItem.SOURCE_MACHINE_NAME 22 | $sourceConfigurationServer = $csvItem.CONFIGURATION_SERVER 23 | 24 | $protectedItem = $asrCommon.GetProtectedItemFromVault($vaultName, $sourceMachineName, $sourceConfigurationServer) 25 | if ($protectedItem -ne $null) { 26 | if ($protectedItem.AllowedOperations.Contains('UnplannedFailover')) { 27 | $processor.Logger.LogTrace("Starting UnplannedFailover operation for item '$($sourceMachineName)'") 28 | $targetFailoverJob = Start-AzRecoveryServicesAsrUnplannedFailoverJob ` 29 | -ReplicationProtectedItem $protectedItem ` 30 | -Direction PrimaryToRecovery 31 | 32 | $reportItem.FailoverJobId = $targetFailoverJob.ID 33 | } else { 34 | $processor.Logger.LogTrace("UnplannedFailover operation not allowed for item '$($sourceMachineName)'") 35 | } 36 | } else { 37 | $processor.Logger.LogTrace("'$($sourceMachineName)' item is not in a protected state ready for replication") 38 | } 39 | } 40 | 41 | Function ProcessItem($processor, $csvItem, $reportItem) { 42 | try { 43 | ProcessItemImpl $processor $csvItem $reportItem 44 | } 45 | catch { 46 | $exceptionMessage = $_ | Out-String 47 | $processor.Logger.LogError($exceptionMessage) 48 | throw 49 | } 50 | } 51 | 52 | $logger = New-AsrLoggerInstance -CommandPath $PSCommandPath 53 | $asrCommon = New-AsrCommonInstance -Logger $logger 54 | $processor = New-CsvProcessorInstance -Logger $logger -ProcessItemFunction $function:ProcessItem 55 | $processor.ProcessFile($CsvFilePath) 56 | -------------------------------------------------------------------------------- /azure-migrate/migrate-at-scale-with-site-recovery/asr_list_protectables.ps1: -------------------------------------------------------------------------------- 1 | Param( 2 | [parameter(Mandatory=$true)] 3 | $SubscriptionId, 4 | [parameter(Mandatory=$true)] 5 | $VaultName, 6 | [parameter(Mandatory=$true)] 7 | $ConfigurationServer, 8 | [parameter(Mandatory=$true)] 9 | $CsvOutput 10 | ) 11 | 12 | class ProtectableItemInfo 13 | { 14 | [string]$Machine 15 | [string]$ProtectionStatus 16 | } 17 | 18 | $currentContext = Get-AzContext 19 | $currentSubscription = $currentContext.Subscription 20 | if ($currentSubscription.Id -ne $subscriptionId) 21 | { 22 | Set-AzContext -Subscription $subscriptionId 23 | $currentContext = Get-AzContext 24 | $currentSubscription = $currentContext.Subscription 25 | if ($currentSubscription.Id -ne $subscriptionId) 26 | { 27 | LogErrorAndThrow("SubscriptionId '$($subscriptionId)' is not selected as current default subscription") 28 | } 29 | } 30 | 31 | $targetVault = Get-AzRecoveryServicesVault -Name $VaultName 32 | if ($targetVault -eq $null) 33 | { 34 | LogError("Vault with name '$($vaultName)' unable to find") 35 | } 36 | 37 | Set-AzRecoveryServicesAsrVaultContext -Vault $targetVault 38 | $fabricServer = Get-AzRecoveryServicesAsrFabric ` 39 | -FriendlyName $ConfigurationServer 40 | $protectionContainer = Get-AzRecoveryServicesAsrProtectionContainer ` 41 | -Fabric $fabricServer 42 | 43 | $items = Get-AzRecoveryServicesAsrProtectableItem ` 44 | -ProtectionContainer $protectionContainer 45 | 46 | $protectedItemStatusArray = New-Object System.Collections.Generic.List[System.Object] 47 | if ($items.Count -gt 0) 48 | { 49 | foreach ($item in $items) 50 | { 51 | $statusItemInfo = [ProtectableItemInfo]::new() 52 | $statusItemInfo.Machine = $item.FriendlyName 53 | $statusItemInfo.ProtectionStatus = $item.ProtectionStatus 54 | 55 | $protectedItemStatusArray.Add($statusItemInfo) 56 | } 57 | 58 | $protectedItemStatusArray.ToArray() | Export-Csv $CsvOutput -Delimiter ',' -NoTypeInformation 59 | Write-Host "Information written in csv file '$($CsvOutput)'" 60 | } else { 61 | Write-Host "There are no items in this container" 62 | } 63 | 64 | 65 | 66 | 67 | -------------------------------------------------------------------------------- /virtual-network/create-windows-vm-detailed.ps1: -------------------------------------------------------------------------------- 1 | # Variables for common values 2 | $resourceGroup = "myResourceGroup" 3 | $location = "westeurope" 4 | $vmName = "myVM" 5 | 6 | # Create user object 7 | $cred = Get-Credential -Message "Enter a username and password for the virtual machine." 8 | 9 | # Create a resource group 10 | New-AzResourceGroup -Name $resourceGroup -Location $location 11 | 12 | # Create a subnet configuration 13 | $subnetConfig = New-AzVirtualNetworkSubnetConfig -Name mySubnet -AddressPrefix 192.168.1.0/24 14 | 15 | # Create a virtual network 16 | $vnet = New-AzVirtualNetwork -ResourceGroupName $resourceGroup -Location $location ` 17 | -Name MYvNET -AddressPrefix 192.168.0.0/16 -Subnet $subnetConfig 18 | 19 | # Create a public IP address and specify a DNS name 20 | $pip = New-AzPublicIpAddress -ResourceGroupName $resourceGroup -Location $location ` 21 | -Name "mypublicdns$(Get-Random)" -AllocationMethod Static -IdleTimeoutInMinutes 4 22 | 23 | # Create an inbound network security group rule for port 3389 24 | $nsgRuleRDP = New-AzNetworkSecurityRuleConfig -Name myNetworkSecurityGroupRuleRDP -Protocol Tcp ` 25 | -Direction Inbound -Priority 1000 -SourceAddressPrefix * -SourcePortRange * -DestinationAddressPrefix * ` 26 | -DestinationPortRange 3389 -Access Allow 27 | 28 | # Create a network security group 29 | $nsg = New-AzNetworkSecurityGroup -ResourceGroupName $resourceGroup -Location $location ` 30 | -Name myNetworkSecurityGroup -SecurityRules $nsgRuleRDP 31 | 32 | # Create a virtual network card and associate with public IP address and NSG 33 | $nic = New-AzNetworkInterface -Name myNic -ResourceGroupName $resourceGroup -Location $location ` 34 | -SubnetId $vnet.Subnets[0].Id -PublicIpAddressId $pip.Id -NetworkSecurityGroupId $nsg.Id 35 | 36 | # Create a virtual machine configuration 37 | $vmConfig = New-AzVMConfig -VMName $vmName -VMSize Standard_D1 | ` 38 | Set-AzVMOperatingSystem -Windows -ComputerName $vmName -Credential $cred | ` 39 | Set-AzVMSourceImage -PublisherName MicrosoftWindowsServer -Offer WindowsServer -Skus 2016-Datacenter -Version latest | ` 40 | Add-AzVMNetworkInterface -Id $nic.Id 41 | 42 | # Create a virtual machine 43 | New-AzVM -ResourceGroupName $resourceGroup -Location $location -VM $vmConfig 44 | -------------------------------------------------------------------------------- /cosmosdb/sql/ps-container-create-index-none.ps1: -------------------------------------------------------------------------------- 1 | # Reference: Az.CosmosDB | https://docs.microsoft.com/powershell/module/az.cosmosdb 2 | # -------------------------------------------------- 3 | # Purpose 4 | # Create Cosmos SQL API account, database, and container with dedicated throughput and no indexing policy 5 | # -------------------------------------------------- 6 | Function New-RandomString{Param ([Int]$Length = 10) return $(-join ((97..122) + (48..57) | Get-Random -Count $Length | ForEach-Object {[char]$_}))} 7 | # -------------------------------------------------- 8 | $uniqueId = New-RandomString -Length 7 # Random alphanumeric string for unique resource names 9 | $apiKind = "Sql" 10 | # -------------------------------------------------- 11 | # Variables - ***** SUBSTITUTE YOUR VALUES ***** 12 | $locations = @() 13 | $locations += New-AzCosmosDBLocationObject -LocationName "East Us" -FailoverPriority 0 -IsZoneRedundant 0 14 | $locations += New-AzCosmosDBLocationObject -LocationName "West Us" -FailoverPriority 1 -IsZoneRedundant 0 15 | 16 | $resourceGroupName = "myResourceGroup" # Resource Group must already exist 17 | $accountName = "cosmos-$uniqueId" # Must be all lower case 18 | $consistencyLevel = "Session" 19 | $tags = @{Tag1 = "MyTag1"; Tag2 = "MyTag2"; Tag3 = "MyTag3"} 20 | $databaseName = "myDatabase" 21 | $containerName = "myContainer" 22 | $containerRUs = 400 23 | $partitionKeyPath = "/myPartitionKey" 24 | # -------------------------------------------------- 25 | Write-Host "Creating account $accountName" 26 | $account = New-AzCosmosDBAccount -ResourceGroupName $resourceGroupName ` 27 | -LocationObject $locations -Name $accountName -ApiKind $apiKind -Tag $tags ` 28 | -DefaultConsistencyLevel $consistencyLevel ` 29 | -EnableAutomaticFailover:$true 30 | 31 | Write-Host "Creating database $databaseName" 32 | $database = New-AzCosmosDBSqlDatabase -ParentObject $account -Name $databaseName 33 | 34 | $indexingPolicy = New-AzCosmosDBSqlIndexingPolicy -IndexingMode None 35 | 36 | Write-Host "Creating container $containerName" 37 | $container = New-AzCosmosDBSqlContainer ` 38 | -ParentObject $database -Name $containerName ` 39 | -Throughput $containerRUs -IndexingPolicy $indexingPolicy ` 40 | -PartitionKeyKind Hash -PartitionKeyPath $partitionKeyPath 41 | -------------------------------------------------------------------------------- /virtual-machine/create-vm-detailed/create-windows-vm-detailed.ps1: -------------------------------------------------------------------------------- 1 | # Variables for common values 2 | $resourceGroup = "myResourceGroup" 3 | $location = "westeurope" 4 | $vmName = "myVM" 5 | 6 | # Create user object 7 | $cred = Get-Credential -Message "Enter a username and password for the virtual machine." 8 | 9 | # Create a resource group 10 | New-AzResourceGroup -Name $resourceGroup -Location $location 11 | 12 | # Create a subnet configuration 13 | $subnetConfig = New-AzVirtualNetworkSubnetConfig -Name mySubnet -AddressPrefix 192.168.1.0/24 14 | 15 | # Create a virtual network 16 | $vnet = New-AzVirtualNetwork -ResourceGroupName $resourceGroup -Location $location ` 17 | -Name MYvNET -AddressPrefix 192.168.0.0/16 -Subnet $subnetConfig 18 | 19 | # Create a public IP address and specify a DNS name 20 | $pip = New-AzPublicIpAddress -ResourceGroupName $resourceGroup -Location $location ` 21 | -Name "mypublicdns$(Get-Random)" -AllocationMethod Static -IdleTimeoutInMinutes 4 22 | 23 | # Create an inbound network security group rule for port 3389 24 | $nsgRuleRDP = New-AzNetworkSecurityRuleConfig -Name myNetworkSecurityGroupRuleRDP -Protocol Tcp ` 25 | -Direction Inbound -Priority 1000 -SourceAddressPrefix * -SourcePortRange * -DestinationAddressPrefix * ` 26 | -DestinationPortRange 3389 -Access Allow 27 | 28 | # Create a network security group 29 | $nsg = New-AzNetworkSecurityGroup -ResourceGroupName $resourceGroup -Location $location ` 30 | -Name myNetworkSecurityGroup -SecurityRules $nsgRuleRDP 31 | 32 | # Create a virtual network card and associate with public IP address and NSG 33 | $nic = New-AzNetworkInterface -Name myNic -ResourceGroupName $resourceGroup -Location $location ` 34 | -SubnetId $vnet.Subnets[0].Id -PublicIpAddressId $pip.Id -NetworkSecurityGroupId $nsg.Id 35 | 36 | # Create a virtual machine configuration 37 | $vmConfig = New-AzVMConfig -VMName $vmName -VMSize Standard_D1 | ` 38 | Set-AzVMOperatingSystem -Windows -ComputerName $vmName -Credential $cred | ` 39 | Set-AzVMSourceImage -PublisherName MicrosoftWindowsServer -Offer WindowsServer -Skus 2016-Datacenter -Version latest | ` 40 | Add-AzVMNetworkInterface -Id $nic.Id 41 | 42 | # Create a virtual machine 43 | New-AzVM -ResourceGroupName $resourceGroup -Location $location -VM $vmConfig 44 | -------------------------------------------------------------------------------- /site-recovery/dr-at-scale-onpremise-azure/asr_list_protectables.ps1: -------------------------------------------------------------------------------- 1 | Param( 2 | [parameter(Mandatory=$true)] 3 | $SubscriptionId, 4 | [parameter(Mandatory=$true)] 5 | $VaultName, 6 | [parameter(Mandatory=$true)] 7 | $ConfigurationServer, 8 | [parameter(Mandatory=$true)] 9 | $CsvOutput 10 | ) 11 | 12 | class ProtectableItemInfo 13 | { 14 | [string]$Machine 15 | [string]$ProtectionStatus 16 | } 17 | 18 | $currentContext = Get-AzureRmContext 19 | $currentSubscription = $currentContext.Subscription 20 | if ($currentSubscription.Id -ne $subscriptionId) 21 | { 22 | Set-AzureRmContext -Subscription $subscriptionId 23 | $currentContext = Get-AzureRmContext 24 | $currentSubscription = $currentContext.Subscription 25 | if ($currentSubscription.Id -ne $subscriptionId) 26 | { 27 | LogErrorAndThrow("SubscriptionId '$($subscriptionId)' is not selected as current default subscription") 28 | } 29 | } 30 | 31 | $targetVault = Get-AzureRmRecoveryServicesVault -Name $VaultName 32 | if ($targetVault -eq $null) 33 | { 34 | LogError("Vault with name '$($vaultName)' unable to find") 35 | } 36 | 37 | Set-AzureRmRecoveryServicesAsrVaultContext -Vault $targetVault 38 | $fabricServer = Get-AzureRmRecoveryServicesAsrFabric ` 39 | -FriendlyName $ConfigurationServer 40 | $protectionContainer = Get-AzureRmRecoveryServicesAsrProtectionContainer ` 41 | -Fabric $fabricServer 42 | 43 | $items = Get-AzureRmRecoveryServicesAsrProtectableItem ` 44 | -ProtectionContainer $protectionContainer 45 | 46 | $protectedItemStatusArray = New-Object System.Collections.Generic.List[System.Object] 47 | if ($items.Count -gt 0) 48 | { 49 | foreach ($item in $items) 50 | { 51 | $statusItemInfo = [ProtectableItemInfo]::new() 52 | $statusItemInfo.Machine = $item.FriendlyName 53 | $statusItemInfo.ProtectionStatus = $item.ProtectionStatus 54 | 55 | $protectedItemStatusArray.Add($statusItemInfo) 56 | } 57 | 58 | $protectedItemStatusArray.ToArray() | Export-Csv $CsvOutput -Delimiter ',' -NoTypeInformation 59 | Write-Host "Information written in csv file '$($CsvOutput)'" 60 | } else { 61 | Write-Host "There are no items in this container" 62 | } 63 | 64 | 65 | 66 | 67 | -------------------------------------------------------------------------------- /site-recovery/dr-at-scale-onpremise-azure/asr_logger.ps1: -------------------------------------------------------------------------------- 1 | class MigrationLogger { 2 | 3 | [string]$CurrentCommandPath 4 | [string]$OutputFilePath 5 | [string]$ScriptName 6 | [DateTime]$StartDate 7 | 8 | MigrationLogger([string] $CurrentCommandPath) { 9 | $this.StartDate = Get-Date 10 | $this.CurrentCommandPath = $CurrentCommandPath 11 | $this.ScriptName = Split-Path $CurrentCommandPath -Leaf 12 | $fileName = [string]::Concat("log.", $this.ScriptName, ".", $this.FormatDate($this.StartDate), ".txt") 13 | 14 | $this.OutputFilePath = $this.ReplaceLastSubstring($CurrentCommandPath, $this.ScriptName, $fileName) 15 | } 16 | 17 | [string] FormatDate($date) { 18 | return $date.ToString("yyyyMMdd_HHmmss") 19 | } 20 | 21 | [string] FormatCurrentDate() { 22 | $currentDate = Get-Date 23 | return $this.FormatDate($currentDate) 24 | } 25 | 26 | [string] ReplaceLastSubstring([string]$str, [string]$substr, [string]$newstr) 27 | { 28 | $lastIndex = $str.LastIndexOf($substr) 29 | $result = $str.Remove($lastIndex,$substr.Length).Insert($lastIndex,$newstr) 30 | return $result 31 | } 32 | 33 | [void] LogError([string] $Message) 34 | { 35 | $logDate = $this.FormatCurrentDate() 36 | $logMessage = [string]::Concat($logDate, "[ERROR]-", $Message) 37 | $logMessage | Out-File -FilePath $this.OutputFilePath -Append 38 | Write-Host $logMessage -ForegroundColor Yellow 39 | } 40 | 41 | [void] LogErrorAndThrow([string] $Message) 42 | { 43 | $logDate = $this.FormatCurrentDate() 44 | $logMessage = [string]::Concat($logDate, "[ERROR]-", $Message) 45 | $logMessage | Out-File -FilePath $this.OutputFilePath -Append 46 | Write-Error $logMessage 47 | } 48 | 49 | [void] LogTrace([string] $Message) 50 | { 51 | $logDate = $this.FormatCurrentDate() 52 | $logMessage = [string]::Concat($logDate, "[LOG]-", $Message) 53 | $logMessage | Out-File -FilePath $this.OutputFilePath -Append 54 | Write-Host $logMessage 55 | } 56 | 57 | } 58 | 59 | 60 | Function New-AsrLoggerInstance($CommandPath) 61 | { 62 | return [MigrationLogger]::new($CommandPath) 63 | } 64 | 65 | --------------------------------------------------------------------------------