├── .azure-pipelines ├── credscan-suppressions.json ├── daily-build.yml ├── security-scan.yml └── sign-package.yml ├── .github ├── CONTRIBUTING.md ├── ISSUE_TEMPLATE │ ├── doc-bug.yml │ ├── feature_request.md │ └── issue.md └── workflows │ └── pr-check.yml ├── .gitignore ├── CODE_OF_CONDUCT.md ├── LICENSE ├── README.md ├── SECURITY.md ├── build.proj ├── common └── code-upgrade-samples │ ├── az │ ├── compute-create-dockerhost.ps1 │ ├── compute-create-windowsvm-quick-splatted-params-1.ps1 │ ├── compute-create-windowsvm-quick-splatted-params-2.ps1 │ ├── compute-create-windowsvm-quick-splatted-params-3.ps1 │ ├── compute-create-windowsvm-quick.ps1 │ ├── compute-create-wordpress-mysql.ps1 │ ├── devtestlab-add-marketplace-image-to-lab.ps1 │ ├── dynamic-parameters-test1.ps1 │ ├── network-create-vm-two-nics.ps1 │ ├── network-peer-two-virtual-networks.ps1 │ ├── network-route-traffic-through-nva.ps1 │ ├── sqldb-create-and-configure-database.ps1 │ ├── sqldb-import-from-bacpac.ps1 │ ├── sqldb-move-database-between-pools-and-standalone.ps1 │ ├── sqldb-restore-database.ps1 │ ├── webapp-back-restore.ps1 │ ├── webapp-create-from-github.ps1 │ └── webapp-monitor-with-logs.ps1 │ └── azurerm │ ├── compute-create-dockerhost.ps1 │ ├── compute-create-windowsvm-quick-splatted-params-1.ps1 │ ├── compute-create-windowsvm-quick-splatted-params-2.ps1 │ ├── compute-create-windowsvm-quick-splatted-params-3.ps1 │ ├── compute-create-windowsvm-quick.ps1 │ ├── compute-create-wordpress-mysql.ps1 │ ├── devtestlab-add-marketplace-image-to-lab.ps1 │ ├── dynamic-parameters-test1.ps1 │ ├── network-create-vm-two-nics.ps1 │ ├── network-peer-two-virtual-networks.ps1 │ ├── network-route-traffic-through-nva.ps1 │ ├── sqldb-create-and-configure-database.ps1 │ ├── sqldb-import-from-bacpac.ps1 │ ├── sqldb-move-database-between-pools-and-standalone.ps1 │ ├── sqldb-restore-database.ps1 │ ├── webapp-back-restore.ps1 │ ├── webapp-create-from-github.ps1 │ └── webapp-monitor-with-logs.ps1 ├── docs ├── how-to-update-az-module-spec.md └── quickstart-migrate-azurerm-to-az-automatically.md ├── package-lock.json ├── powershell-module ├── .vscode │ └── settings.json ├── Az.Tools.Migration │ ├── Az.Tools.Migration.format.ps1xml │ ├── Az.Tools.Migration.psd1 │ ├── Az.Tools.Migration.psm1 │ ├── Classes │ │ └── Classes.ps1 │ ├── Functions │ │ ├── Private │ │ │ ├── Confirm-StringBuilderSubstring.ps1 │ │ │ ├── Find-CmdletsInFile.ps1 │ │ │ ├── Get-ModulePreferences.ps1 │ │ │ ├── Invoke-ModuleUpgradeStep.ps1 │ │ │ ├── New-ModifiedFileName.ps1 │ │ │ ├── Out-FileBatchResult.ps1 │ │ │ ├── Send-MetricsIfDataCollectionEnabled.ps1 │ │ │ ├── Send-PageViewTelemetry.ps1 │ │ │ └── Set-ModulePreference.ps1 │ │ └── Public │ │ │ ├── Disable-AzUpgradeDataCollection.ps1 │ │ │ ├── Enable-AzUpgradeDataCollection.ps1 │ │ │ ├── Find-AzUpgradeCommandReference.ps1 │ │ │ ├── Get-AzUpgradeAliasSpec.ps1 │ │ │ ├── Get-AzUpgradeCmdletSpec.ps1 │ │ │ ├── Invoke-AzUpgradeModulePlan.ps1 │ │ │ └── New-AzUpgradeModulePlan.ps1 │ ├── Resources │ │ ├── Assembly │ │ │ ├── Microsoft.ApplicationInsights.2.12.0 │ │ │ │ └── Microsoft.ApplicationInsights.dll │ │ │ └── Newtonsoft.Json.12.0.3 │ │ │ │ └── Newtonsoft.Json.dll │ │ ├── ModuleSpecs │ │ │ ├── Az │ │ │ │ └── Latest │ │ │ │ │ └── 11.0.0 │ │ │ │ │ ├── Az.Accounts.2.13.2.Cmdlets.json │ │ │ │ │ ├── Az.Advisor.2.0.0.Cmdlets.json │ │ │ │ │ ├── Az.Aks.6.0.0.Cmdlets.json │ │ │ │ │ ├── Az.AnalysisServices.1.1.4.Cmdlets.json │ │ │ │ │ ├── Az.ApiManagement.4.0.2.Cmdlets.json │ │ │ │ │ ├── Az.App.1.0.0.Cmdlets.json │ │ │ │ │ ├── Az.AppConfiguration.1.3.0.Cmdlets.json │ │ │ │ │ ├── Az.ApplicationInsights.2.2.2.Cmdlets.json │ │ │ │ │ ├── Az.ArcResourceBridge.1.0.0.Cmdlets.json │ │ │ │ │ ├── Az.Attestation.2.0.0.Cmdlets.json │ │ │ │ │ ├── Az.Automanage.1.0.0.Cmdlets.json │ │ │ │ │ ├── Az.Automation.1.9.1.Cmdlets.json │ │ │ │ │ ├── Az.Batch.3.5.0.Cmdlets.json │ │ │ │ │ ├── Az.Billing.2.0.3.Cmdlets.json │ │ │ │ │ ├── Az.Cdn.3.1.1.Cmdlets.json │ │ │ │ │ ├── Az.CloudService.2.0.0.Cmdlets.json │ │ │ │ │ ├── Az.CognitiveServices.1.14.1.Cmdlets.json │ │ │ │ │ ├── Az.Compute.7.0.0.Cmdlets.json │ │ │ │ │ ├── Az.ConfidentialLedger.1.0.0.Cmdlets.json │ │ │ │ │ ├── Az.ContainerInstance.4.0.0.Cmdlets.json │ │ │ │ │ ├── Az.ContainerRegistry.4.1.2.Cmdlets.json │ │ │ │ │ ├── Az.CosmosDB.1.13.0.Cmdlets.json │ │ │ │ │ ├── Az.DataBoxEdge.1.1.0.Cmdlets.json │ │ │ │ │ ├── Az.DataFactory.1.17.1.Cmdlets.json │ │ │ │ │ ├── Az.DataLakeAnalytics.1.0.3.Cmdlets.json │ │ │ │ │ ├── Az.DataLakeStore.1.3.0.Cmdlets.json │ │ │ │ │ ├── Az.DataProtection.2.1.0.Cmdlets.json │ │ │ │ │ ├── Az.DataShare.1.0.1.Cmdlets.json │ │ │ │ │ ├── Az.Databricks.1.7.1.Cmdlets.json │ │ │ │ │ ├── Az.DeploymentManager.1.1.0.Cmdlets.json │ │ │ │ │ ├── Az.DesktopVirtualization.4.2.0.Cmdlets.json │ │ │ │ │ ├── Az.DevCenter.1.0.0.Cmdlets.json │ │ │ │ │ ├── Az.DevTestLabs.1.0.2.Cmdlets.json │ │ │ │ │ ├── Az.Dns.1.2.0.Cmdlets.json │ │ │ │ │ ├── Az.EventGrid.1.6.0.Cmdlets.json │ │ │ │ │ ├── Az.EventHub.4.2.0.Cmdlets.json │ │ │ │ │ ├── Az.FrontDoor.1.10.0.Cmdlets.json │ │ │ │ │ ├── Az.Functions.4.0.7.Cmdlets.json │ │ │ │ │ ├── Az.HDInsight.6.0.2.Cmdlets.json │ │ │ │ │ ├── Az.HealthcareApis.2.0.0.Cmdlets.json │ │ │ │ │ ├── Az.IotHub.2.7.5.Cmdlets.json │ │ │ │ │ ├── Az.KeyVault.5.0.0.Cmdlets.json │ │ │ │ │ ├── Az.Kusto.2.3.0.Cmdlets.json │ │ │ │ │ ├── Az.LoadTesting.1.0.0.Cmdlets.json │ │ │ │ │ ├── Az.LogicApp.1.5.0.Cmdlets.json │ │ │ │ │ ├── Az.MachineLearning.1.1.3.Cmdlets.json │ │ │ │ │ ├── Az.MachineLearningServices.1.0.0.Cmdlets.json │ │ │ │ │ ├── Az.Maintenance.1.4.0.Cmdlets.json │ │ │ │ │ ├── Az.ManagedServiceIdentity.1.1.1.Cmdlets.json │ │ │ │ │ ├── Az.ManagedServices.3.0.0.Cmdlets.json │ │ │ │ │ ├── Az.MarketplaceOrdering.2.0.0.Cmdlets.json │ │ │ │ │ ├── Az.Media.1.1.2.Cmdlets.json │ │ │ │ │ ├── Az.Migrate.2.2.0.Cmdlets.json │ │ │ │ │ ├── Az.Monitor.5.0.0.Cmdlets.json │ │ │ │ │ ├── Az.MySql.1.1.1.Cmdlets.json │ │ │ │ │ ├── Az.Network.7.0.0.Cmdlets.json │ │ │ │ │ ├── Az.NetworkCloud.1.0.0.Cmdlets.json │ │ │ │ │ ├── Az.NotificationHubs.1.1.2.Cmdlets.json │ │ │ │ │ ├── Az.OperationalInsights.3.2.0.Cmdlets.json │ │ │ │ │ ├── Az.PolicyInsights.1.6.4.Cmdlets.json │ │ │ │ │ ├── Az.PostgreSql.1.1.0.Cmdlets.json │ │ │ │ │ ├── Az.PowerBIEmbedded.2.0.0.Cmdlets.json │ │ │ │ │ ├── Az.PrivateDns.1.0.4.Cmdlets.json │ │ │ │ │ ├── Az.RecoveryServices.6.6.1.Cmdlets.json │ │ │ │ │ ├── Az.RedisCache.1.8.1.Cmdlets.json │ │ │ │ │ ├── Az.RedisEnterpriseCache.1.2.0.Cmdlets.json │ │ │ │ │ ├── Az.Relay.2.0.0.Cmdlets.json │ │ │ │ │ ├── Az.ResourceMover.1.2.0.Cmdlets.json │ │ │ │ │ ├── Az.Resources.6.12.0.Cmdlets.json │ │ │ │ │ ├── Az.Security.1.5.0.Cmdlets.json │ │ │ │ │ ├── Az.SecurityInsights.3.1.1.Cmdlets.json │ │ │ │ │ ├── Az.ServiceBus.3.0.0.Cmdlets.json │ │ │ │ │ ├── Az.ServiceFabric.3.3.0.Cmdlets.json │ │ │ │ │ ├── Az.SignalR.2.0.0.Cmdlets.json │ │ │ │ │ ├── Az.Sql.4.11.0.Cmdlets.json │ │ │ │ │ ├── Az.SqlVirtualMachine.2.1.0.Cmdlets.json │ │ │ │ │ ├── Az.StackHCI.2.2.3.Cmdlets.json │ │ │ │ │ ├── Az.Storage.6.0.0.Cmdlets.json │ │ │ │ │ ├── Az.StorageMover.1.2.0.Cmdlets.json │ │ │ │ │ ├── Az.StorageSync.2.1.0.Cmdlets.json │ │ │ │ │ ├── Az.StreamAnalytics.2.0.0.Cmdlets.json │ │ │ │ │ ├── Az.Support.1.0.0.Cmdlets.json │ │ │ │ │ ├── Az.Synapse.3.0.4.Cmdlets.json │ │ │ │ │ ├── Az.TrafficManager.1.2.2.Cmdlets.json │ │ │ │ │ ├── Az.Websites.3.1.2.Cmdlets.json │ │ │ │ │ └── CmdletAliases │ │ │ │ │ └── Aliases.json │ │ │ └── AzureRM │ │ │ │ └── 6.13.1 │ │ │ │ ├── Azure.AnalysisServices.0.5.4.Cmdlets.json │ │ │ │ ├── Azure.Storage.4.6.1.Cmdlets.json │ │ │ │ ├── AzureRM.AnalysisServices.0.6.14.Cmdlets.json │ │ │ │ ├── AzureRM.ApiManagement.6.1.7.Cmdlets.json │ │ │ │ ├── AzureRM.ApplicationInsights.0.1.8.Cmdlets.json │ │ │ │ ├── AzureRM.Automation.6.1.1.Cmdlets.json │ │ │ │ ├── AzureRM.Backup.4.0.11.Cmdlets.json │ │ │ │ ├── AzureRM.Batch.4.1.5.Cmdlets.json │ │ │ │ ├── AzureRM.Billing.0.14.6.Cmdlets.json │ │ │ │ ├── AzureRM.Cdn.5.0.6.Cmdlets.json │ │ │ │ ├── AzureRM.CognitiveServices.0.9.12.Cmdlets.json │ │ │ │ ├── AzureRM.Compute.5.9.1.Cmdlets.json │ │ │ │ ├── AzureRM.Consumption.0.3.7.Cmdlets.json │ │ │ │ ├── AzureRM.ContainerInstance.0.2.12.Cmdlets.json │ │ │ │ ├── AzureRM.ContainerRegistry.1.0.10.Cmdlets.json │ │ │ │ ├── AzureRM.DataFactories.5.0.3.Cmdlets.json │ │ │ │ ├── AzureRM.DataFactoryV2.0.5.11.Cmdlets.json │ │ │ │ ├── AzureRM.DataLakeAnalytics.5.1.4.Cmdlets.json │ │ │ │ ├── AzureRM.DataLakeStore.6.2.1.Cmdlets.json │ │ │ │ ├── AzureRM.DevTestLabs.4.0.9.Cmdlets.json │ │ │ │ ├── AzureRM.Dns.5.1.0.Cmdlets.json │ │ │ │ ├── AzureRM.EventGrid.0.3.7.Cmdlets.json │ │ │ │ ├── AzureRM.EventHub.0.7.0.Cmdlets.json │ │ │ │ ├── AzureRM.HDInsight.4.1.8.Cmdlets.json │ │ │ │ ├── AzureRM.Insights.5.1.5.Cmdlets.json │ │ │ │ ├── AzureRM.IotHub.3.1.8.Cmdlets.json │ │ │ │ ├── AzureRM.KeyVault.5.2.1.Cmdlets.json │ │ │ │ ├── AzureRM.LogicApp.4.1.4.Cmdlets.json │ │ │ │ ├── AzureRM.MachineLearning.0.18.5.Cmdlets.json │ │ │ │ ├── AzureRM.MachineLearningCompute.0.4.8.Cmdlets.json │ │ │ │ ├── AzureRM.MarketplaceOrdering.0.2.7.Cmdlets.json │ │ │ │ ├── AzureRM.Media.0.10.4.Cmdlets.json │ │ │ │ ├── AzureRM.Network.6.11.1.Cmdlets.json │ │ │ │ ├── AzureRM.NotificationHubs.5.0.3.Cmdlets.json │ │ │ │ ├── AzureRM.OperationalInsights.5.0.6.Cmdlets.json │ │ │ │ ├── AzureRM.PolicyInsights.1.1.0.Cmdlets.json │ │ │ │ ├── AzureRM.PowerBIEmbedded.4.1.10.Cmdlets.json │ │ │ │ ├── AzureRM.Profile.5.8.2.Cmdlets.json │ │ │ │ ├── AzureRM.RecoveryServices.4.1.9.Cmdlets.json │ │ │ │ ├── AzureRM.RecoveryServices.Backup.4.5.2.Cmdlets.json │ │ │ │ ├── AzureRM.RecoveryServices.SiteRecovery.0.2.12.Cmdlets.json │ │ │ │ ├── AzureRM.RedisCache.5.1.0.Cmdlets.json │ │ │ │ ├── AzureRM.Relay.0.3.12.Cmdlets.json │ │ │ │ ├── AzureRM.Resources.6.7.3.Cmdlets.json │ │ │ │ ├── AzureRM.Scheduler.0.16.10.Cmdlets.json │ │ │ │ ├── AzureRM.ServiceBus.0.6.13.Cmdlets.json │ │ │ │ ├── AzureRM.ServiceFabric.0.3.15.Cmdlets.json │ │ │ │ ├── AzureRM.SignalR.1.0.0.Cmdlets.json │ │ │ │ ├── AzureRM.Sql.4.12.1.Cmdlets.json │ │ │ │ ├── AzureRM.Storage.5.2.0.Cmdlets.json │ │ │ │ ├── AzureRM.StreamAnalytics.4.0.10.Cmdlets.json │ │ │ │ ├── AzureRM.Tags.4.0.5.Cmdlets.json │ │ │ │ ├── AzureRM.TrafficManager.4.1.3.Cmdlets.json │ │ │ │ ├── AzureRM.UsageAggregates.4.0.5.Cmdlets.json │ │ │ │ └── AzureRM.Websites.5.2.0.Cmdlets.json │ │ └── TestFiles │ │ │ ├── FunctionExample-MultipleCommands.ps1 │ │ │ ├── FunctionExample-OneCommand.ps1 │ │ │ ├── FunctionExample-SubExpressionLineContinuation.ps1 │ │ │ ├── ScriptExample-LineContinuation.ps1 │ │ │ ├── ScriptExample-MultipleCommands.ps1 │ │ │ ├── ScriptExample-OneCommand.ps1 │ │ │ ├── ScriptExample-ParameterSplatting1.ps1 │ │ │ ├── ScriptExample-ParameterSplatting2.ps1 │ │ │ ├── ScriptExample-ParameterSplatting3.ps1 │ │ │ ├── ScriptExample-ParameterSplatting4.ps1 │ │ │ ├── ScriptExample-ParameterSplatting5.ps1 │ │ │ ├── ScriptExample-ParameterSplatting6.ps1 │ │ │ ├── ScriptExample-ParameterSplatting7.ps1 │ │ │ ├── ScriptExample-ParameterSplatting8.ps1 │ │ │ ├── ScriptExample-SubExpressionCommand.ps1 │ │ │ ├── ScriptExample-SubExpressionCommandAfterParams.ps1 │ │ │ └── ScriptExample-SubExpressionLineContinuation.ps1 │ └── Tests │ │ └── Functions │ │ ├── Private │ │ ├── Confirm-StringBuilderSubstring.tests.ps1 │ │ ├── Find-CmdletsInFile.tests.ps1 │ │ ├── Get-ModulePreferences.tests.ps1 │ │ ├── Invoke-ModuleUpgradeStep.tests.ps1 │ │ ├── New-ModifiedFileName.tests.ps1 │ │ ├── Send-MetricsIfDataCollectionEnabled.tests.ps1 │ │ └── Set-ModulePreference.tests.ps1 │ │ └── Public │ │ ├── Disable-AzUpgradeDataCollection.tests.ps1 │ │ ├── Enable-AzUpgradeDataCollection.tests.ps1 │ │ ├── Find-AzUpgradeCommandReference.tests.ps1 │ │ ├── Get-AzUpgradeAliasSpec.tests.ps1 │ │ ├── Get-AzUpgradeCmdletSpec.tests.ps1 │ │ ├── Invoke-AzUpgradeModulePlan.tests.ps1 │ │ ├── Invoke-SamplesTesting.tests.ps1 │ │ └── New-AzUpgradeModulePlan.tests.ps1 ├── ChangeLog.md ├── PSScriptAnalyzerSettings.psd1 ├── README.md ├── Scripts │ ├── New-AzCmdletSpec.ps1 │ └── Publish-Module.ps1 ├── build.proj └── help │ ├── Az.Tools.Migration.md │ ├── Disable-AzUpgradeDataCollection.md │ ├── Enable-AzUpgradeDataCollection.md │ ├── Find-AzUpgradeCommandReference.md │ ├── Get-AzUpgradeAliasSpec.md │ ├── Get-AzUpgradeCmdletSpec.md │ ├── Invoke-AzUpgradeModulePlan.md │ └── New-AzUpgradeModulePlan.md └── vscode-extension ├── .eslintrc.json ├── .gitignore ├── .vscode ├── extensions.json ├── launch.json ├── settings.json └── tasks.json ├── .vscodeignore ├── CHANGELOG.md ├── LICENSE.txt ├── README.md ├── build.proj ├── logo.png ├── package-lock.json ├── package.json ├── resources └── readme │ ├── command-palette.png │ ├── overview.gif │ ├── quick-fix.png │ └── select-version.png ├── src ├── diagnostic.ts ├── extension.ts ├── logging.ts ├── platform.ts ├── powershell.ts ├── quickFix.ts ├── test │ ├── runTest.ts │ └── suite │ │ ├── extension.test.ts │ │ └── index.ts ├── types │ ├── migraion.ts │ └── node-powershell.d.ts └── utils.ts └── tsconfig.json /.azure-pipelines/credscan-suppressions.json: -------------------------------------------------------------------------------- 1 | { 2 | "tool": "Credential Scanner", 3 | "suppressions": [ 4 | 5 | ] 6 | } 7 | -------------------------------------------------------------------------------- /.azure-pipelines/daily-build.yml: -------------------------------------------------------------------------------- 1 | # Please don't use ADO UI defined scheduled triggers because it takes precedence over YAML scheduled triggers. 2 | # https://docs.microsoft.com/en-us/azure/devops/pipelines/process/scheduled-triggers 3 | schedules: 4 | - cron: "0 0 * * *" 5 | displayName: Daily Midnight Build 6 | branches: 7 | include: 8 | - master 9 | 10 | trigger: none 11 | pr: none 12 | 13 | pool: 14 | vmImage: 'windows-2019' 15 | 16 | steps: 17 | - task: DotNetCoreCLI@2 18 | displayName: 'Build' 19 | inputs: 20 | command: custom 21 | custom: msbuild 22 | arguments: 'build.proj /t:Build' -------------------------------------------------------------------------------- /.azure-pipelines/security-scan.yml: -------------------------------------------------------------------------------- 1 | trigger: 2 | branches: 3 | include: 4 | - '*' 5 | 6 | pool: 7 | name: pool-windows-2019 8 | 9 | steps: 10 | - task: ms-codeanalysis.vss-microsoft-security-code-analysis-devops.build-task-credscan.CredScan@2 11 | displayName: 'Run CredScan' 12 | continueOnError: true 13 | inputs: 14 | toolMajorVersion: "V2" 15 | suppressionsFile: .azure-pipelines\credscan-suppressions.json -------------------------------------------------------------------------------- /.azure-pipelines/sign-package.yml: -------------------------------------------------------------------------------- 1 | trigger: none 2 | pr: none 3 | 4 | pool: 5 | name: pool-windows-2019 6 | 7 | steps: 8 | - task: PowerShell@2 9 | displayName: 'Install platyPS' 10 | inputs: 11 | targetType: inline 12 | script: 'Install-Module platyPS -Force -Confirm:$false -Scope CurrentUser' 13 | 14 | - task: PowerShell@2 15 | displayName: 'Install PowerShellGet [v2.1.3 has a Publish-Module bug]' 16 | inputs: 17 | targetType: inline 18 | script: 'Install-Module PowerShellGet -Force -Confirm:$false -Scope CurrentUser -SkipPublisherCheck' 19 | 20 | - task: DotNetCoreCLI@2 21 | displayName: 'Build' 22 | inputs: 23 | command: custom 24 | custom: msbuild 25 | arguments: 'build.proj /t:Build' 26 | 27 | - task: SFP.build-tasks.custom-build-task-1.EsrpCodeSigning@4 28 | displayName: 'Signing' 29 | inputs: 30 | ConnectedServiceName: $(signServiceConnection) 31 | FolderPath: artifacts 32 | Pattern: | 33 | Az.Tools.Migration/**/*.ps1 34 | Az.Tools.Migration/**/*.psd1 35 | Az.Tools.Migration/**/*.psm1 36 | Az.Tools.Migration/**/*.ps1xml 37 | Az.Tools.Migration/**/*.js 38 | UseMinimatch: true 39 | signConfigType: inlineSignParams 40 | inlineOperation: | 41 | [ 42 | { 43 | "KeyCode": "CP-230012", 44 | "OperationCode": "SigntoolSign", 45 | "Parameters": { 46 | "OpusName": "Microsoft", 47 | "OpusInfo": "http://www.microsoft.com", 48 | "FileDigest": "/fd \"SHA256\"", 49 | "PageHash": "/NPH", 50 | "TimeStamp": "/tr \"http://rfc3161.gtm.corp.microsoft.com/TSS/HttpTspServer\" /td sha256" 51 | }, 52 | "ToolName": "sign", 53 | "ToolVersion": "1.0" 54 | }, 55 | { 56 | "KeyCode": "CP-230012", 57 | "OperationCode": "SigntoolVerify", 58 | "Parameters": {}, 59 | "ToolName": "sign", 60 | "ToolVersion": "1.0" 61 | } 62 | ] 63 | 64 | - task: SFP.build-tasks.custom-build-task-1.EsrpCodeSigning@4 65 | displayName: '3rd Party Signing [Authenticode]' 66 | inputs: 67 | ConnectedServiceName: $(signServiceConnection) 68 | FolderPath: artifacts 69 | Pattern: | 70 | Az.Tools.Migration/Resources/Assembly/**/*.dll 71 | UseMinimatch: true 72 | signConfigType: inlineSignParams 73 | inlineOperation: | 74 | [ 75 | { 76 | "KeyCode": "CP-231522", 77 | "OperationCode": "SigntoolSign", 78 | "Parameters": { 79 | "OpusName": "Microsoft", 80 | "OpusInfo": "http://www.microsoft.com", 81 | "FileDigest": "/fd \"SHA256\"", 82 | "PageHash": "/NPH", 83 | "TimeStamp": "/tr \"http://rfc3161.gtm.corp.microsoft.com/TSS/HttpTspServer\" /td sha256" 84 | }, 85 | "ToolName": "sign", 86 | "ToolVersion": "1.0" 87 | }, 88 | { 89 | "KeyCode": "CP-231522", 90 | "OperationCode": "SigntoolVerify", 91 | "Parameters": {}, 92 | "ToolName": "sign", 93 | "ToolVersion": "1.0" 94 | } 95 | ] 96 | 97 | - task: DotNetCoreCLI@2 98 | displayName: Package 99 | inputs: 100 | command: custom 101 | custom: msbuild 102 | arguments: 'build.proj /t:Package' 103 | 104 | - task: PublishPipelineArtifact@0 105 | displayName: 'Save artifacts' 106 | inputs: 107 | artifactName: artifacts 108 | targetPath: artifacts 109 | condition: succeededOrFailed() 110 | -------------------------------------------------------------------------------- /.github/CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing to Azure PowerShell migration tools 2 | 3 | We welcome and appreciate contributions from the community. 4 | You can be involved and contribute to this project in many ways: 5 | 6 | - Opening issues or submitting feature requests 7 | - Writing and improving documentation 8 | - Contributing to code 9 | 10 | Please read the rest of this document for detailed information about the contribution process. 11 | 12 | ## GitHub 13 | 14 | - Make sure you have a [GitHub account](https://github.com/signup/free). 15 | - Learning Git: 16 | - GitHub Help: [Good Resources for Learning Git and GitHub][good-git-resources] 17 | - [Git Basics](https://github.com/PowerShell/PowerShell/blob/master/docs/git/basics.md): install and getting started 18 | - [GitHub Flow Guide](https://guides.github.com/introduction/flow/): step-by-step instructions of GitHub Flow 19 | 20 | ## Opening issues or submitting feature requests 21 | 22 | If you are facing issues with either the PowerShell module or the VSCode extension you can open a [new issue](https://github.com/Azure/azure-powershell-migration/issues/new). 23 | It is a best practice to search through existing issues if the issue has not been already been reported. If this is the case, vote on the issue to help prioritizing the work. 24 | 25 | ## Writing and improving documentation 26 | 27 | Create a [fork of this repo][working-with-forks] to your account, create a new branch on your fork, edit the content, then submit a Pull Request. 28 | More details on how to [create a Pull Request](https://docs.github.com/en/github/collaborating-with-issues-and-pull-requests/creating-a-pull-request) 29 | 30 | ## Code contribution 31 | 32 | ### Code editor 33 | 34 | We recommend that you use [Visual Studio Code](https://docs.microsoft.com/dotnet/core/tutorials/with-visual-studio-code) 35 | 36 | ### Setup your local environment 37 | 38 | - We use [Pester v 4.10.1](https://www.powershellgallery.com/packages/Pester/4.10.1) for the tests. If not already present, you need to install it `Install-Module -Name Pester -RequiredVersion 4.10.1` 39 | - Create a [fork of this repo][working-with-forks] to you own account. 40 | - Clone your fork locally. 41 | 42 | ### Writing code 43 | 44 | > **IMPORTANT:** If you are writing code to submit a feature request, ensure that you have submitted a feature request before and it has been accepted. 45 | 46 | - Launch VSCode and open the `powershell-module` folder instead of each individual file. 47 | Alternatively, from a prompt, navigate to `\azure-powershell-migration\powershell-module` directory and type `code .` 48 | 49 | - New features must have unit tests and supporting documentation in order to be accepted. 50 | 51 | - Execute tests 52 | ``` 53 | # add the path to the module directory to the environment variable 54 | $env:PSModulePath += ";\azure-powershell-migration\powershell-module" 55 | 56 | # Pester 5.x has breaking change. 4.10.1 is required. 57 | Install-Module -Name Pester -RequiredVersion 4.10.1 58 | 59 | cd \azure-powershell-migration\powershell-module\Az.Tools.Migration 60 | 61 | # Execute all test cases 62 | Invoke-Pester -TestName "*tests" 63 | ``` 64 | 65 | - Any resources or code that may also be used for the VSCode extension should be placed in the `common` folder at the root of this repository. 66 | 67 | Further reading: 68 | 69 | - [Writing tests with Pester](https://pester.dev/docs/quick-start#creating-a-pester-test) 70 | - [Introduction to Pester](https://dev.to/omiossec/unit-testing-in-powershell-introduction-to-pester-1de7) 71 | - [Pester source code](https://github.com/pester/Pester/tree/4.10.1) 72 | 73 | ### Building and publishing 74 | 75 | The owners of the repository own the publication process. 76 | After a PR has been accepted and merged we will publish a revision of the module to the PowerShell gallery. 77 | 78 | We will indicate in the PR when the module will be published using milestones. 79 | 80 | ## Contributor License Agreement (CLA) 81 | 82 | This project welcomes contributions and suggestions. Most contributions require you to agree to a 83 | Contributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us 84 | the rights to use your contribution. For details, visit https://cla.opensource.microsoft.com. 85 | 86 | When you submit a pull request, a CLA bot will automatically determine whether you need to provide 87 | a CLA and decorate the PR appropriately (e.g., status check, comment). Simply follow the instructions 88 | provided by the bot. You will only need to do this once across all repos using our CLA. 89 | 90 | This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). 91 | For more information see the [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or 92 | contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with any additional questions or comments. 93 | 94 | [working-with-forks]: (https://docs.github.com/en/github/collaborating-with-issues-and-pull-requests/working-with-forks) -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/doc-bug.yml: -------------------------------------------------------------------------------- 1 | name: ✒️ Documentation issue or question 2 | description: Report documentation related issue 3 | title: '[Doc]: ' 4 | labels: [needs-triage] 5 | 6 | body: 7 | - type: markdown 8 | attributes: 9 | value: > 10 | Az.Tools.Migration documentation includes 3 categories: 11 | 12 | - Conceptual doc about Az.Tools.Migration: https://learn.microsoft.com/powershell/azure/migration-overview?view=aztools 13 | 14 | - Cmdlet reference doc: https://learn.microsoft.com/powershell/module/az.tools.migration/?view=aztools 15 | 16 | - Engineering doc on Github repo: https://github.com/Azure/azure-powershell-migration 17 | - type: markdown 18 | attributes: 19 | value: Select the issue type, and describe the issue in the text box below. Add as much detail as needed to help us resolve the issue. 20 | - type: dropdown 21 | id: issue-type 22 | attributes: 23 | label: Type of issue 24 | options: 25 | - Other (describe below) 26 | - Code doesn't work 27 | - Missing information 28 | - Outdated article 29 | - Typo 30 | - VS Code extension article 31 | validations: 32 | required: true 33 | - type: textarea 34 | id: userfeedback 35 | validations: 36 | required: true 37 | attributes: 38 | label: Feedback 39 | description: >- 40 | If possible, please provide extended details that will add context and help the team update 41 | the documentation. Additional details may not be useful for typos, grammar, formatting, etc. 42 | For technical or factual errors, please include code snippets and output to show how the 43 | documentation is incorrect. 44 | - type: markdown 45 | attributes: 46 | value: Article information 47 | - type: markdown 48 | attributes: 49 | value: "*If the following fields are automatically filled in for you, please don't modify them*" 50 | - type: input 51 | id: pageUrl 52 | attributes: 53 | label: Page URL 54 | - type: input 55 | id: contentSourceUrl 56 | attributes: 57 | label: Content source URL 58 | - type: input 59 | id: author 60 | attributes: 61 | label: Author 62 | description: GitHub Id of the author 63 | - type: input 64 | id: documentVersionIndependentId 65 | attributes: 66 | label: Document Id 67 | - type: input 68 | id: platformId 69 | attributes: 70 | label: Platform Id 71 | - type: markdown 72 | attributes: 73 | value: > 74 | The Azure PowerShell team is listening, please let us know how we are doing: https://aka.ms/azpssurvey?Q_CHL=REPO. 75 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/feature_request.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Feature request 3 | about: Suggest improvements for the project 4 | title: '' 5 | labels: '' 6 | assignees: '' 7 | 8 | --- 9 | 10 | **Component** 11 | [] PowerShell module 12 | [] VSCode extension 13 | [] Other 14 | 15 | **Description of the new feature** 16 | Please provide a clear and concise description of the problem. Ex. I'm always frustrated when [...] 17 | 18 | **Describe the solution you'd like** 19 | A clear and concise description of what you want to happen. 20 | 21 | **Describe alternatives you've considered** 22 | A clear and concise description of any alternative solutions or features you've considered. 23 | 24 | **Additional context** 25 | Add any other context or screenshots about the feature request here. 26 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/issue.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Issue 3 | about: Report an issue with the toolkit 4 | title: '' 5 | labels: '' 6 | assignees: '' 7 | 8 | --- 9 | 10 | **Component** 11 | [] PowerShell module 12 | [] VSCode extension 13 | [] Other 14 | 15 | **Description of the issue** 16 | Please provide a clear and concise description of the problem. Ex. When I do this ... I face this issue ... 17 | 18 | **Describe how to reproduce the issue** 19 | Be as precise as possible about the reprduction steps 20 | 21 | **Environment** 22 | Describe the environment on which this issue is happening 23 | 24 | **Error output** 25 | Share the error log 26 | 27 | **Additional context** 28 | Add any other context or screenshots about the issue here. 29 | -------------------------------------------------------------------------------- /.github/workflows/pr-check.yml: -------------------------------------------------------------------------------- 1 | name: pr-check 2 | 3 | on: 4 | push: 5 | pull_request: 6 | branches: 7 | - main 8 | jobs: 9 | pr-check: 10 | runs-on: ubuntu-latest 11 | steps: 12 | - name: Checkout 13 | uses: actions/checkout@v4 14 | 15 | - name: Install Node.js 14 16 | uses: actions/setup-node@v4 17 | with: 18 | node-version: 14.x 19 | 20 | - name: Lint and build 21 | run: | 22 | pushd vscode-extension 23 | npm install 24 | npm run lint 25 | npm run compile 26 | if [ $? -ne 0 ]; then 27 | exit 1 28 | fi 29 | popd 30 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Microsoft Open Source Code of Conduct 2 | 3 | This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). 4 | 5 | Resources: 6 | 7 | - [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/) 8 | - [Microsoft Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) 9 | - Contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with questions or concerns 10 | - Employees can reach out at [aka.ms/opensource/moderation-support](https://aka.ms/opensource/moderation-support) 11 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) Microsoft Corporation. 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 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # AzureRM to Az Migration Toolkit 2 | 3 | Effortlessly migrate your PowerShell scripts from AzureRM to the [Az PowerShell module](https://docs.microsoft.com/powershell/azure/install-az-ps). 4 | 5 | This repository includes a PowerShell module and a VSCode extension to automate the migration of 6 | your PowerShell scripts and modules from AzureRM to the Az PowerShell module. 7 | 8 | The current version of the migration toolkit is aimed at AzureRM to Az migration. We are 9 | considering adding the additional capability to migrate between Az versions. 10 | 11 | ## Repository Structure 12 | 13 | * common 14 | * Resources shared by the PowerShell module and the VSCode extension. 15 | * Script samples used for testing purposes. 16 | 17 | * docs 18 | * Quick starts and additional documentation. 19 | 20 | * powershell-module 21 | * Code for the Az.Tools.Migration PowerShell module. 22 | 23 | * vscode-extension 24 | * Code for the VSCode extension. 25 | 26 | ## Feedback 27 | 28 | We welcome issues and PRs. Feel free to open issues for suggestions of new features. 29 | 30 | ## Contributing 31 | 32 | This project welcomes contributions and suggestions. Most contributions require you to agree to a 33 | Contributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us 34 | the rights to use your contribution. For details, see the 35 | [Contributor License Agreement](https://cla.opensource.microsoft.com). 36 | 37 | When you submit a pull request, a CLA bot will automatically determine whether you need to provide a 38 | CLA and decorate the PR appropriately (e.g., status check, comment). Simply follow the instructions 39 | provided by the bot. You only need to do this once across all repos using Microsoft's CLA. 40 | 41 | ## Code of Conduct 42 | 43 | This project has adopted the 44 | [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). For more 45 | information see the [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or 46 | contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with any additional questions or 47 | comments. 48 | -------------------------------------------------------------------------------- /SECURITY.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | ## Security 4 | 5 | Microsoft takes the security of our software products and services seriously, which includes all source code repositories managed through our GitHub organizations, which include [Microsoft](https://github.com/Microsoft), [Azure](https://github.com/Azure), [DotNet](https://github.com/dotnet), [AspNet](https://github.com/aspnet), [Xamarin](https://github.com/xamarin), and [our GitHub organizations](https://opensource.microsoft.com/). 6 | 7 | If you believe you have found a security vulnerability in any Microsoft-owned repository that meets [Microsoft's definition of a security vulnerability](https://docs.microsoft.com/en-us/previous-versions/tn-archive/cc751383(v=technet.10)), please report it to us as described below. 8 | 9 | ## Reporting Security Issues 10 | 11 | **Please do not report security vulnerabilities through public GitHub issues.** 12 | 13 | Instead, please report them to the Microsoft Security Response Center (MSRC) at [https://msrc.microsoft.com/create-report](https://msrc.microsoft.com/create-report). 14 | 15 | If you prefer to submit without logging in, send email to [secure@microsoft.com](mailto:secure@microsoft.com). If possible, encrypt your message with our PGP key; please download it from the [Microsoft Security Response Center PGP Key page](https://www.microsoft.com/en-us/msrc/pgp-key-msrc). 16 | 17 | You should receive a response within 24 hours. If for some reason you do not, please follow up via email to ensure we received your original message. Additional information can be found at [microsoft.com/msrc](https://www.microsoft.com/msrc). 18 | 19 | Please include the requested information listed below (as much as you can provide) to help us better understand the nature and scope of the possible issue: 20 | 21 | * Type of issue (e.g. buffer overflow, SQL injection, cross-site scripting, etc.) 22 | * Full paths of source file(s) related to the manifestation of the issue 23 | * The location of the affected source code (tag/branch/commit or direct URL) 24 | * Any special configuration required to reproduce the issue 25 | * Step-by-step instructions to reproduce the issue 26 | * Proof-of-concept or exploit code (if possible) 27 | * Impact of the issue, including how an attacker might exploit the issue 28 | 29 | This information will help us triage your report more quickly. 30 | 31 | If you are reporting for a bug bounty, more complete reports can contribute to a higher bounty award. Please visit our [Microsoft Bug Bounty Program](https://microsoft.com/msrc/bounty) page for more details about our active programs. 32 | 33 | ## Preferred Languages 34 | 35 | We prefer all communications to be in English. 36 | 37 | ## Policy 38 | 39 | Microsoft follows the principle of [Coordinated Vulnerability Disclosure](https://www.microsoft.com/en-us/msrc/cvd). 40 | 41 | -------------------------------------------------------------------------------- /build.proj: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 27 | 28 | 29 | 30 | 31 | -------------------------------------------------------------------------------- /common/code-upgrade-samples/az/compute-create-dockerhost.ps1: -------------------------------------------------------------------------------- 1 | # Original source code: https://github.com/Azure/azure-docs-powershell-samples/blob/a513b6fceae51aaea1daaa8edd4d6fc66590d172/virtual-machine/create-docker-host/create-docker-host.ps1 2 | # Variables for common values 3 | $resourceGroup = "myResourceGroup" 4 | $location = "westeurope" 5 | $vmName = "myVM" 6 | 7 | # Definer user name and blank password 8 | $securePassword = ConvertTo-SecureString ' ' -AsPlainText -Force 9 | $cred = New-Object System.Management.Automation.PSCredential ("azureuser", $securePassword) 10 | 11 | # Create a resource group 12 | New-AzResourceGroup -Name $resourceGroup -Location $location 13 | 14 | # Create a subnet configuration 15 | $subnetConfig = New-AzVirtualNetworkSubnetConfig -Name mySubnet -AddressPrefix 192.168.1.0/24 16 | 17 | # Create a virtual network 18 | $vnet = New-AzVirtualNetwork -ResourceGroupName $resourceGroup -Location $location ` 19 | -Name MYvNET -AddressPrefix 192.168.0.0/16 -Subnet $subnetConfig 20 | 21 | # Create a public IP address and specify a DNS name 22 | $pip = New-AzPublicIpAddress -ResourceGroupName $resourceGroup -Location $location ` 23 | -Name "mypublicdns$(Get-Random)" -AllocationMethod Static -IdleTimeoutInMinutes 4 24 | 25 | # Create an inbound network security group rule for port 22 26 | $nsgRuleSSH = New-AzNetworkSecurityRuleConfig -Name myNetworkSecurityGroupRuleSSH -Protocol Tcp ` 27 | -Direction Inbound -Priority 1000 -SourceAddressPrefix * -SourcePortRange * -DestinationAddressPrefix * ` 28 | -DestinationPortRange 22 -Access Allow 29 | 30 | # Create an inbound network security group rule for port 80 31 | $nsgRuleHTTP = New-AzNetworkSecurityRuleConfig -Name myNetworkSecurityGroupRuleHTTP -Protocol Tcp ` 32 | -Direction Inbound -Priority 2000 -SourceAddressPrefix * -SourcePortRange * -DestinationAddressPrefix * ` 33 | -DestinationPortRange 80 -Access Allow 34 | 35 | # Create a network security group 36 | $nsg = New-AzNetworkSecurityGroup -ResourceGroupName $resourceGroup -Location $location ` 37 | -Name myNetworkSecurityGroup -SecurityRules $nsgRuleSSH,$nsgRuleHTTP 38 | 39 | # Create a virtual network card and associate with public IP address and NSG 40 | $nic = New-AzNetworkInterface -Name myNic -ResourceGroupName $resourceGroup -Location $location ` 41 | -SubnetId $vnet.Subnets[0].Id -PublicIpAddressId $pip.Id -NetworkSecurityGroupId $nsg.Id 42 | 43 | # Create a virtual machine configuration 44 | $vmConfig = New-AzVMConfig -VMName $vmName -VMSize Standard_D1 | ` 45 | Set-AzVMOperatingSystem -Linux -ComputerName $vmName -Credential $cred -DisablePasswordAuthentication | ` 46 | Set-AzVMSourceImage -PublisherName Canonical -Offer UbuntuServer -Skus 14.04.2-LTS -Version latest | ` 47 | Add-AzVMNetworkInterface -Id $nic.Id 48 | 49 | # Configure SSH Keys 50 | $sshPublicKey = Get-Content "$env:USERPROFILE\.ssh\id_rsa.pub" 51 | Add-AzVMSshPublicKey -VM $vmConfig -KeyData $sshPublicKey -Path "/home/azureuser/.ssh/authorized_keys" 52 | 53 | # Create a virtual machine 54 | New-AzVM -ResourceGroupName $resourceGroup -Location $location -VM $vmConfig 55 | 56 | # Install Docker and run container 57 | $PublicSettings = '{"docker": {"port": "2375"},"compose": {"web": {"image": "nginx","ports": ["80:80"]}}}' 58 | 59 | Set-AzVMExtension -Name "Docker" -ResourceGroupName $resourceGroup -VMName $vmName ` 60 | -Publisher "Microsoft.Azure.Extensions" -ExtensionType "DockerExtension" -TypeHandlerVersion 1.0 ` 61 | -SettingString $PublicSettings -Location $location -------------------------------------------------------------------------------- /common/code-upgrade-samples/az/compute-create-windowsvm-quick-splatted-params-1.ps1: -------------------------------------------------------------------------------- 1 | # Original source code: https://github.com/Azure/azure-docs-powershell-samples/blob/a513b6fceae51aaea1daaa8edd4d6fc66590d172/virtual-machine/create-vm-detailed/create-windows-vm-quick.ps1 2 | # Variables for common values 3 | $resourceGroup = "myResourceGroup" 4 | $location = "westeurope" 5 | $vmName = "myVM" 6 | 7 | # Create user object 8 | $cred = Get-Credential -Message "Enter a username and password for the virtual machine." 9 | 10 | # Create a resource group 11 | New-AzResourceGroup -Name $resourceGroup -Location $location 12 | 13 | # Create a virtual machine 14 | # use splatted params 15 | $virtualMachineParams = @{ 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 | } 25 | New-AzVM @virtualMachineParams -ResourceGroupName $resourceGroup -Name $vmName 26 | -------------------------------------------------------------------------------- /common/code-upgrade-samples/az/compute-create-windowsvm-quick-splatted-params-2.ps1: -------------------------------------------------------------------------------- 1 | # Original source code: https://github.com/Azure/azure-docs-powershell-samples/blob/a513b6fceae51aaea1daaa8edd4d6fc66590d172/virtual-machine/create-vm-detailed/create-windows-vm-quick.ps1 2 | # Variables for common values 3 | $resourceGroup = "myResourceGroup" 4 | $location = "westeurope" 5 | $vmName = "myVM" 6 | 7 | # Create user object 8 | $cred = Get-Credential -Message "Enter a username and password for the virtual machine." 9 | 10 | # Create a resource group 11 | New-AzResourceGroup -Name $resourceGroup -Location $location 12 | 13 | # Create a virtual machine 14 | # use splatted params (keys are wrapped with quotes) 15 | $virtualMachineParams = @{ 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 | } 25 | New-AzVM @virtualMachineParams -ResourceGroupName $resourceGroup -Name $vmName 26 | -------------------------------------------------------------------------------- /common/code-upgrade-samples/az/compute-create-windowsvm-quick-splatted-params-3.ps1: -------------------------------------------------------------------------------- 1 | # Original source code: https://github.com/Azure/azure-docs-powershell-samples/blob/a513b6fceae51aaea1daaa8edd4d6fc66590d172/virtual-machine/create-vm-detailed/create-windows-vm-quick.ps1 2 | # Variables for common values 3 | $resourceGroup = "myResourceGroup" 4 | $location = "westeurope" 5 | $vmName = "myVM" 6 | 7 | # Create user object 8 | $cred = Get-Credential -Message "Enter a username and password for the virtual machine." 9 | 10 | # Create a resource group 11 | New-AzResourceGroup -Name $resourceGroup -Location $location 12 | 13 | # Create a virtual machine 14 | # use splatted params 15 | $virtualMachineParams = [ordered]@{ 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 | } 25 | New-AzVM @virtualMachineParams -ResourceGroupName $resourceGroup -Name $vmName 26 | -------------------------------------------------------------------------------- /common/code-upgrade-samples/az/compute-create-windowsvm-quick.ps1: -------------------------------------------------------------------------------- 1 | # Original source code: https://github.com/Azure/azure-docs-powershell-samples/blob/a513b6fceae51aaea1daaa8edd4d6fc66590d172/virtual-machine/create-vm-detailed/create-windows-vm-quick.ps1 2 | # Variables for common values 3 | $resourceGroup = "myResourceGroup" 4 | $location = "westeurope" 5 | $vmName = "myVM" 6 | 7 | # Create user object 8 | $cred = Get-Credential -Message "Enter a username and password for the virtual machine." 9 | 10 | # Create a resource group 11 | New-AzResourceGroup -Name $resourceGroup -Location $location 12 | 13 | # Create a virtual machine 14 | New-AzVM ` 15 | -ResourceGroupName $resourceGroup ` 16 | -Name $vmName ` 17 | -Location $location ` 18 | -Image "Win2016Datacenter" ` 19 | -VirtualNetworkName "myVnet" ` 20 | -SubnetName "mySubnet" ` 21 | -SecurityGroupName "myNetworkSecurityGroup" ` 22 | -PublicIpAddressName "myPublicIp" ` 23 | -Credential $cred ` 24 | -OpenPorts 3389 -------------------------------------------------------------------------------- /common/code-upgrade-samples/az/compute-create-wordpress-mysql.ps1: -------------------------------------------------------------------------------- 1 | # Original source code: https://github.com/Azure/azure-docs-powershell-samples/blob/a513b6fceae51aaea1daaa8edd4d6fc66590d172/virtual-machine/create-wordpress-mysql/create-wordpress-mysql.ps1 2 | # Variables for common values 3 | $resourceGroup = "myResourceGroup" 4 | $location = "westeurope" 5 | $vmName = "myVM" 6 | 7 | # Definer user name and blank password 8 | $securePassword = ConvertTo-SecureString ' ' -AsPlainText -Force 9 | $cred = New-Object System.Management.Automation.PSCredential ("azureuser", $securePassword) 10 | 11 | # Create a resource group 12 | New-AzResourceGroup -Name $resourceGroup -Location $location 13 | 14 | # Create a subnet configuration 15 | $subnetConfig = New-AzVirtualNetworkSubnetConfig -Name mySubnet -AddressPrefix 192.168.1.0/24 16 | 17 | # Create a virtual network 18 | $vnet = New-AzVirtualNetwork -ResourceGroupName $resourceGroup -Location $location ` 19 | -Name MYvNET -AddressPrefix 192.168.0.0/16 -Subnet $subnetConfig 20 | 21 | # Create a public IP address and specify a DNS name 22 | $pip = New-AzPublicIpAddress -ResourceGroupName $resourceGroup -Location $location ` 23 | -Name "mypublicdns$(Get-Random)" -AllocationMethod Static -IdleTimeoutInMinutes 4 24 | 25 | # Create an inbound network security group rule for port 22 26 | $nsgRuleSSH = New-AzNetworkSecurityRuleConfig -Name myNetworkSecurityGroupRuleSSH -Protocol Tcp ` 27 | -Direction Inbound -Priority 1000 -SourceAddressPrefix * -SourcePortRange * -DestinationAddressPrefix * ` 28 | -DestinationPortRange 22 -Access Allow 29 | 30 | # Create an inbound network security group rule for port 80 31 | $nsgRuleHTTP = New-AzNetworkSecurityRuleConfig -Name myNetworkSecurityGroupRuleHTTP -Protocol Tcp ` 32 | -Direction Inbound -Priority 2000 -SourceAddressPrefix * -SourcePortRange * -DestinationAddressPrefix * ` 33 | -DestinationPortRange 80 -Access Allow 34 | 35 | # Create a network security group 36 | $nsg = New-AzNetworkSecurityGroup -ResourceGroupName $resourceGroup -Location $location ` 37 | -Name myNetworkSecurityGroup -SecurityRules $nsgRuleSSH,$nsgRuleHTTP 38 | 39 | # Create a virtual network card and associate with public IP address and NSG 40 | $nic = New-AzNetworkInterface -Name myNic -ResourceGroupName $resourceGroup -Location $location ` 41 | -SubnetId $vnet.Subnets[0].Id -PublicIpAddressId $pip.Id -NetworkSecurityGroupId $nsg.Id 42 | 43 | # Create a virtual machine configuration 44 | $vmConfig = New-AzVMConfig -VMName $vmname -VMSize Standard_D1 | ` 45 | Set-AzVMOperatingSystem -Linux -ComputerName $vmName -Credential $cred -DisablePasswordAuthentication | ` 46 | Set-AzVMSourceImage -PublisherName Canonical -Offer UbuntuServer -Skus 14.04.2-LTS -Version latest | ` 47 | Add-AzVMNetworkInterface -Id $nic.Id 48 | 49 | # Configure SSH Keys 50 | $sshPublicKey = Get-Content "$env:USERPROFILE\.ssh\id_rsa.pub" 51 | Add-AzVMSshPublicKey -VM $vmconfig -KeyData $sshPublicKey -Path "/home/azureuser/.ssh/authorized_keys" 52 | 53 | # Create a virtual machine 54 | New-AzVM -ResourceGroupName $resourceGroup -Location $location -VM $vmConfig 55 | 56 | # Start a CustomScript extension to use a simple bash script to update, download and install WordPress and MySQL 57 | $PublicSettings = '{"fileUris":["https://raw.githubusercontent.com/Azure/azure-quickstart-templates/master/wordpress-single-vm-ubuntu/install_wordpress.sh"],"commandToExecute":"sh install_wordpress.sh"}' 58 | 59 | Set-AzVMExtension -Name "WordPress" -ResourceGroupName $resourceGroup -VMName $vmName ` 60 | -Publisher "Microsoft.Azure.Extensions" -ExtensionType "CustomScript" -TypeHandlerVersion 2.0 ` 61 | -SettingString $PublicSettings ` 62 | -Location $location -------------------------------------------------------------------------------- /common/code-upgrade-samples/az/dynamic-parameters-test1.ps1: -------------------------------------------------------------------------------- 1 | # dynamic params example 1: a mix of known parameters and user / dynamic parameters should be supported, but provide a warning instead of an error. 2 | 3 | New-AzResourceGroupDeployment -ResourceGroupName "ContosoEngineering" ` 4 | -TemplateFile "D:\Azure\Templates\EngineeringSite.json" ` 5 | -TemplateParameterFile "D:\Azure\Templates\EngSiteParms.json" ` 6 | -DynamicUserParam1 "test1" ` 7 | -DynamicUserParam2 "test2" 8 | -------------------------------------------------------------------------------- /common/code-upgrade-samples/az/network-create-vm-two-nics.ps1: -------------------------------------------------------------------------------- 1 | # Original source code: https://github.com/Azure/azure-docs-powershell-samples/blob/26f8f493b3c83d23365c2d4a1c4be90ecece1dd4/virtual-network/vm-with-two-nics/vm-with-two-nics.ps1 2 | # Variables for common values 3 | $rgName='MyResourceGroup' 4 | $location='eastus' 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 $rgName -Location $location 11 | 12 | # Create a virtual network with a front-end subnet and back-end subnet. 13 | $fesubnet = New-AzVirtualNetworkSubnetConfig -Name 'MySubnet-FrontEnd' -AddressPrefix '10.0.1.0/24' 14 | $besubnet = New-AzVirtualNetworkSubnetConfig -Name 'MySubnet-BackEnd' -AddressPrefix '10.0.2.0/24' 15 | $vnet = New-AzVirtualNetwork -ResourceGroupName $rgName -Name 'MyVnet' -AddressPrefix '10.0.0.0/16' ` 16 | -Location $location -Subnet $fesubnet, $besubnet 17 | 18 | # Create NSG rules to allow HTTP & HTTPS traffic inbound. 19 | $rule1 = New-AzNetworkSecurityRuleConfig -Name 'Allow-HTTP-ALL' -Description 'Allow HTTP' ` 20 | -Access Allow -Protocol Tcp -Direction Inbound -Priority 100 ` 21 | -SourceAddressPrefix Internet -SourcePortRange * ` 22 | -DestinationAddressPrefix * -DestinationPortRange 80 23 | 24 | $rule2 = New-AzNetworkSecurityRuleConfig -Name 'Allow-HTTPS-All' -Description 'Allow HTTPS' ` 25 | -Access Allow -Protocol Tcp -Direction Inbound -Priority 200 ` 26 | -SourceAddressPrefix Internet -SourcePortRange * ` 27 | -DestinationAddressPrefix * -DestinationPortRange 80 28 | 29 | # Create an NSG rule to allow RDP traffic from the Internet to the front-end subnet. 30 | $rule2 = New-AzNetworkSecurityRuleConfig -Name 'Allow-RDP-All' -Description "Allow RDP" ` 31 | -Access Allow -Protocol Tcp -Direction Inbound -Priority 300 ` 32 | -SourceAddressPrefix Internet -SourcePortRange * ` 33 | -DestinationAddressPrefix * -DestinationPortRange 3389 34 | 35 | # Create a network security group (NSG) for the front-end subnet. 36 | $nsg = New-AzNetworkSecurityGroup -ResourceGroupName $RgName -Location $location ` 37 | -Name "MyNsg-FrontEnd" -SecurityRules $rule1,$rule2,$rule3 38 | 39 | # Associate the front-end NSG to the front-end subnet. 40 | Set-AzVirtualNetworkSubnetConfig -VirtualNetwork $vnet -Name 'MySubnet-FrontEnd' ` 41 | -AddressPrefix 10.0.1.0/24 -NetworkSecurityGroup $nsgfe 42 | 43 | # Create an NSG rule to block all outbound traffic from the back-end subnet to the Internet (inbound blocked by default). 44 | $rule1 = New-AzNetworkSecurityRuleConfig -Name 'Deny-Internet-All' -Description 'Deny Internet All' ` 45 | -Access Deny -Protocol Tcp -Direction Outbound -Priority 300 ` 46 | -SourceAddressPrefix * -SourcePortRange * ` 47 | -DestinationAddressPrefix * -DestinationPortRange * 48 | 49 | # Create a network security group for back-end subnet. 50 | $nsgbe = New-AzNetworkSecurityGroup -ResourceGroupName $RgName -Location $location ` 51 | -Name 'MyNsg-BackEnd' -SecurityRules $rule1 52 | 53 | # Associate the back-end NSG to the back-end subnet. 54 | Set-AzVirtualNetworkSubnetConfig -VirtualNetwork $vnet -Name 'MySubnet-BackEnd' ` 55 | -AddressPrefix 10.0.2.0/24 -NetworkSecurityGroup $nsgbe 56 | 57 | # Create a public IP addresses for the VM front-end network interface. 58 | $publicipvm = New-AzPublicIpAddress -ResourceGroupName $rgName -Name 'MyPublicIp-FrontEnd' ` 59 | -location $location -AllocationMethod Dynamic 60 | 61 | 62 | # Create a network interface for the VM attached to the front-end subnet. 63 | $nicVMfe = New-AzNetworkInterface -ResourceGroupName $rgName -Location $location ` 64 | -Name 'MyNic-FrontEnd' -PublicIpAddress $publicipvm -Subnet $vnet.Subnets[0] 65 | 66 | # Create a network interface for the VM attached to the back-end subnet. 67 | $nicVMbe = New-AzNetworkInterface -ResourceGroupName $rgName -Location $location ` 68 | -Name 'MyNic-BackEnd' -Subnet $vnet.Subnets[1] 69 | 70 | # Create the VM with both the FrontEnd and BackEnd NICs. 71 | $vmConfig = New-AzVMConfig -VMName 'MyVm' -VMSize 'Standard_DS2' | ` 72 | Set-AzVMOperatingSystem -Windows -ComputerName 'MyVm' -Credential $cred | ` 73 | Set-AzVMSourceImage -PublisherName 'MicrosoftWindowsServer' -Offer 'WindowsServer' ` 74 | -Skus '2016-Datacenter' -Version 'latest' 75 | 76 | $vmconfig = Add-AzVMNetworkInterface -VM $vmConfig -id $nicVMfe.Id -Primary 77 | $vmconfig = Add-AzVMNetworkInterface -VM $vmConfig -id $nicVMbe.Id 78 | 79 | # Create a virtual machine 80 | $vm = New-AzVM -ResourceGroupName $rgName -Location $location -VM $vmConfig -------------------------------------------------------------------------------- /common/code-upgrade-samples/az/network-peer-two-virtual-networks.ps1: -------------------------------------------------------------------------------- 1 | # Original source code: https://github.com/Azure/azure-docs-powershell-samples/tree/26f8f493b3c83d23365c2d4a1c4be90ecece1dd4/virtual-network/peer-two-virtual-networks 2 | # Variables for common values 3 | $rgName='MyResourceGroup' 4 | $location='eastus' 5 | 6 | # Create a resource group. 7 | New-AzResourceGroup -Name $rgName -Location $location 8 | 9 | # Create virtual network 1. 10 | $vnet1 = New-AzVirtualNetwork -ResourceGroupName $rgName -Name 'Vnet1' -AddressPrefix '10.0.0.0/16' -Location $location 11 | 12 | # Create virtual network 2. 13 | $vnet2 = New-AzVirtualNetwork -ResourceGroupName $rgName -Name 'Vnet2' -AddressPrefix '10.1.0.0/16' -Location $location 14 | 15 | # Peer VNet1 to VNet2. 16 | Add-AzVirtualNetworkPeering -Name 'LinkVnet1ToVnet2' -VirtualNetwork $vnet1 -RemoteVirtualNetworkId $vnet2.Id 17 | 18 | # Peer VNet2 to VNet1. 19 | Add-AzVirtualNetworkPeering -Name 'LinkVnet2ToVnet1' -VirtualNetwork $vnet2 -RemoteVirtualNetworkId $vnet1.Id -------------------------------------------------------------------------------- /common/code-upgrade-samples/az/network-route-traffic-through-nva.ps1: -------------------------------------------------------------------------------- 1 | # Original source code: https://github.com/Azure/azure-docs-powershell-samples/blob/26f8f493b3c83d23365c2d4a1c4be90ecece1dd4/virtual-network/route-traffic-through-nva/route-traffic-through-nva.ps1 2 | # Variables for common values 3 | $rgName='MyResourceGroup' 4 | $location='eastus' 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 $rgName -Location $location 11 | 12 | # Create a virtual network, a front-end subnet, a back-end subnet, and a DMZ subnet. 13 | $fesubnet = New-AzVirtualNetworkSubnetConfig -Name 'MySubnet-FrontEnd' -AddressPrefix 10.0.1.0/24 14 | $besubnet = New-AzVirtualNetworkSubnetConfig -Name 'MySubnet-BackEnd' -AddressPrefix 10.0.2.0/24 15 | $dmzsubnet = New-AzVirtualNetworkSubnetConfig -Name 'MySubnet-Dmz' -AddressPrefix 10.0.0.0/24 16 | 17 | $vnet = New-AzVirtualNetwork -ResourceGroupName $rgName -Name 'MyVnet' -AddressPrefix 10.0.0.0/16 ` 18 | -Location $location -Subnet $fesubnet, $besubnet, $dmzsubnet 19 | 20 | # Create NSG rules to allow HTTP & HTTPS traffic inbound. 21 | $rule1 = New-AzNetworkSecurityRuleConfig -Name 'Allow-HTTP-ALL' -Description 'Allow HTTP' ` 22 | -Access Allow -Protocol Tcp -Direction Inbound -Priority 100 ` 23 | -SourceAddressPrefix Internet -SourcePortRange * ` 24 | -DestinationAddressPrefix * -DestinationPortRange 80 25 | 26 | $rule2 = New-AzNetworkSecurityRuleConfig -Name 'Allow-HTTPS-All' -Description 'Allow HTTPS' ` 27 | -Access Allow -Protocol Tcp -Direction Inbound -Priority 200 ` 28 | -SourceAddressPrefix Internet -SourcePortRange * ` 29 | -DestinationAddressPrefix * -DestinationPortRange 443 30 | 31 | # Create a network security group (NSG) for the front-end subnet. 32 | $nsg = New-AzNetworkSecurityGroup -ResourceGroupName $RgName -Location $location ` 33 | -Name 'MyNsg-FrontEnd' -SecurityRules $rule1,$rule2 34 | 35 | # Associate the front-end NSG to the front-end subnet. 36 | Set-AzVirtualNetworkSubnetConfig -VirtualNetwork $vnet -Name 'MySubnet-FrontEnd' ` 37 | -AddressPrefix '10.0.1.0/24' -NetworkSecurityGroup $nsg 38 | 39 | # Create a public IP address for the firewall VM. 40 | $publicip = New-AzPublicIpAddress -ResourceGroupName $rgName -Name 'MyPublicIP-Firewall' ` 41 | -location $location -AllocationMethod Dynamic 42 | 43 | # Create a NIC for the firewall VM and enable IP forwarding. 44 | $nicVMFW = New-AzNetworkInterface -ResourceGroupName $rgName -Location $location -Name 'MyNic-Firewall' ` 45 | -PublicIpAddress $publicip -Subnet $vnet.Subnets[2] -EnableIPForwarding 46 | 47 | #Create a firewall VM to accept all traffic between the front and back-end subnets. 48 | $vmConfig = New-AzVMConfig -VMName 'MyVm-Firewall' -VMSize Standard_DS2 | ` 49 | Set-AzVMOperatingSystem -Windows -ComputerName 'MyVm-Firewall' -Credential $cred | ` 50 | Set-AzVMSourceImage -PublisherName MicrosoftWindowsServer -Offer WindowsServer ` 51 | -Skus 2016-Datacenter -Version latest | Add-AzVMNetworkInterface -Id $nicVMFW.Id 52 | 53 | $vm = New-AzVM -ResourceGroupName $rgName -Location $location -VM $vmConfig 54 | 55 | # Create a route for traffic from the front-end to the back-end subnet through the firewall VM. 56 | $route = New-AzRouteConfig -Name 'RouteToBackEnd' -AddressPrefix 10.0.2.0/24 ` 57 | -NextHopType VirtualAppliance -NextHopIpAddress $nicVMFW.IpConfigurations[0].PrivateIpAddress 58 | 59 | # Create a route for traffic from the front-end subnet to the Internet through the firewall VM. 60 | $route2 = New-AzRouteConfig -Name 'RouteToInternet' -AddressPrefix 0.0.0.0/0 ` 61 | -NextHopType VirtualAppliance -NextHopIpAddress $nicVMFW.IpConfigurations[0].PrivateIpAddress 62 | 63 | # Create route table for the FrontEnd subnet. 64 | $routeTableFEtoBE = New-AzRouteTable -Name 'MyRouteTable-FrontEnd' -ResourceGroupName $rgName ` 65 | -location $location -Route $route, $route2 66 | 67 | # Associate the route table to the FrontEnd subnet. 68 | Set-AzVirtualNetworkSubnetConfig -VirtualNetwork $vnet -Name 'MySubnet-FrontEnd' -AddressPrefix 10.0.1.0/24 ` 69 | -NetworkSecurityGroup $nsg -RouteTable $routeTableFEtoBE 70 | 71 | # Create a route for traffic from the back-end subnet to the front-end subnet through the firewall VM. 72 | $route = New-AzRouteConfig -Name 'RouteToFrontEnd' -AddressPrefix '10.0.1.0/24' -NextHopType VirtualAppliance ` 73 | -NextHopIpAddress $nicVMFW.IpConfigurations[0].PrivateIPAddress 74 | 75 | # Create a route for traffic from the back-end subnet to the Internet through the firewall VM. 76 | $route2 = New-AzRouteConfig -Name 'RouteToInternet' -AddressPrefix '0.0.0.0/0' -NextHopType VirtualAppliance ` 77 | -NextHopIpAddress $nicVMFW.IpConfigurations[0].PrivateIPAddress 78 | 79 | # Create route table for the BackEnd subnet. 80 | $routeTableBE = New-AzRouteTable -Name 'MyRouteTable-BackEnd' -ResourceGroupName $rgName ` 81 | -location $location -Route $route, $route2 82 | 83 | # Associate the route table to the BackEnd subnet. 84 | Set-AzVirtualNetworkSubnetConfig -VirtualNetwork $vnet -Name 'MySubnet-BackEnd' ` 85 | -AddressPrefix '10.0.2.0/24' -RouteTable $routeTableBE -------------------------------------------------------------------------------- /common/code-upgrade-samples/az/sqldb-create-and-configure-database.ps1: -------------------------------------------------------------------------------- 1 | # Original source codet: https://github.com/Azure/azure-docs-powershell-samples/blob/5513f8ea73e2b9630311d7ea27372cddc4e65cae/sql-database/create-and-configure-database/create-and-configure-database.ps1 2 | 3 | # Set the resource group name and location for your server 4 | $resourceGroupName = "myResourceGroup-$(Get-Random)" 5 | $location = "southcentralus" 6 | # Set an admin login and password for your server 7 | $adminlogin = "ServerAdmin" 8 | $password = "ChangeYourAdminPassword1" 9 | # Set server name - the logical server name has to be unique in the system 10 | $serverName = "server-$(Get-Random)" 11 | # The sample database name 12 | $databaseName = "mySampleDatabase" 13 | # The ip address range that you want to allow to access your server 14 | $startIp = "0.0.0.0" 15 | $endIp = "0.0.0.0" 16 | 17 | # Create a resource group 18 | $resourceGroup = New-AzResourceGroup -Name $resourceGroupName -Location $location 19 | 20 | # Create a server with a system wide unique server name 21 | $server = New-AzSqlServer -ResourceGroupName $resourceGroupName ` 22 | -ServerName $serverName ` 23 | -Location $location ` 24 | -SqlAdministratorCredentials $(New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $adminlogin, $(ConvertTo-SecureString -String $password -AsPlainText -Force)) 25 | 26 | # Create a server firewall rule that allows access from the specified IP range 27 | $serverFirewallRule = New-AzSqlServerFirewallRule -ResourceGroupName $resourceGroupName ` 28 | -ServerName $serverName ` 29 | -FirewallRuleName "AllowedIPs" -StartIpAddress $startIp -EndIpAddress $endIp 30 | 31 | # Create a blank database with an S0 performance level 32 | $database = New-AzSqlDatabase -ResourceGroupName $resourceGroupName ` 33 | -ServerName $serverName ` 34 | -DatabaseName $databaseName ` 35 | -RequestedServiceObjectiveName "S0" ` 36 | -SampleName "AdventureWorksLT" -------------------------------------------------------------------------------- /common/code-upgrade-samples/az/sqldb-import-from-bacpac.ps1: -------------------------------------------------------------------------------- 1 | # Original source code: https://github.com/Azure/azure-docs-powershell-samples/blob/5513f8ea73e2b9630311d7ea27372cddc4e65cae/sql-database/import-from-bacpac/import-from-bacpac.ps1 2 | 3 | # Set the resource group name and location for your server 4 | $resourceGroupName = "myResourceGroup-$(Get-Random)" 5 | $location = "westeurope" 6 | # Set an admin login and password for your server 7 | $adminlogin = "ServerAdmin" 8 | $password = "ChangeYourAdminPassword1" 9 | # Set server name - the logical server name has to be unique in the system 10 | $serverName = "server-$(Get-Random)" 11 | # The sample database name 12 | $databaseName = "myImportedDatabase" 13 | # The storage account name and storage container name 14 | $storageAccountName = "sqlimport$(Get-Random)" 15 | $storageContainerName = "importcontainer$(Get-Random)" 16 | # BACPAC file name 17 | $bacpacFilename = "sample.bacpac" 18 | # The ip address range that you want to allow to access your server 19 | $startip = "0.0.0.0" 20 | $endip = "0.0.0.0" 21 | 22 | # Create a resource group 23 | $resourcegroup = New-AzResourceGroup -Name $resourceGroupName -Location $location 24 | 25 | # Create a storage account 26 | $storageAccount = New-AzStorageAccount -ResourceGroupName $resourceGroupName ` 27 | -Name $storageAccountName ` 28 | -Location $location ` 29 | -SkuName "Standard_LRS" 30 | 31 | # Create a storage container 32 | $storageContainer = New-AzStorageContainer -Name $storageContainerName ` 33 | -Context $(New-AzStorageContext -StorageAccountName $storageAccountName ` 34 | -StorageAccountKey $(Get-AzStorageAccountKey -ResourceGroupName $resourceGroupName -Name $storageAccountName).Value[0]) 35 | 36 | # Download sample database from Github 37 | [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 #required by Github 38 | Invoke-WebRequest -Uri "https://github.com/Microsoft/sql-server-samples/releases/download/wide-world-importers-v1.0/WideWorldImporters-Standard.bacpac" -OutFile $bacpacfilename 39 | 40 | # Upload sample database into storage container 41 | Set-AzStorageBlobContent -Container $storagecontainername ` 42 | -File $bacpacFilename ` 43 | -Context $(New-AzStorageContext -StorageAccountName $storageAccountName ` 44 | -StorageAccountKey $(Get-AzStorageAccountKey -ResourceGroupName $resourceGroupName -Name $storageAccountName).Value[0]) 45 | 46 | # Create a new server with a system wide unique server name 47 | $server = New-AzSqlServer -ResourceGroupName $resourceGroupName ` 48 | -ServerName $serverName ` 49 | -Location $location ` 50 | -SqlAdministratorCredentials $(New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $adminlogin, $(ConvertTo-SecureString -String $password -AsPlainText -Force)) 51 | 52 | # Create a server firewall rule that allows access from the specified IP range 53 | $serverFirewallRule = New-AzSqlServerFirewallRule -ResourceGroupName $resourceGroupName ` 54 | -ServerName $serverName ` 55 | -FirewallRuleName "AllowedIPs" -StartIpAddress $startIp -EndIpAddress $endIp 56 | 57 | # Import bacpac to database with an S3 performance level 58 | $importRequest = New-AzSqlDatabaseImport -ResourceGroupName $resourceGroupName ` 59 | -ServerName $serverName ` 60 | -DatabaseName $databaseName ` 61 | -DatabaseMaxSizeBytes "262144000" ` 62 | -StorageKeyType "StorageAccessKey" ` 63 | -StorageKey $(Get-AzStorageAccountKey -ResourceGroupName $resourceGroupName -Name $storageAccountName).Value[0] ` 64 | -StorageUri "https://$storageaccountname.blob.core.windows.net/$storageContainerName/$bacpacFilename" ` 65 | -Edition "Standard" ` 66 | -ServiceObjectiveName "S3" ` 67 | -AdministratorLogin "$adminlogin" ` 68 | -AdministratorLoginPassword $(ConvertTo-SecureString -String $password -AsPlainText -Force) 69 | 70 | # Check import status and wait for the import to complete 71 | $importStatus = Get-AzSqlDatabaseImportExportStatus -OperationStatusLink $importRequest.OperationStatusLink 72 | [Console]::Write("Importing") 73 | while ($importStatus.Status -eq "InProgress") 74 | { 75 | $importStatus = Get-AzSqlDatabaseImportExportStatus -OperationStatusLink $importRequest.OperationStatusLink 76 | [Console]::Write(".") 77 | Start-Sleep -s 10 78 | } 79 | [Console]::WriteLine("") 80 | $importStatus 81 | 82 | # Scale down to S0 after import is complete 83 | Set-AzSqlDatabase -ResourceGroupName $resourceGroupName ` 84 | -ServerName $serverName ` 85 | -DatabaseName $databaseName ` 86 | -Edition "Standard" ` 87 | -RequestedServiceObjectiveName "S0" -------------------------------------------------------------------------------- /common/code-upgrade-samples/az/sqldb-move-database-between-pools-and-standalone.ps1: -------------------------------------------------------------------------------- 1 | # Original source code: https://github.com/Azure/azure-docs-powershell-samples/blob/5513f8ea73e2b9630311d7ea27372cddc4e65cae/sql-database/move-database-between-pools-and-standalone/move-database-between-pools-and-standalone.ps1 2 | # Set the resource group name and location for your server 3 | $resourceGroupName = "myResourceGroup-$(Get-Random)" 4 | $location = "southcentralus" 5 | # Set elastic pool names 6 | $firstPoolName = "MyFirstPool" 7 | $secondPoolName = "MySecondPool" 8 | # Set an admin login and password for your server 9 | $adminlogin = "ServerAdmin" 10 | $password = "" 11 | # The logical server name has to be unique in the system 12 | $serverName = "server-$(Get-Random)" 13 | # The sample database names 14 | $firstDatabaseName = "myFirstSampleDatabase" 15 | $secondDatabaseName = "mySecondSampleDatabase" 16 | # The ip address range that you want to allow to access your server 17 | $startIp = "0.0.0.0" 18 | $endIp = "0.0.0.0" 19 | 20 | # Create a new resource group 21 | $resourceGroup = New-AzResourceGroup -Name $resourceGroupName -Location $location 22 | 23 | # Create a new server with a system wide unique server name 24 | $server = New-AzSqlServer -ResourceGroupName $resourceGroupName ` 25 | -ServerName $serverName ` 26 | -Location $location ` 27 | -SqlAdministratorCredentials $(New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $adminlogin, $(ConvertTo-SecureString -String $password -AsPlainText -Force)) 28 | 29 | # Create a server firewall rule that allows access from the specified IP range 30 | $serverFirewallRule = New-AzSqlServerFirewallRule -ResourceGroupName $resourceGroupName ` 31 | -ServerName $serverName ` 32 | -FirewallRuleName "AllowedIPs" -StartIpAddress $startIp -EndIpAddress $endIp 33 | 34 | # Create two elastic database pools 35 | $firstPool = New-AzSqlElasticPool -ResourceGroupName $resourceGroupName ` 36 | -ServerName $servername ` 37 | -ElasticPoolName $firstPoolName ` 38 | -Edition "Standard" ` 39 | -Dtu 50 ` 40 | -DatabaseDtuMin 10 ` 41 | -DatabaseDtuMax 20 42 | $secondPool = New-AzSqlElasticPool -ResourceGroupName $resourceGroupName ` 43 | -ServerName $serverName ` 44 | -ElasticPoolName $secondPoolName ` 45 | -Edition "Standard" ` 46 | -Dtu 50 ` 47 | -DatabaseDtuMin 10 ` 48 | -DatabaseDtuMax 50 49 | 50 | # Create two blank databases in the first pool 51 | $firstDatabase = New-AzSqlDatabase -ResourceGroupName $resourceGroupName ` 52 | -ServerName $serverName ` 53 | -DatabaseName $firstDatabaseName ` 54 | -ElasticPoolName $firstPoolName 55 | $secondDatabase = New-AzSqlDatabase -ResourceGroupName $resourceGroupName ` 56 | -ServerName $serverName ` 57 | -DatabaseName $secondDatabaseName ` 58 | -ElasticPoolName $secondPoolName 59 | 60 | # Move the database to the second pool 61 | $firstDatabase = Set-AzSqlDatabase -ResourceGroupName $resourceGroupName ` 62 | -ServerName $serverName ` 63 | -DatabaseName $firstDatabaseName ` 64 | -ElasticPoolName $secondPoolName 65 | 66 | # Move the database into a standalone performance level 67 | $firstDatabase = Set-AzSqlDatabase -ResourceGroupName $resourceGroupName ` 68 | -ServerName $serverName ` 69 | -DatabaseName $firstDatabaseName ` 70 | -RequestedServiceObjectiveName "S0" -------------------------------------------------------------------------------- /common/code-upgrade-samples/az/sqldb-restore-database.ps1: -------------------------------------------------------------------------------- 1 | # Original source code: https://github.com/Azure/azure-docs-powershell-samples/blob/5513f8ea73e2b9630311d7ea27372cddc4e65cae/sql-database/restore-database/restore-database.ps1 2 | 3 | # Set the resource group name and location for your server 4 | $resourceGroupName = "myResourceGroup-$(Get-Random)" 5 | $location = "westeurope" 6 | # Set an admin login and password for your server 7 | $adminlogin = "ServerAdmin" 8 | $password = "ChangeYourAdminPassword1" 9 | # Set server name - the logical server name has to be unique in the system 10 | $serverName = "server-$(Get-Random)" 11 | # The sample database name 12 | $databaseName = "mySampleDatabase" 13 | # The restored database names 14 | $pointInTimeRestoreDatabaseName = "MySampleDatabase_10MinutesAgo" 15 | # The ip address range that you want to allow to access your server 16 | $startIp = "0.0.0.0" 17 | $endIp = "0.0.0.0" 18 | 19 | 20 | # Create a resource group 21 | $resourceGroup = New-AzResourceGroup -Name $resourceGroupName -Location $location 22 | 23 | # Create a server with a system wide unique server name 24 | $server = New-AzSqlServer -ResourceGroupName $resourceGroupName ` 25 | -ServerName $serverName ` 26 | -Location $location ` 27 | -SqlAdministratorCredentials $(New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $adminlogin, $(ConvertTo-SecureString -String $password -AsPlainText -Force)) 28 | 29 | # Create a server firewall rule that allows access from the specified IP range 30 | $firewallRule = New-AzSqlServerFirewallRule -ResourceGroupName $resourceGroupName ` 31 | -ServerName $serverName ` 32 | -FirewallRuleName "AllowedIPs" -StartIpAddress $startIp -EndIpAddress $endIp 33 | 34 | # Create a blank database with an S0 performance level 35 | $database = New-AzSqlDatabase -ResourceGroupName $resourceGroupName ` 36 | -ServerName $serverName ` 37 | -DatabaseName $databaseName ` 38 | -RequestedServiceObjectiveName "S0" 39 | 40 | Start-Sleep -second 600 41 | 42 | # Restore database to its state 7 minutes ago 43 | # Note: Point-in-time restore requires database to be at least 5 minutes old 44 | Restore-AzSqlDatabase ` 45 | -FromPointInTimeBackup ` 46 | -PointInTime (Get-Date).AddMinutes(-2) ` 47 | -ResourceGroupName $resourceGroupName ` 48 | -ServerName $serverName ` 49 | -TargetDatabaseName $pointInTimeRestoreDatabaseName ` 50 | -ResourceId $database.ResourceID ` 51 | -Edition "Standard" ` 52 | -ServiceObjectiveName "S0" -------------------------------------------------------------------------------- /common/code-upgrade-samples/az/webapp-back-restore.ps1: -------------------------------------------------------------------------------- 1 | # Original source code: https://github.com/Azure/azure-docs-powershell-samples/blob/77c8876ed0d79ba5538e3e583fe03aa514ae7661/app-service/backup-restore/backup-restore.ps1 2 | $resourceGroupName = "myResourceGroup" 3 | $webappname = "" 4 | 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-AzWebAppBackupList -ResourceGroupName $resourceGroupName -Name $webappname | where {$_.BackupId -eq ''}) 13 | 14 | # Restore the app by overwriting it with the backup data 15 | $backup | Restore-AzWebAppBackup -Overwrite -------------------------------------------------------------------------------- /common/code-upgrade-samples/az/webapp-create-from-github.ps1: -------------------------------------------------------------------------------- 1 | # Original source code: https://github.com/Azure/azure-docs-powershell-samples/blob/77c8876ed0d79ba5538e3e583fe03aa514ae7661/app-service/deploy-github/deploy-github.ps1 2 | # Replace the following URL with a public GitHub repo URL 3 | $gitrepo="https://github.com/Azure-Samples/app-service-web-dotnet-get-started.git" 4 | $webappname="mywebapp$(Get-Random)" 5 | $location="West Europe" 6 | 7 | # Create a resource group. 8 | New-AzResourceGroup -Name myResourceGroup -Location $location 9 | 10 | # Create an App Service plan in Free tier. 11 | New-AzAppServicePlan -Name $webappname -Location $location -ResourceGroupName myResourceGroup -Tier Free 12 | 13 | # Create a web app. 14 | New-AzWebApp -Name $webappname -Location $location -AppServicePlan $webappname -ResourceGroupName myResourceGroup 15 | 16 | # Configure GitHub deployment from your GitHub repo and deploy once. 17 | $PropertiesObject = @{ 18 | repoUrl = "$gitrepo"; 19 | branch = "master"; 20 | isManualIntegration = "true"; 21 | } 22 | Set-AzResource -Properties $PropertiesObject -ResourceGroupName myResourceGroup -ResourceType Microsoft.Web/sites/sourcecontrols -ResourceName $webappname/web -ApiVersion 2015-08-01 -Force -------------------------------------------------------------------------------- /common/code-upgrade-samples/az/webapp-monitor-with-logs.ps1: -------------------------------------------------------------------------------- 1 | # Original source code: https://github.com/Azure/azure-docs-powershell-samples/blob/77c8876ed0d79ba5538e3e583fe03aa514ae7661/app-service/monitor-with-logs/monitor-with-logs.ps1 2 | 3 | # Generates a Random Value 4 | $Random=(New-Guid).ToString().Substring(0,8) 5 | 6 | # Variables 7 | $ResourceGroupName="myResourceGroup$Random" 8 | $AppName="AppServiceMonitor$Random" 9 | $Location="WestUS" 10 | 11 | # Create a Resource Group 12 | New-AzResourceGroup -Name $ResourceGroupName -Location $Location 13 | 14 | # Create an App Service Plan 15 | New-AzAppservicePlan -Name AppServiceMonitorPlan -ResourceGroupName $ResourceGroupName -Location $Location -Tier Basic 16 | 17 | # Create a Web App in the App Service Plan 18 | New-AzWebApp -Name $AppName -ResourceGroupName $ResourceGroupName -Location $Location -AppServicePlan AppServiceMonitorPlan 19 | 20 | # Enable Logs 21 | Set-AzWebApp -RequestTracingEnabled $True -HttpLoggingEnabled $True -DetailedErrorLoggingEnabled $True -ResourceGroupName $ResourceGroupName -Name $AppName 22 | 23 | # Make a Request 24 | Invoke-WebRequest -Method "Get" -Uri https://$AppName.azurewebsites.net/404 -ErrorAction SilentlyContinue -------------------------------------------------------------------------------- /common/code-upgrade-samples/azurerm/compute-create-dockerhost.ps1: -------------------------------------------------------------------------------- 1 | # Original source code: https://github.com/Azure/azure-docs-powershell-samples/blob/a513b6fceae51aaea1daaa8edd4d6fc66590d172/virtual-machine/create-docker-host/create-docker-host.ps1 2 | # Variables for common values 3 | $resourceGroup = "myResourceGroup" 4 | $location = "westeurope" 5 | $vmName = "myVM" 6 | 7 | # Definer user name and blank password 8 | $securePassword = ConvertTo-SecureString ' ' -AsPlainText -Force 9 | $cred = New-Object System.Management.Automation.PSCredential ("azureuser", $securePassword) 10 | 11 | # Create a resource group 12 | New-AzureRmResourceGroup -Name $resourceGroup -Location $location 13 | 14 | # Create a subnet configuration 15 | $subnetConfig = New-AzureRmVirtualNetworkSubnetConfig -Name mySubnet -AddressPrefix 192.168.1.0/24 16 | 17 | # Create a virtual network 18 | $vnet = New-AzureRmVirtualNetwork -ResourceGroupName $resourceGroup -Location $location ` 19 | -Name MYvNET -AddressPrefix 192.168.0.0/16 -Subnet $subnetConfig 20 | 21 | # Create a public IP address and specify a DNS name 22 | $pip = New-AzureRmPublicIpAddress -ResourceGroupName $resourceGroup -Location $location ` 23 | -Name "mypublicdns$(Get-Random)" -AllocationMethod Static -IdleTimeoutInMinutes 4 24 | 25 | # Create an inbound network security group rule for port 22 26 | $nsgRuleSSH = New-AzureRmNetworkSecurityRuleConfig -Name myNetworkSecurityGroupRuleSSH -Protocol Tcp ` 27 | -Direction Inbound -Priority 1000 -SourceAddressPrefix * -SourcePortRange * -DestinationAddressPrefix * ` 28 | -DestinationPortRange 22 -Access Allow 29 | 30 | # Create an inbound network security group rule for port 80 31 | $nsgRuleHTTP = New-AzureRmNetworkSecurityRuleConfig -Name myNetworkSecurityGroupRuleHTTP -Protocol Tcp ` 32 | -Direction Inbound -Priority 2000 -SourceAddressPrefix * -SourcePortRange * -DestinationAddressPrefix * ` 33 | -DestinationPortRange 80 -Access Allow 34 | 35 | # Create a network security group 36 | $nsg = New-AzureRmNetworkSecurityGroup -ResourceGroupName $resourceGroup -Location $location ` 37 | -Name myNetworkSecurityGroup -SecurityRules $nsgRuleSSH,$nsgRuleHTTP 38 | 39 | # Create a virtual network card and associate with public IP address and NSG 40 | $nic = New-AzureRmNetworkInterface -Name myNic -ResourceGroupName $resourceGroup -Location $location ` 41 | -SubnetId $vnet.Subnets[0].Id -PublicIpAddressId $pip.Id -NetworkSecurityGroupId $nsg.Id 42 | 43 | # Create a virtual machine configuration 44 | $vmConfig = New-AzureRmVMConfig -VMName $vmName -VMSize Standard_D1 | ` 45 | Set-AzureRmVMOperatingSystem -Linux -ComputerName $vmName -Credential $cred -DisablePasswordAuthentication | ` 46 | Set-AzureRmVMSourceImage -PublisherName Canonical -Offer UbuntuServer -Skus 14.04.2-LTS -Version latest | ` 47 | Add-AzureRmVMNetworkInterface -Id $nic.Id 48 | 49 | # Configure SSH Keys 50 | $sshPublicKey = Get-Content "$env:USERPROFILE\.ssh\id_rsa.pub" 51 | Add-AzureRmVMSshPublicKey -VM $vmConfig -KeyData $sshPublicKey -Path "/home/azureuser/.ssh/authorized_keys" 52 | 53 | # Create a virtual machine 54 | New-AzureRmVM -ResourceGroupName $resourceGroup -Location $location -VM $vmConfig 55 | 56 | # Install Docker and run container 57 | $PublicSettings = '{"docker": {"port": "2375"},"compose": {"web": {"image": "nginx","ports": ["80:80"]}}}' 58 | 59 | Set-AzureRmVMExtension -ExtensionName "Docker" -ResourceGroupName $resourceGroup -VMName $vmName ` 60 | -Publisher "Microsoft.Azure.Extensions" -ExtensionType "DockerExtension" -TypeHandlerVersion 1.0 ` 61 | -SettingString $PublicSettings -Location $location -------------------------------------------------------------------------------- /common/code-upgrade-samples/azurerm/compute-create-windowsvm-quick-splatted-params-1.ps1: -------------------------------------------------------------------------------- 1 | # Original source code: https://github.com/Azure/azure-docs-powershell-samples/blob/a513b6fceae51aaea1daaa8edd4d6fc66590d172/virtual-machine/create-vm-detailed/create-windows-vm-quick.ps1 2 | # Variables for common values 3 | $resourceGroup = "myResourceGroup" 4 | $location = "westeurope" 5 | $vmName = "myVM" 6 | 7 | # Create user object 8 | $cred = Get-Credential -Message "Enter a username and password for the virtual machine." 9 | 10 | # Create a resource group 11 | New-AzureRmResourceGroup -Name $resourceGroup -Location $location 12 | 13 | # Create a virtual machine 14 | # use splatted params 15 | $virtualMachineParams = @{ 16 | Location = $location 17 | ImageName = "Win2016Datacenter" 18 | VirtualNetworkName = "myVnet" 19 | SubnetName = "mySubnet" 20 | SecurityGroupName = "myNetworkSecurityGroup" 21 | PublicIpAddressName = "myPublicIp" 22 | Credential = $cred 23 | OpenPorts = 3389 24 | } 25 | New-AzureRmVM @virtualMachineParams -ResourceGroupName $resourceGroup -Name $vmName -------------------------------------------------------------------------------- /common/code-upgrade-samples/azurerm/compute-create-windowsvm-quick-splatted-params-2.ps1: -------------------------------------------------------------------------------- 1 | # Original source code: https://github.com/Azure/azure-docs-powershell-samples/blob/a513b6fceae51aaea1daaa8edd4d6fc66590d172/virtual-machine/create-vm-detailed/create-windows-vm-quick.ps1 2 | # Variables for common values 3 | $resourceGroup = "myResourceGroup" 4 | $location = "westeurope" 5 | $vmName = "myVM" 6 | 7 | # Create user object 8 | $cred = Get-Credential -Message "Enter a username and password for the virtual machine." 9 | 10 | # Create a resource group 11 | New-AzureRmResourceGroup -Name $resourceGroup -Location $location 12 | 13 | # Create a virtual machine 14 | # use splatted params (keys are wrapped with quotes) 15 | $virtualMachineParams = @{ 16 | "Location" = $location 17 | "ImageName" = "Win2016Datacenter" 18 | "VirtualNetworkName" = "myVnet" 19 | "SubnetName" = "mySubnet" 20 | "SecurityGroupName" = "myNetworkSecurityGroup" 21 | "PublicIpAddressName" = "myPublicIp" 22 | "Credential" = $cred 23 | "OpenPorts" = 3389 24 | } 25 | New-AzureRmVM @virtualMachineParams -ResourceGroupName $resourceGroup -Name $vmName -------------------------------------------------------------------------------- /common/code-upgrade-samples/azurerm/compute-create-windowsvm-quick-splatted-params-3.ps1: -------------------------------------------------------------------------------- 1 | # Original source code: https://github.com/Azure/azure-docs-powershell-samples/blob/a513b6fceae51aaea1daaa8edd4d6fc66590d172/virtual-machine/create-vm-detailed/create-windows-vm-quick.ps1 2 | # Variables for common values 3 | $resourceGroup = "myResourceGroup" 4 | $location = "westeurope" 5 | $vmName = "myVM" 6 | 7 | # Create user object 8 | $cred = Get-Credential -Message "Enter a username and password for the virtual machine." 9 | 10 | # Create a resource group 11 | New-AzureRmResourceGroup -Name $resourceGroup -Location $location 12 | 13 | # Create a virtual machine 14 | # use splatted params 15 | $virtualMachineParams = [ordered]@{ 16 | Location = $location 17 | ImageName = "Win2016Datacenter" 18 | VirtualNetworkName = "myVnet" 19 | SubnetName = "mySubnet" 20 | SecurityGroupName = "myNetworkSecurityGroup" 21 | PublicIpAddressName = "myPublicIp" 22 | Credential = $cred 23 | OpenPorts = 3389 24 | } 25 | New-AzureRmVM @virtualMachineParams -ResourceGroupName $resourceGroup -Name $vmName -------------------------------------------------------------------------------- /common/code-upgrade-samples/azurerm/compute-create-windowsvm-quick.ps1: -------------------------------------------------------------------------------- 1 | # Original source code: https://github.com/Azure/azure-docs-powershell-samples/blob/a513b6fceae51aaea1daaa8edd4d6fc66590d172/virtual-machine/create-vm-detailed/create-windows-vm-quick.ps1 2 | # Variables for common values 3 | $resourceGroup = "myResourceGroup" 4 | $location = "westeurope" 5 | $vmName = "myVM" 6 | 7 | # Create user object 8 | $cred = Get-Credential -Message "Enter a username and password for the virtual machine." 9 | 10 | # Create a resource group 11 | New-AzureRmResourceGroup -Name $resourceGroup -Location $location 12 | 13 | # Create a virtual machine 14 | New-AzureRmVM ` 15 | -ResourceGroupName $resourceGroup ` 16 | -Name $vmName ` 17 | -Location $location ` 18 | -ImageName "Win2016Datacenter" ` 19 | -VirtualNetworkName "myVnet" ` 20 | -SubnetName "mySubnet" ` 21 | -SecurityGroupName "myNetworkSecurityGroup" ` 22 | -PublicIpAddressName "myPublicIp" ` 23 | -Credential $cred ` 24 | -OpenPorts 3389 -------------------------------------------------------------------------------- /common/code-upgrade-samples/azurerm/compute-create-wordpress-mysql.ps1: -------------------------------------------------------------------------------- 1 | # Original source code: https://github.com/Azure/azure-docs-powershell-samples/blob/a513b6fceae51aaea1daaa8edd4d6fc66590d172/virtual-machine/create-wordpress-mysql/create-wordpress-mysql.ps1 2 | # Variables for common values 3 | $resourceGroup = "myResourceGroup" 4 | $location = "westeurope" 5 | $vmName = "myVM" 6 | 7 | # Definer user name and blank password 8 | $securePassword = ConvertTo-SecureString ' ' -AsPlainText -Force 9 | $cred = New-Object System.Management.Automation.PSCredential ("azureuser", $securePassword) 10 | 11 | # Create a resource group 12 | New-AzureRmResourceGroup -Name $resourceGroup -Location $location 13 | 14 | # Create a subnet configuration 15 | $subnetConfig = New-AzureRmVirtualNetworkSubnetConfig -Name mySubnet -AddressPrefix 192.168.1.0/24 16 | 17 | # Create a virtual network 18 | $vnet = New-AzureRmVirtualNetwork -ResourceGroupName $resourceGroup -Location $location ` 19 | -Name MYvNET -AddressPrefix 192.168.0.0/16 -Subnet $subnetConfig 20 | 21 | # Create a public IP address and specify a DNS name 22 | $pip = New-AzureRmPublicIpAddress -ResourceGroupName $resourceGroup -Location $location ` 23 | -Name "mypublicdns$(Get-Random)" -AllocationMethod Static -IdleTimeoutInMinutes 4 24 | 25 | # Create an inbound network security group rule for port 22 26 | $nsgRuleSSH = New-AzureRmNetworkSecurityRuleConfig -Name myNetworkSecurityGroupRuleSSH -Protocol Tcp ` 27 | -Direction Inbound -Priority 1000 -SourceAddressPrefix * -SourcePortRange * -DestinationAddressPrefix * ` 28 | -DestinationPortRange 22 -Access Allow 29 | 30 | # Create an inbound network security group rule for port 80 31 | $nsgRuleHTTP = New-AzureRmNetworkSecurityRuleConfig -Name myNetworkSecurityGroupRuleHTTP -Protocol Tcp ` 32 | -Direction Inbound -Priority 2000 -SourceAddressPrefix * -SourcePortRange * -DestinationAddressPrefix * ` 33 | -DestinationPortRange 80 -Access Allow 34 | 35 | # Create a network security group 36 | $nsg = New-AzureRmNetworkSecurityGroup -ResourceGroupName $resourceGroup -Location $location ` 37 | -Name myNetworkSecurityGroup -SecurityRules $nsgRuleSSH,$nsgRuleHTTP 38 | 39 | # Create a virtual network card and associate with public IP address and NSG 40 | $nic = New-AzureRmNetworkInterface -Name myNic -ResourceGroupName $resourceGroup -Location $location ` 41 | -SubnetId $vnet.Subnets[0].Id -PublicIpAddressId $pip.Id -NetworkSecurityGroupId $nsg.Id 42 | 43 | # Create a virtual machine configuration 44 | $vmConfig = New-AzureRmVMConfig -VMName $vmname -VMSize Standard_D1 | ` 45 | Set-AzureRmVMOperatingSystem -Linux -ComputerName $vmName -Credential $cred -DisablePasswordAuthentication | ` 46 | Set-AzureRmVMSourceImage -PublisherName Canonical -Offer UbuntuServer -Skus 14.04.2-LTS -Version latest | ` 47 | Add-AzureRmVMNetworkInterface -Id $nic.Id 48 | 49 | # Configure SSH Keys 50 | $sshPublicKey = Get-Content "$env:USERPROFILE\.ssh\id_rsa.pub" 51 | Add-AzureRmVMSshPublicKey -VM $vmconfig -KeyData $sshPublicKey -Path "/home/azureuser/.ssh/authorized_keys" 52 | 53 | # Create a virtual machine 54 | New-AzureRmVM -ResourceGroupName $resourceGroup -Location $location -VM $vmConfig 55 | 56 | # Start a CustomScript extension to use a simple bash script to update, download and install WordPress and MySQL 57 | $PublicSettings = '{"fileUris":["https://raw.githubusercontent.com/Azure/azure-quickstart-templates/master/wordpress-single-vm-ubuntu/install_wordpress.sh"],"commandToExecute":"sh install_wordpress.sh"}' 58 | 59 | Set-AzureRmVMExtension -ExtensionName "WordPress" -ResourceGroupName $resourceGroup -VMName $vmName ` 60 | -Publisher "Microsoft.Azure.Extensions" -ExtensionType "CustomScript" -TypeHandlerVersion 2.0 ` 61 | -SettingString $PublicSettings ` 62 | -Location $location -------------------------------------------------------------------------------- /common/code-upgrade-samples/azurerm/dynamic-parameters-test1.ps1: -------------------------------------------------------------------------------- 1 | # dynamic params example 1: a mix of known parameters and user / dynamic parameters should be supported, but provide a warning instead of an error. 2 | 3 | New-AzureRmResourceGroupDeployment -ResourceGroupName "ContosoEngineering" ` 4 | -TemplateFile "D:\Azure\Templates\EngineeringSite.json" ` 5 | -TemplateParameterFile "D:\Azure\Templates\EngSiteParms.json" ` 6 | -DynamicUserParam1 "test1" ` 7 | -DynamicUserParam2 "test2" -------------------------------------------------------------------------------- /common/code-upgrade-samples/azurerm/network-create-vm-two-nics.ps1: -------------------------------------------------------------------------------- 1 | # Original source code: https://github.com/Azure/azure-docs-powershell-samples/blob/26f8f493b3c83d23365c2d4a1c4be90ecece1dd4/virtual-network/vm-with-two-nics/vm-with-two-nics.ps1 2 | # Variables for common values 3 | $rgName='MyResourceGroup' 4 | $location='eastus' 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-AzureRmResourceGroup -Name $rgName -Location $location 11 | 12 | # Create a virtual network with a front-end subnet and back-end subnet. 13 | $fesubnet = New-AzureRmVirtualNetworkSubnetConfig -Name 'MySubnet-FrontEnd' -AddressPrefix '10.0.1.0/24' 14 | $besubnet = New-AzureRmVirtualNetworkSubnetConfig -Name 'MySubnet-BackEnd' -AddressPrefix '10.0.2.0/24' 15 | $vnet = New-AzureRmVirtualNetwork -ResourceGroupName $rgName -Name 'MyVnet' -AddressPrefix '10.0.0.0/16' ` 16 | -Location $location -Subnet $fesubnet, $besubnet 17 | 18 | # Create NSG rules to allow HTTP & HTTPS traffic inbound. 19 | $rule1 = New-AzureRmNetworkSecurityRuleConfig -Name 'Allow-HTTP-ALL' -Description 'Allow HTTP' ` 20 | -Access Allow -Protocol Tcp -Direction Inbound -Priority 100 ` 21 | -SourceAddressPrefix Internet -SourcePortRange * ` 22 | -DestinationAddressPrefix * -DestinationPortRange 80 23 | 24 | $rule2 = New-AzureRmNetworkSecurityRuleConfig -Name 'Allow-HTTPS-All' -Description 'Allow HTTPS' ` 25 | -Access Allow -Protocol Tcp -Direction Inbound -Priority 200 ` 26 | -SourceAddressPrefix Internet -SourcePortRange * ` 27 | -DestinationAddressPrefix * -DestinationPortRange 80 28 | 29 | # Create an NSG rule to allow RDP traffic from the Internet to the front-end subnet. 30 | $rule2 = New-AzureRmNetworkSecurityRuleConfig -Name 'Allow-RDP-All' -Description "Allow RDP" ` 31 | -Access Allow -Protocol Tcp -Direction Inbound -Priority 300 ` 32 | -SourceAddressPrefix Internet -SourcePortRange * ` 33 | -DestinationAddressPrefix * -DestinationPortRange 3389 34 | 35 | # Create a network security group (NSG) for the front-end subnet. 36 | $nsg = New-AzureRmNetworkSecurityGroup -ResourceGroupName $RgName -Location $location ` 37 | -Name "MyNsg-FrontEnd" -SecurityRules $rule1,$rule2,$rule3 38 | 39 | # Associate the front-end NSG to the front-end subnet. 40 | Set-AzureRmVirtualNetworkSubnetConfig -VirtualNetwork $vnet -Name 'MySubnet-FrontEnd' ` 41 | -AddressPrefix 10.0.1.0/24 -NetworkSecurityGroup $nsgfe 42 | 43 | # Create an NSG rule to block all outbound traffic from the back-end subnet to the Internet (inbound blocked by default). 44 | $rule1 = New-AzureRmNetworkSecurityRuleConfig -Name 'Deny-Internet-All' -Description 'Deny Internet All' ` 45 | -Access Deny -Protocol Tcp -Direction Outbound -Priority 300 ` 46 | -SourceAddressPrefix * -SourcePortRange * ` 47 | -DestinationAddressPrefix * -DestinationPortRange * 48 | 49 | # Create a network security group for back-end subnet. 50 | $nsgbe = New-AzureRmNetworkSecurityGroup -ResourceGroupName $RgName -Location $location ` 51 | -Name 'MyNsg-BackEnd' -SecurityRules $rule1 52 | 53 | # Associate the back-end NSG to the back-end subnet. 54 | Set-AzureRmVirtualNetworkSubnetConfig -VirtualNetwork $vnet -Name 'MySubnet-BackEnd' ` 55 | -AddressPrefix 10.0.2.0/24 -NetworkSecurityGroup $nsgbe 56 | 57 | # Create a public IP addresses for the VM front-end network interface. 58 | $publicipvm = New-AzureRmPublicIpAddress -ResourceGroupName $rgName -Name 'MyPublicIp-FrontEnd' ` 59 | -location $location -AllocationMethod Dynamic 60 | 61 | 62 | # Create a network interface for the VM attached to the front-end subnet. 63 | $nicVMfe = New-AzureRmNetworkInterface -ResourceGroupName $rgName -Location $location ` 64 | -Name 'MyNic-FrontEnd' -PublicIpAddress $publicipvm -Subnet $vnet.Subnets[0] 65 | 66 | # Create a network interface for the VM attached to the back-end subnet. 67 | $nicVMbe = New-AzureRmNetworkInterface -ResourceGroupName $rgName -Location $location ` 68 | -Name 'MyNic-BackEnd' -Subnet $vnet.Subnets[1] 69 | 70 | # Create the VM with both the FrontEnd and BackEnd NICs. 71 | $vmConfig = New-AzureRmVMConfig -VMName 'MyVm' -VMSize 'Standard_DS2' | ` 72 | Set-AzureRmVMOperatingSystem -Windows -ComputerName 'MyVm' -Credential $cred | ` 73 | Set-AzureRmVMSourceImage -PublisherName 'MicrosoftWindowsServer' -Offer 'WindowsServer' ` 74 | -Skus '2016-Datacenter' -Version 'latest' 75 | 76 | $vmconfig = Add-AzureRmVMNetworkInterface -VM $vmConfig -id $nicVMfe.Id -Primary 77 | $vmconfig = Add-AzureRmVMNetworkInterface -VM $vmConfig -id $nicVMbe.Id 78 | 79 | # Create a virtual machine 80 | $vm = New-AzureRmVM -ResourceGroupName $rgName -Location $location -VM $vmConfig -------------------------------------------------------------------------------- /common/code-upgrade-samples/azurerm/network-peer-two-virtual-networks.ps1: -------------------------------------------------------------------------------- 1 | # Original source code: https://github.com/Azure/azure-docs-powershell-samples/tree/26f8f493b3c83d23365c2d4a1c4be90ecece1dd4/virtual-network/peer-two-virtual-networks 2 | # Variables for common values 3 | $rgName='MyResourceGroup' 4 | $location='eastus' 5 | 6 | # Create a resource group. 7 | New-AzureRmResourceGroup -Name $rgName -Location $location 8 | 9 | # Create virtual network 1. 10 | $vnet1 = New-AzureRmVirtualNetwork -ResourceGroupName $rgName -Name 'Vnet1' -AddressPrefix '10.0.0.0/16' -Location $location 11 | 12 | # Create virtual network 2. 13 | $vnet2 = New-AzureRmVirtualNetwork -ResourceGroupName $rgName -Name 'Vnet2' -AddressPrefix '10.1.0.0/16' -Location $location 14 | 15 | # Peer VNet1 to VNet2. 16 | Add-AzureRmVirtualNetworkPeering -Name 'LinkVnet1ToVnet2' -VirtualNetwork $vnet1 -RemoteVirtualNetworkId $vnet2.Id 17 | 18 | # Peer VNet2 to VNet1. 19 | Add-AzureRmVirtualNetworkPeering -Name 'LinkVnet2ToVnet1' -VirtualNetwork $vnet2 -RemoteVirtualNetworkId $vnet1.Id -------------------------------------------------------------------------------- /common/code-upgrade-samples/azurerm/sqldb-create-and-configure-database.ps1: -------------------------------------------------------------------------------- 1 | # Original source codet: https://github.com/Azure/azure-docs-powershell-samples/blob/5513f8ea73e2b9630311d7ea27372cddc4e65cae/sql-database/create-and-configure-database/create-and-configure-database.ps1 2 | 3 | # Set the resource group name and location for your server 4 | $resourcegroupname = "myResourceGroup-$(Get-Random)" 5 | $location = "southcentralus" 6 | # Set an admin login and password for your server 7 | $adminlogin = "ServerAdmin" 8 | $password = "ChangeYourAdminPassword1" 9 | # Set server name - the logical server name has to be unique in the system 10 | $servername = "server-$(Get-Random)" 11 | # The sample database name 12 | $databasename = "mySampleDatabase" 13 | # The ip address range that you want to allow to access your server 14 | $startip = "0.0.0.0" 15 | $endip = "0.0.0.0" 16 | 17 | # Create a resource group 18 | $resourcegroup = New-AzureRmResourceGroup -Name $resourcegroupname -Location $location 19 | 20 | # Create a server with a system wide unique server name 21 | $server = New-AzureRmSqlServer -ResourceGroupName $resourcegroupname ` 22 | -ServerName $servername ` 23 | -Location $location ` 24 | -SqlAdministratorCredentials $(New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $adminlogin, $(ConvertTo-SecureString -String $password -AsPlainText -Force)) 25 | 26 | # Create a server firewall rule that allows access from the specified IP range 27 | $serverfirewallrule = New-AzureRmSqlServerFirewallRule -ResourceGroupName $resourcegroupname ` 28 | -ServerName $servername ` 29 | -FirewallRuleName "AllowedIPs" -StartIpAddress $startip -EndIpAddress $endip 30 | 31 | # Create a blank database with an S0 performance level 32 | $database = New-AzureRmSqlDatabase -ResourceGroupName $resourcegroupname ` 33 | -ServerName $servername ` 34 | -DatabaseName $databasename ` 35 | -RequestedServiceObjectiveName "S0" ` 36 | -SampleName "AdventureWorksLT" -------------------------------------------------------------------------------- /common/code-upgrade-samples/azurerm/sqldb-import-from-bacpac.ps1: -------------------------------------------------------------------------------- 1 | # Original source code: https://github.com/Azure/azure-docs-powershell-samples/blob/5513f8ea73e2b9630311d7ea27372cddc4e65cae/sql-database/import-from-bacpac/import-from-bacpac.ps1 2 | 3 | # Set the resource group name and location for your server 4 | $resourcegroupname = "myResourceGroup-$(Get-Random)" 5 | $location = "westeurope" 6 | # Set an admin login and password for your server 7 | $adminlogin = "ServerAdmin" 8 | $password = "ChangeYourAdminPassword1" 9 | # Set server name - the logical server name has to be unique in the system 10 | $servername = "server-$(Get-Random)" 11 | # The sample database name 12 | $databasename = "myImportedDatabase" 13 | # The storage account name and storage container name 14 | $storageaccountname = "sqlimport$(Get-Random)" 15 | $storagecontainername = "importcontainer$(Get-Random)" 16 | # BACPAC file name 17 | $bacpacfilename = "sample.bacpac" 18 | # The ip address range that you want to allow to access your server 19 | $startip = "0.0.0.0" 20 | $endip = "0.0.0.0" 21 | 22 | # Create a resource group 23 | $resourcegroup = New-AzureRmResourceGroup -Name $resourcegroupname -Location $location 24 | 25 | # Create a storage account 26 | $storageaccount = New-AzureRmStorageAccount -ResourceGroupName $resourcegroupname ` 27 | -AccountName $storageaccountname ` 28 | -Location $location ` 29 | -Type "Standard_LRS" 30 | 31 | # Create a storage container 32 | $storagecontainer = New-AzureStorageContainer -Name $storagecontainername ` 33 | -Context $(New-AzureStorageContext -StorageAccountName $storageaccountname ` 34 | -StorageAccountKey $(Get-AzureRmStorageAccountKey -ResourceGroupName $resourcegroupname -StorageAccountName $storageaccountname).Value[0]) 35 | 36 | # Download sample database from Github 37 | [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 #required by Github 38 | Invoke-WebRequest -Uri "https://github.com/Microsoft/sql-server-samples/releases/download/wide-world-importers-v1.0/WideWorldImporters-Standard.bacpac" -OutFile $bacpacfilename 39 | 40 | # Upload sample database into storage container 41 | Set-AzureStorageBlobContent -Container $storagecontainername ` 42 | -File $bacpacfilename ` 43 | -Context $(New-AzureStorageContext -StorageAccountName $storageaccountname ` 44 | -StorageAccountKey $(Get-AzureRmStorageAccountKey -ResourceGroupName $resourcegroupname -StorageAccountName $storageaccountname).Value[0]) 45 | 46 | # Create a new server with a system wide unique server name 47 | $server = New-AzureRmSqlServer -ResourceGroupName $resourcegroupname ` 48 | -ServerName $servername ` 49 | -Location $location ` 50 | -SqlAdministratorCredentials $(New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $adminlogin, $(ConvertTo-SecureString -String $password -AsPlainText -Force)) 51 | 52 | # Create a server firewall rule that allows access from the specified IP range 53 | $serverfirewallrule = New-AzureRmSqlServerFirewallRule -ResourceGroupName $resourcegroupname ` 54 | -ServerName $servername ` 55 | -FirewallRuleName "AllowedIPs" -StartIpAddress $startip -EndIpAddress $endip 56 | 57 | # Import bacpac to database with an S3 performance level 58 | $importRequest = New-AzureRmSqlDatabaseImport -ResourceGroupName $resourcegroupname ` 59 | -ServerName $servername ` 60 | -DatabaseName $databasename ` 61 | -DatabaseMaxSizeBytes "262144000" ` 62 | -StorageKeyType "StorageAccessKey" ` 63 | -StorageKey $(Get-AzureRmStorageAccountKey -ResourceGroupName $resourcegroupname -StorageAccountName $storageaccountname).Value[0] ` 64 | -StorageUri "https://$storageaccountname.blob.core.windows.net/$storagecontainername/$bacpacfilename" ` 65 | -Edition "Standard" ` 66 | -ServiceObjectiveName "S3" ` 67 | -AdministratorLogin "$adminlogin" ` 68 | -AdministratorLoginPassword $(ConvertTo-SecureString -String $password -AsPlainText -Force) 69 | 70 | # Check import status and wait for the import to complete 71 | $importStatus = Get-AzureRmSqlDatabaseImportExportStatus -OperationStatusLink $importRequest.OperationStatusLink 72 | [Console]::Write("Importing") 73 | while ($importStatus.Status -eq "InProgress") 74 | { 75 | $importStatus = Get-AzureRmSqlDatabaseImportExportStatus -OperationStatusLink $importRequest.OperationStatusLink 76 | [Console]::Write(".") 77 | Start-Sleep -s 10 78 | } 79 | [Console]::WriteLine("") 80 | $importStatus 81 | 82 | # Scale down to S0 after import is complete 83 | Set-AzureRmSqlDatabase -ResourceGroupName $resourcegroupname ` 84 | -ServerName $servername ` 85 | -DatabaseName $databasename ` 86 | -Edition "Standard" ` 87 | -RequestedServiceObjectiveName "S0" -------------------------------------------------------------------------------- /common/code-upgrade-samples/azurerm/sqldb-move-database-between-pools-and-standalone.ps1: -------------------------------------------------------------------------------- 1 | # Original source code: https://github.com/Azure/azure-docs-powershell-samples/blob/5513f8ea73e2b9630311d7ea27372cddc4e65cae/sql-database/move-database-between-pools-and-standalone/move-database-between-pools-and-standalone.ps1 2 | # Set the resource group name and location for your server 3 | $resourcegroupname = "myResourceGroup-$(Get-Random)" 4 | $location = "southcentralus" 5 | # Set elastic pool names 6 | $firstpoolname = "MyFirstPool" 7 | $secondpoolname = "MySecondPool" 8 | # Set an admin login and password for your server 9 | $adminlogin = "ServerAdmin" 10 | $password = "" 11 | # The logical server name has to be unique in the system 12 | $servername = "server-$(Get-Random)" 13 | # The sample database names 14 | $firstdatabasename = "myFirstSampleDatabase" 15 | $seconddatabasename = "mySecondSampleDatabase" 16 | # The ip address range that you want to allow to access your server 17 | $startip = "0.0.0.0" 18 | $endip = "0.0.0.0" 19 | 20 | # Create a new resource group 21 | $resourcegroup = New-AzureRmResourceGroup -Name $resourcegroupname -Location $location 22 | 23 | # Create a new server with a system wide unique server name 24 | $server = New-AzureRmSqlServer -ResourceGroupName $resourcegroupname ` 25 | -ServerName $servername ` 26 | -Location $location ` 27 | -SqlAdministratorCredentials $(New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $adminlogin, $(ConvertTo-SecureString -String $password -AsPlainText -Force)) 28 | 29 | # Create a server firewall rule that allows access from the specified IP range 30 | $serverfirewallrule = New-AzureRmSqlServerFirewallRule -ResourceGroupName $resourcegroupname ` 31 | -ServerName $servername ` 32 | -FirewallRuleName "AllowedIPs" -StartIpAddress $startip -EndIpAddress $endip 33 | 34 | # Create two elastic database pools 35 | $firstpool = New-AzureRmSqlElasticPool -ResourceGroupName $resourcegroupname ` 36 | -ServerName $servername ` 37 | -ElasticPoolName $firstpoolname ` 38 | -Edition "Standard" ` 39 | -Dtu 50 ` 40 | -DatabaseDtuMin 10 ` 41 | -DatabaseDtuMax 20 42 | $secondpool = New-AzureRmSqlElasticPool -ResourceGroupName $resourcegroupname ` 43 | -ServerName $servername ` 44 | -ElasticPoolName $secondpoolname ` 45 | -Edition "Standard" ` 46 | -Dtu 50 ` 47 | -DatabaseDtuMin 10 ` 48 | -DatabaseDtuMax 50 49 | 50 | # Create two blank databases in the first pool 51 | $firstdatabase = New-AzureRmSqlDatabase -ResourceGroupName $resourcegroupname ` 52 | -ServerName $servername ` 53 | -DatabaseName $firstdatabasename ` 54 | -ElasticPoolName $firstpoolname 55 | $seconddatabase = New-AzureRmSqlDatabase -ResourceGroupName $resourcegroupname ` 56 | -ServerName $servername ` 57 | -DatabaseName $seconddatabasename ` 58 | -ElasticPoolName $secondpoolname 59 | 60 | # Move the database to the second pool 61 | $firstdatabase = Set-AzureRmSqlDatabase -ResourceGroupName $resourcegroupname ` 62 | -ServerName $servername ` 63 | -DatabaseName $firstdatabasename ` 64 | -ElasticPoolName $secondpoolname 65 | 66 | # Move the database into a standalone performance level 67 | $firstdatabase = Set-AzureRmSqlDatabase -ResourceGroupName $resourcegroupname ` 68 | -ServerName $servername ` 69 | -DatabaseName $firstdatabasename ` 70 | -RequestedServiceObjectiveName "S0" -------------------------------------------------------------------------------- /common/code-upgrade-samples/azurerm/sqldb-restore-database.ps1: -------------------------------------------------------------------------------- 1 | # Original source code: https://github.com/Azure/azure-docs-powershell-samples/blob/5513f8ea73e2b9630311d7ea27372cddc4e65cae/sql-database/restore-database/restore-database.ps1 2 | 3 | # Set the resource group name and location for your server 4 | $resourcegroupname = "myResourceGroup-$(Get-Random)" 5 | $location = "westeurope" 6 | # Set an admin login and password for your server 7 | $adminlogin = "ServerAdmin" 8 | $password = "ChangeYourAdminPassword1" 9 | # Set server name - the logical server name has to be unique in the system 10 | $servername = "server-$(Get-Random)" 11 | # The sample database name 12 | $databasename = "mySampleDatabase" 13 | # The restored database names 14 | $pointintimerestoredatabasename = "MySampleDatabase_10MinutesAgo" 15 | # The ip address range that you want to allow to access your server 16 | $startip = "0.0.0.0" 17 | $endip = "0.0.0.0" 18 | 19 | 20 | # Create a resource group 21 | $resourcegroup = New-AzureRmResourceGroup -Name $resourcegroupname -Location $location 22 | 23 | # Create a server with a system wide unique server name 24 | $server = New-AzureRmSqlServer -ResourceGroupName $resourcegroupname ` 25 | -ServerName $servername ` 26 | -Location $location ` 27 | -SqlAdministratorCredentials $(New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $adminlogin, $(ConvertTo-SecureString -String $password -AsPlainText -Force)) 28 | 29 | # Create a server firewall rule that allows access from the specified IP range 30 | $firewallrule = New-AzureRmSqlServerFirewallRule -ResourceGroupName $resourcegroupname ` 31 | -ServerName $servername ` 32 | -FirewallRuleName "AllowedIPs" -StartIpAddress $startip -EndIpAddress $endip 33 | 34 | # Create a blank database with an S0 performance level 35 | $database = New-AzureRmSqlDatabase -ResourceGroupName $resourcegroupname ` 36 | -ServerName $servername ` 37 | -DatabaseName $databasename ` 38 | -RequestedServiceObjectiveName "S0" 39 | 40 | Start-Sleep -second 600 41 | 42 | # Restore database to its state 7 minutes ago 43 | # Note: Point-in-time restore requires database to be at least 5 minutes old 44 | Restore-AzureRmSqlDatabase ` 45 | -FromPointInTimeBackup ` 46 | -PointInTime (Get-Date).AddMinutes(-2) ` 47 | -ResourceGroupName $resourcegroupname ` 48 | -ServerName $servername ` 49 | -TargetDatabaseName $pointintimerestoredatabasename ` 50 | -ResourceId $database.ResourceID ` 51 | -Edition "Standard" ` 52 | -ServiceObjectiveName "S0" -------------------------------------------------------------------------------- /common/code-upgrade-samples/azurerm/webapp-back-restore.ps1: -------------------------------------------------------------------------------- 1 | # Original source code: https://github.com/Azure/azure-docs-powershell-samples/blob/77c8876ed0d79ba5538e3e583fe03aa514ae7661/app-service/backup-restore/backup-restore.ps1 2 | $resourceGroupName = "myResourceGroup" 3 | $webappname = "" 4 | 5 | 6 | # List statuses of all backups that are complete or currently executing. 7 | Get-AzureRmWebAppBackupList -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-AzureRmWebAppBackupList -ResourceGroupName $resourceGroupName -Name $webappname | where {$_.BackupId -eq ''}) 13 | 14 | # Restore the app by overwriting it with the backup data 15 | $backup | Restore-AzureRmWebAppBackup -Overwrite -------------------------------------------------------------------------------- /common/code-upgrade-samples/azurerm/webapp-create-from-github.ps1: -------------------------------------------------------------------------------- 1 | # Original source code: https://github.com/Azure/azure-docs-powershell-samples/blob/77c8876ed0d79ba5538e3e583fe03aa514ae7661/app-service/deploy-github/deploy-github.ps1 2 | # Replace the following URL with a public GitHub repo URL 3 | $gitrepo="https://github.com/Azure-Samples/app-service-web-dotnet-get-started.git" 4 | $webappname="mywebapp$(Get-Random)" 5 | $location="West Europe" 6 | 7 | # Create a resource group. 8 | New-AzureRmResourceGroup -Name myResourceGroup -Location $location 9 | 10 | # Create an App Service plan in Free tier. 11 | New-AzureRmAppServicePlan -Name $webappname -Location $location -ResourceGroupName myResourceGroup -Tier Free 12 | 13 | # Create a web app. 14 | New-AzureRmWebApp -Name $webappname -Location $location -AppServicePlan $webappname -ResourceGroupName myResourceGroup 15 | 16 | # Configure GitHub deployment from your GitHub repo and deploy once. 17 | $PropertiesObject = @{ 18 | repoUrl = "$gitrepo"; 19 | branch = "master"; 20 | isManualIntegration = "true"; 21 | } 22 | Set-AzureRmResource -PropertyObject $PropertiesObject -ResourceGroupName myResourceGroup -ResourceType Microsoft.Web/sites/sourcecontrols -ResourceName $webappname/web -ApiVersion 2015-08-01 -Force -------------------------------------------------------------------------------- /common/code-upgrade-samples/azurerm/webapp-monitor-with-logs.ps1: -------------------------------------------------------------------------------- 1 | # Original source code: https://github.com/Azure/azure-docs-powershell-samples/blob/77c8876ed0d79ba5538e3e583fe03aa514ae7661/app-service/monitor-with-logs/monitor-with-logs.ps1 2 | 3 | # Generates a Random Value 4 | $Random=(New-Guid).ToString().Substring(0,8) 5 | 6 | # Variables 7 | $ResourceGroupName="myResourceGroup$Random" 8 | $AppName="AppServiceMonitor$Random" 9 | $Location="WestUS" 10 | 11 | # Create a Resource Group 12 | New-AzureRMResourceGroup -Name $ResourceGroupName -Location $Location 13 | 14 | # Create an App Service Plan 15 | New-AzureRMAppservicePlan -Name AppServiceMonitorPlan -ResourceGroupName $ResourceGroupName -Location $Location -Tier Basic 16 | 17 | # Create a Web App in the App Service Plan 18 | New-AzureRMWebApp -Name $AppName -ResourceGroupName $ResourceGroupName -Location $Location -AppServicePlan AppServiceMonitorPlan 19 | 20 | # Enable Logs 21 | Set-AzureRMWebApp -RequestTracingEnabled $True -HttpLoggingEnabled $True -DetailedErrorLoggingEnabled $True -ResourceGroupName $ResourceGroupName -Name $AppName 22 | 23 | # Make a Request 24 | Invoke-WebRequest -Method "Get" -Uri https://$AppName.azurewebsites.net/404 -ErrorAction SilentlyContinue -------------------------------------------------------------------------------- /docs/how-to-update-az-module-spec.md: -------------------------------------------------------------------------------- 1 | # How to Update Az Module Spec 2 | 3 | The Az PowerShell module command and alias specifications are stored in 4 | `powershell-module\Az.Tools.Migration\Resources\ModuleSpecs\Az\{version}`. 5 | 6 | Occasionally, these should be updated to latest. This document describes how to update the spec to latest. 7 | 8 | ## Requirements 9 | 10 | Have the following installed on your system: 11 | 12 | * PowerShell 7.x or later. 13 | * Pester 4.10.1 (5.* cannot work due to breaking change) 14 | * Cloned the [azure-powershell-migration](https://github.com/Azure/azure-powershell-migration) 15 | GitHub repository to your local computer. 16 | 17 | ## Update Instructions 18 | 19 | 1. Open a PowerShell 7.x or later prompt. 20 | 21 | 1. Install the desired target version of the Az PowerShell module to your local computer, specifying 22 | the `CurrentUser` scope. For example, the following installs v4.6.1 in the current user's scope. 23 | 24 | ```powershell 25 | Install-Module -Name Az -RequiredVersion 4.6.1 -Repository PSGallery -Scope CurrentUser -AllowClobber -Force 26 | ``` 27 | 28 | 1. Go the root folder of cloned Github repository 29 | 30 | 1. Add module path into `$env:PSModulePath` 31 | ```powershell 32 | $env:PSModulePath += ';'+ (Join-Path -Path (Get-Location) -ChildPath 'powershell-module') 33 | ``` 34 | 35 | 1. Import the Az.Tools.Migration PowerShell module. 36 | 37 | ```powershell 38 | Import-Module -Name Az.Tools.Migration 39 | ``` 40 | 41 | 1. Run the module spec generation script for the desired version. 42 | 43 | * Update the module repo path to the file system location where you cloned the repository. 44 | * Ensure the Az PowerShell module version variable is set to the desired version. 45 | 46 | ```powershell 47 | # setup 48 | $azModuleVersion = '5.6.0' 49 | 50 | # execute 51 | .\powershell-module\Scripts\New-AzCmdletSpec.ps1 -AzVersion $azModuleVersion 52 | ``` 53 | 54 | 1. Remove the old module spec files from module resources: 55 | `powershell-module\Az.Tools.Migration\Resources\ModuleSpecs\Az\Latest\{old-version}`. 56 | 57 | 1. Run the unit tests to make sure all unit tests pass. 58 | 59 | It's common for some tests to fail because the expected number of aliases or cmdlets from the specs has changed. If so, please update the `$expectedAliasCount`/`$expectedCommandCount` in test files. 60 | 61 | Restart PowerShell Process and navigate to the root folder of cloned Github repository 62 | ```powershell 63 | <# Add the path of parent folder of module to environment variable #> 64 | $env:PSModulePath += ';'+ (Join-Path -Path (Get-Location) -ChildPath 'powershell-module') 65 | 66 | <# Go to the root folder of module #> 67 | cd powershell-module\Az.Tools.Migration 68 | 69 | Invoke-Pester 70 | ``` 71 | 72 | Restart PowerShell if test is changed and module needs to be imported again. 73 | 74 | 1. Add new version and release notes to `powershell-module/ChangeLog.md` and `powershell-module/Az.Tools.Migration/Az.Tools.Migration.psd1`. 75 | 76 | *Note: The major version of Az.Tools.Migration should be the major version of targeted Az Version. * 77 | 78 | 1. Submit a pull request to commit the new changes. 79 | -------------------------------------------------------------------------------- /docs/quickstart-migrate-azurerm-to-az-automatically.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: Automatically migrate PowerShell scripts from AzureRM to the Az PowerShell module 3 | description: Learn how to automatically migrate PowerShell scripts from AzureRM to the Az PowerShell module. 4 | author: mikefrobbins 5 | ms.service: azure-powershell 6 | ms.topic: quickstart 7 | ms.custom: devx-track-azurepowershell 8 | ms.author: mirobb 9 | ms.date: 09/11/2020 10 | --- 11 | 12 | # Quickstart: Automatically migrate PowerShell scripts from AzureRM to the Az PowerShell module 13 | 14 | In this article, you'll learn how to use the Az.Tools.Migration PowerShell module to automatically 15 | upgrade your PowerShell scripts and script modules from AzureRM to the Az PowerShell module. 16 | 17 | Report feedback and issues about the Az.Tools.Migration PowerShell module via 18 | [a GitHub issue](https://github.com/Azure/azure-powershell-migration/issues) in the 19 | `azure-powershell-migration` repository. 20 | 21 | ## Requirements 22 | 23 | * Update your existing PowerShell scripts to AzureRM PowerShell module version [6.13.1](https://github.com/Azure/azure-powershell/releases/tag/v6.13.1-November2018) or [6.13.2](https://github.com/Azure/azure-powershell/releases/tag/v6.13.2-March2021). 24 | * Install the Az.Tools.Migration PowerShell module. 25 | 26 | ```powershell 27 | Install-Module -Name Az.Tools.Migration 28 | ``` 29 | 30 | ## Step 1: Generate an upgrade plan 31 | 32 | You use the `New-AzUpgradeModulePlan` cmdlet to generate an upgrade plan for migrating your scripts 33 | and modules to the Az PowerShell module. The upgrade plan details the specific file and offset 34 | points that require changes when moving from AzureRM to the Az PowerShell cmdlets. 35 | 36 | > [!NOTE] 37 | > The `New-AzUpgradeModulePlan` cmdlet doesn't execute the plan, it only generates the upgrade steps. 38 | 39 | ```powershell 40 | # Generate an upgrade plan for the specified PowerShell script and save it to a variable. 41 | $Plan = New-AzUpgradeModulePlan -FromAzureRmVersion 6.13.1 -ToAzVersion latest -FilePath 'C:\Scripts\my-azure-script.ps1' 42 | ``` 43 | 44 | ```powershell 45 | # Generate an upgrade plan for all the scripts and module files in the specified folder and save it to a variable. 46 | $Plan = New-AzUpgradeModulePlan -FromAzureRmVersion 6.13.1 -ToAzVersion latest -DirectoryPath 'C:\Scripts' 47 | ``` 48 | 49 | Review the results of the upgrade plan. 50 | 51 | ```powershell 52 | # Show the entire upgrade plan 53 | $Plan 54 | ``` 55 | 56 | Run the following command to filter the results to commands that have warnings or errors. This may 57 | be helpful on large result sets to quickly identify errors before performing the upgrade. 58 | 59 | ```powershell 60 | # Filter plan results to only warnings and errors 61 | $Plan | Where-Object PlanResult -ne ReadyToUpgrade | Format-List 62 | ``` 63 | 64 | ## Step 2: Perform the upgrade 65 | 66 | The upgrade plan is executed when you run the `Invoke-AzUpgradeModulePlan` cmdlet. This command performs 67 | an upgrade of the specified file or folders except for any errors that were identified by the `New-AzUpgradeModulePlan` cmdlet. 68 | 69 | This command requires you to specify if the files should be modified in place or if new files should be saved 70 | alongside your original files (leaving originals unmodified). 71 | 72 | > [!CAUTION] 73 | > There is no undo operation. Always ensure that you have a backup copy of your PowerShell scripts 74 | > and modules that you're attempting to upgrade. 75 | 76 | > [!WARNING] 77 | > The `Invoke-AzUpgradeModulePlan` cmdlet is destructive when the `-FileEditMode ModifyExistingFiles` option is specified! It modifies your scripts and functions 78 | > in place according to the module upgrade plan generated by the `New-AzUpgradeModulePlan` cmdlet. For the non-destructive option specify `-FileEditMode SaveChangesToNewFiles` instead. 79 | 80 | ```powershell 81 | # Execute the automatic upgrade plan and save the results to a variable. 82 | $Results = Invoke-AzUpgradeModulePlan -Plan $Plan -FileEditMode SaveChangesToNewFiles 83 | ``` 84 | 85 | Review the results of the upgrade operation. 86 | 87 | ```powershell 88 | # Show the results for the entire upgrade operation 89 | $Results 90 | ``` 91 | 92 | If any errors are returned, you can take a closer look at the error results with the following command: 93 | 94 | ```powershell 95 | # Filter results to show only errors 96 | $Results | Where-Object UpgradeResult -ne UpgradeCompleted | Format-List 97 | ``` 98 | 99 | ## Limitations 100 | 101 | * File I/O operations use default encoding. Unusual file encoding situations may cause problems. 102 | * AzureRM cmdlets passed as arguments to Pester unit test mock statements aren't detected. 103 | * Currently, only Az PowerShell module version 10.3 is supported as a target. 104 | 105 | ## Next steps 106 | 107 | To learn more about the Az PowerShell module, see the [Azure PowerShell documentation](https://docs.microsoft.com/powershell/azure/) -------------------------------------------------------------------------------- /package-lock.json: -------------------------------------------------------------------------------- 1 | { 2 | "lockfileVersion": 1 3 | } 4 | -------------------------------------------------------------------------------- /powershell-module/.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | //-------- Files configuration -------- 3 | 4 | // always insert spaces instead of tabs, regardless of the current file's detected indentation. 5 | // 6 | // NOTE: on file save, VSCode will not automatically convert existing tab characters into spaces. 7 | // there is however a built-in VSCode command to accomplish this task on a file. Steps to correct the tabs on a single file: 8 | // 9 | // 1. Open a file in VSCode. 10 | // 2. Use Ctrl+Shift+P to bring up the command palette. 11 | // 3. Search for the command "Convert Indentation To Spaces" and select the result. 12 | // 4. This will run the action to convert tabs to spaces for the currently open file. 13 | // 14 | "editor.detectIndentation": false, 15 | "editor.insertSpaces": true, 16 | "editor.tabSize": 4, 17 | 18 | // trim trailing whitespace automatically when you save a file. 19 | "files.trimTrailingWhitespace": true, 20 | 21 | // trim trailing newlines at the end of a file automatically when you save a file. 22 | "files.trimFinalNewlines": true, 23 | 24 | //-------- PowerShell Configuration -------- 25 | 26 | // Use a custom PowerShell Script Analyzer settings file for this workspace. 27 | // Relative paths for this setting are always relative to the workspace root dir. 28 | "powershell.scriptAnalysis.settingsPath": "PSScriptAnalyzerSettings.psd1", 29 | 30 | // update the default word separators to remove the $ character. 31 | // this means you can double click on a PowerShell variable name (ex: $myVariable) and it 32 | // will correctly select the entire variable (including $) instead of just selecting the word. 33 | "editor.wordSeparators": "`~!@#%^&*()-=+[{]}\\|;:'\",.<>/?" 34 | } 35 | -------------------------------------------------------------------------------- /powershell-module/Az.Tools.Migration/Az.Tools.Migration.psm1: -------------------------------------------------------------------------------- 1 | <# 2 | The module manifest (.psd1) defines this file as the entry point or root of the module. 3 | Ensure that all of the module functionality is loaded directly from this file. 4 | #> 5 | 6 | # conditionally load required assemblies (in this case Newtonsoft.Json) 7 | # PowerShell Core has this assembly loaded by default. 8 | # Windows PowerShell does not ship with this so it usually needs to be loaded. 9 | 10 | $jsonType = [System.AppDomain]::CurrentDomain.GetAssemblies() | ForEach-Object { $_.GetTypes() | Where-Object { $_.FullName -eq "Newtonsoft.Json.JsonConvert" } } 11 | 12 | if ($jsonType -eq $null) 13 | { 14 | # type is not already loaded. 15 | # attempt to load this assembly from the resources folder. 16 | Add-Type -Path "$PSScriptRoot\Resources\Assembly\Newtonsoft.Json.12.0.3\Newtonsoft.Json.dll" -ErrorAction Stop 17 | } 18 | 19 | # load classes 20 | 21 | foreach ($classFile in (Get-ChildItem -Path "$PSScriptRoot\Classes" -Recurse -Include "*.ps1")) 22 | { 23 | . $classFile 24 | } 25 | 26 | # load functions 27 | 28 | foreach ($functionFile in (Get-ChildItem -Path "$PSScriptRoot\Functions" -Recurse -Include "*.ps1")) 29 | { 30 | . $functionFile 31 | } -------------------------------------------------------------------------------- /powershell-module/Az.Tools.Migration/Functions/Private/Confirm-StringBuilderSubstring.ps1: -------------------------------------------------------------------------------- 1 | function Confirm-StringBuilderSubstring 2 | { 3 | <# 4 | .SYNOPSIS 5 | Confirms that the substring exists at the specified offset in the string builder. 6 | 7 | .DESCRIPTION 8 | Confirms that the substring exists at the specified offset in the string builder. An error will be thrown if the offset positions do not match expectation. 9 | 10 | .PARAMETER FileContents 11 | Specify the file contents wrapped in a stringbuilder. 12 | 13 | .PARAMETER Substring 14 | Specify the substring to validate. 15 | 16 | .PARAMETER StartOffset 17 | Specify the start offset position. 18 | 19 | .PARAMETER EndOffset 20 | Specify the end offset position. 21 | 22 | .EXAMPLE 23 | PS C:\ Confirm-StringBuilderSubstring -FileContent $builder -Substring '-test' -StartOffset 23 -EndOffset 28 24 | Confirms that the substring '-test' exists at the specified offset. 25 | #> 26 | [CmdletBinding()] 27 | Param 28 | ( 29 | [Parameter( 30 | Mandatory=$true, 31 | HelpMessage='Specify the file contents wrapped in a stringbuilder.')] 32 | [System.Text.StringBuilder] 33 | [ValidateNotNull()] 34 | $FileContent, 35 | 36 | [Parameter( 37 | Mandatory=$true, 38 | HelpMessage='Specify the substring to validate.')] 39 | [System.String] 40 | [ValidateNotNullOrEmpty()] 41 | $Substring, 42 | 43 | [Parameter( 44 | Mandatory=$true, 45 | HelpMessage='Specify the start offset position.')] 46 | [System.String] 47 | [ValidateNotNullOrEmpty()] 48 | $StartOffset, 49 | 50 | [Parameter( 51 | Mandatory=$true, 52 | HelpMessage='Specify the end offset position.')] 53 | [System.String] 54 | [ValidateNotNullOrEmpty()] 55 | $EndOffset 56 | ) 57 | Process 58 | { 59 | if ($FileContent.Length -lt $StartOffset -or $FileContent.Length -lt $EndOffset) 60 | { 61 | throw 'Upgrade step failed: Offset positions are beyond the file range.' 62 | } 63 | 64 | for (([int]$i = $StartOffset), ([int]$j = 0); $i -lt $EndOffset; ($i++), ($j++)) 65 | { 66 | if ($FileContent[$i] -ne $Substring[$j]) 67 | { 68 | throw 'Upgrade step failed: Offset positions are unexpected. This file may have already been upgraded or has changed since the upgrade plan was generated.' 69 | } 70 | } 71 | } 72 | } -------------------------------------------------------------------------------- /powershell-module/Az.Tools.Migration/Functions/Private/Get-ModulePreferences.ps1: -------------------------------------------------------------------------------- 1 | function Get-ModulePreferences 2 | { 3 | <# 4 | .SYNOPSIS 5 | Returns the current data collection settings for this module. 6 | 7 | .DESCRIPTION 8 | Returns the current data collection settings for this module. 9 | 10 | Data collection can be enabled or disabled with the Enable-AzUpgradeDataCollection and Disabled-AzUpgradeDataCollection commands. 11 | 12 | .EXAMPLE 13 | PS C:\ Get-ModulePreferences 14 | Returns the data collection settings. 15 | #> 16 | [CmdletBinding()] 17 | Param 18 | ( 19 | ) 20 | Process 21 | { 22 | $configurationDirectory = "$home\" + ([Constants]::ConfigurationDirectoryName) 23 | $configurationFileFullPath = Join-Path -Path $configurationDirectory -ChildPath ([Constants]::ConfigurationFileName) 24 | 25 | try 26 | { 27 | if ((Test-Path -Path $configurationFileFullPath) -eq $false) 28 | { 29 | Write-Verbose -Message "Module configuration file $configurationFileFullPath does not exist, creating it now." 30 | 31 | $null = New-Item -Path $configurationDirectory -ItemType Directory -Force 32 | 33 | $newConfig = New-Object -TypeName ModulePreferences 34 | $newConfig.DataCollectionEnabled = $true 35 | 36 | $null = $newConfig | ConvertTo-Json | Out-File -FilePath $configurationFileFullPath -Force 37 | 38 | Write-Output -InputObject $newConfig 39 | } 40 | else 41 | { 42 | Write-Verbose -Message "Module configuration file $configurationFileFullPath exists, loading it now." 43 | 44 | $modulePreferencesRawJson = Get-Content -Path $configurationFileFullPath -Raw 45 | $existingConfig = [Newtonsoft.Json.JsonConvert]::DeserializeObject($modulePreferencesRawJson, [ModulePreferences]) 46 | 47 | Write-Output -InputObject $existingConfig 48 | } 49 | } 50 | catch 51 | { 52 | Write-Verbose -Message "Configuration file error: $_" 53 | 54 | # if we hit configuration file serialization issues, or file i/o 55 | # problems, then return an option set that assumes the user has 56 | # turned off data collection -- just to be safe. 57 | 58 | $newConfig = New-Object -TypeName ModulePreferences 59 | $newConfig.DataCollectionEnabled = $false 60 | Write-Output -InputObject $newConfig 61 | } 62 | } 63 | } -------------------------------------------------------------------------------- /powershell-module/Az.Tools.Migration/Functions/Private/Invoke-ModuleUpgradeStep.ps1: -------------------------------------------------------------------------------- 1 | function Invoke-ModuleUpgradeStep 2 | { 3 | <# 4 | .SYNOPSIS 5 | Runs the individual module upgrade step against the file contents. 6 | 7 | .DESCRIPTION 8 | Runs the individual module upgrade step against the file contents. The file contents are passed in as a stringbuilder 9 | and the edits for this individual upgrade step are performed against that directly. 10 | 11 | .PARAMETER Step 12 | Specify the upgrade step. 13 | 14 | .PARAMETER FileContents 15 | Specify the file contents wrapped in a stringbuilder. 16 | 17 | .EXAMPLE 18 | PS C:\ Invoke-ModuleUpgradeStep -Step $upgradeStep -FileContent $contentsBuilder 19 | Performs an in-line text update for the specified module upgrade step. 20 | #> 21 | [CmdletBinding()] 22 | Param 23 | ( 24 | [Parameter( 25 | Mandatory=$true, 26 | HelpMessage='Specify the upgrade step.')] 27 | [UpgradePlan] 28 | [ValidateNotNull()] 29 | $Step, 30 | 31 | [Parameter( 32 | Mandatory=$true, 33 | HelpMessage='Specify the file contents wrapped in a stringbuilder.')] 34 | [System.Text.StringBuilder] 35 | [ValidateNotNull()] 36 | $FileContent 37 | ) 38 | Process 39 | { 40 | switch ($Step.UpgradeType) 41 | { 42 | "Cmdlet" 43 | { 44 | Write-Verbose -Message ("[{0}] Updating Cmdlet {1} to {2}." ` 45 | -f $Step.Location, $Step.Original, $Step.Replacement) 46 | 47 | # safety check 48 | # ensure that the file offsets are an exact match. 49 | Confirm-StringBuilderSubstring -FileContent $FileContent -Substring $Step.Original ` 50 | -StartOffset $Step.SourceCommand.StartOffset -EndOffset $Step.SourceCommand.EndOffset 51 | 52 | # replacement code 53 | $null = $FileContent.Remove($Step.SourceCommand.StartOffset, ($Step.SourceCommand.EndOffset - $Step.SourceCommand.StartOffset)) 54 | $null = $FileContent.Insert($Step.SourceCommand.StartOffset, $Step.Replacement) 55 | } 56 | "CmdletParameter" 57 | { 58 | if ([System.String]::IsNullOrWhiteSpace($Step.Replacement) -eq $false) 59 | { 60 | Write-Verbose -Message ("[{0}] Updating CmdletParameter {1} to {2}." ` 61 | -f $Step.Location, $Step.Original, $Step.Replacement) 62 | 63 | # safety check 64 | # ensure that the file offsets are an exact match. 65 | Confirm-StringBuilderSubstring -FileContent $FileContent -Substring $Step.Original ` 66 | -StartOffset $Step.SourceCommandParameter.StartOffset -EndOffset $Step.SourceCommandParameter.EndOffset 67 | 68 | # replacement code 69 | $null = $FileContent.Remove($Step.SourceCommandParameter.StartOffset, ($Step.SourceCommandParameter.EndOffset - $Step.SourceCommandParameter.StartOffset)) 70 | $null = $FileContent.Insert($Step.SourceCommandParameter.StartOffset, $Step.Replacement) 71 | } 72 | else 73 | { 74 | Write-Verbose -Message ("[{0}] Skipping CmdletParameter {1}, it has no automated replacement." ` 75 | -f $Step.Location, $Step.Original) 76 | } 77 | } 78 | default 79 | { 80 | throw 'Unexpected upgrade step type found.' 81 | } 82 | } 83 | } 84 | } -------------------------------------------------------------------------------- /powershell-module/Az.Tools.Migration/Functions/Private/New-ModifiedFileName.ps1: -------------------------------------------------------------------------------- 1 | function New-ModifiedFileName 2 | { 3 | <# 4 | .SYNOPSIS 5 | Generates a new file name for a modified PowerShell file. 6 | 7 | .DESCRIPTION 8 | Generates a new file name for a modified PowerShell file. 9 | 10 | .PARAMETER Path 11 | Specify the existing/original file path. 12 | 13 | .EXAMPLE 14 | PS C:\> New-ModifiedFileName -Path 'C:\scripts\test.ps1' 15 | Returns a new modified file name. 16 | #> 17 | [CmdletBinding()] 18 | Param 19 | ( 20 | [Parameter( 21 | Mandatory=$true, 22 | HelpMessage='Specify the existing/original file path.')] 23 | [System.String] 24 | $Path 25 | ) 26 | Process 27 | { 28 | # create a FileInfo object so we can quickly retrieve parts of the path and/or filename. 29 | $fileInfo = New-Object -TypeName 'System.IO.FileInfo' -ArgumentList $Path 30 | 31 | if ($fileInfo.Extension.Length -gt 0) 32 | { 33 | # handling for normal files with extensions 34 | $baseFileName = ($fileInfo.Name.Remove($fileInfo.Name.Length - $fileInfo.Extension.Length)) 35 | $newFileName = $baseFileName + [Constants]::NewFileBaseNameSuffix + $fileInfo.Extension 36 | } 37 | else 38 | { 39 | # extensionless file handling 40 | $newFileName = $fileInfo.Name + [Constants]::NewFileBaseNameSuffix 41 | } 42 | 43 | Write-Output -InputObject (Join-Path -Path $fileInfo.DirectoryName -ChildPath $newFileName) 44 | } 45 | } -------------------------------------------------------------------------------- /powershell-module/Az.Tools.Migration/Functions/Private/Out-FileBatchResult.ps1: -------------------------------------------------------------------------------- 1 | function Out-FileBatchResult 2 | { 3 | <# 4 | .SYNOPSIS 5 | Writes a batch of file update results to the pipeline. 6 | 7 | .DESCRIPTION 8 | Writes a batch of file update results to the pipeline. 9 | 10 | .PARAMETER Results 11 | Specify the results batch. 12 | 13 | .PARAMETER Success 14 | Specify if this batch of updates was successful. 15 | 16 | .PARAMETER Reason 17 | Specify the reason/message for success or failure. 18 | 19 | .EXAMPLE 20 | PS C:\ Out-FileBatchResult -ResultBatch $resultsBatch -Success $true -Reason "Completed successfully" 21 | Writes the current batch of file update results to the pipeline. 22 | #> 23 | [CmdletBinding()] 24 | Param 25 | ( 26 | [Parameter( 27 | Mandatory=$true, 28 | HelpMessage='Specify the results batch.')] 29 | [System.Collections.Generic.List[UpgradeResult]] 30 | [ValidateNotNull()] 31 | $ResultBatch, 32 | 33 | [Parameter( 34 | Mandatory=$true, 35 | HelpMessage='Specify if this batch of updates was successful.')] 36 | [System.Boolean] 37 | [ValidateNotNull()] 38 | $Success, 39 | 40 | [Parameter( 41 | Mandatory=$true, 42 | HelpMessage='Specify the reason/message for success or failure.')] 43 | [System.String] 44 | [ValidateNotNullOrEmpty()] 45 | $Reason 46 | ) 47 | Process 48 | { 49 | foreach ($result in $ResultBatch) 50 | { 51 | if ($result.UpgradeResult -ne [UpgradeResultReasonCode]::UnableToUpgrade) 52 | { 53 | if ($Success) 54 | { 55 | if ($result.UpgradeResultReason -ne $null) 56 | { 57 | $result.UpgradeResultReason = $Reason 58 | } 59 | } 60 | else 61 | { 62 | $result.UpgradeResult = [UpgradeResultReasonCode]::UpgradeActionFailed 63 | $result.UpgradeSeverity = [DiagnosticSeverity]::Error 64 | $result.UpgradeResultReason = $Reason 65 | } 66 | } 67 | 68 | # write the output object 69 | Write-Output -InputObject $result 70 | } 71 | } 72 | } -------------------------------------------------------------------------------- /powershell-module/Az.Tools.Migration/Functions/Private/Set-ModulePreference.ps1: -------------------------------------------------------------------------------- 1 | function Set-ModulePreference 2 | { 3 | <# 4 | .SYNOPSIS 5 | Sets the user's module preferences. 6 | 7 | .DESCRIPTION 8 | Sets the user's module preferences. Preferences are stored in a JSON config file under the user's home directory. 9 | 10 | .PARAMETER DataCollection 11 | Specifies the value for the data collection preference. 12 | 13 | .EXAMPLE 14 | PS C:\ Set-ModulePreference -DataCollectionEnabled $false 15 | Sets the data collection preference to false. 16 | #> 17 | [CmdletBinding()] 18 | Param 19 | ( 20 | [Parameter( 21 | Mandatory=$true, 22 | ParameterSetName='DataCollection', 23 | HelpMessage='Specify the value for the data collection preference.')] 24 | [System.Boolean] 25 | $DataCollectionEnabled 26 | ) 27 | Process 28 | { 29 | # this will create the preferences if they haven't been initialized yet. 30 | $existingModulePreferences = Get-ModulePreferences 31 | 32 | $configurationDirectory = "$home\" + ([Constants]::ConfigurationDirectoryName) 33 | $configurationFileFullPath = Join-Path -Path $configurationDirectory -ChildPath ([Constants]::ConfigurationFileName) 34 | 35 | if ($PSCmdlet.ParameterSetName -eq 'DataCollection') 36 | { 37 | if ($existingModulePreferences.DataCollectionEnabled -ne $DataCollectionEnabled) 38 | { 39 | Write-Verbose -Message "Setting module preference DataCollectionEnabled to $DataCollectionEnabled" 40 | $existingModulePreferences.DataCollectionEnabled = $DataCollectionEnabled 41 | $null = $existingModulePreferences | ConvertTo-Json | Out-File -FilePath $configurationFileFullPath -Force 42 | } 43 | else 44 | { 45 | Write-Verbose -Message "Module preference DataCollectionEnabled is already set to $DataCollectionEnabled" 46 | } 47 | } 48 | 49 | Write-Output -InputObject $existingModulePreferences 50 | } 51 | } -------------------------------------------------------------------------------- /powershell-module/Az.Tools.Migration/Functions/Public/Disable-AzUpgradeDataCollection.ps1: -------------------------------------------------------------------------------- 1 | function Disable-AzUpgradeDataCollection 2 | { 3 | <# 4 | .SYNOPSIS 5 | Disables the setting that allows Az.Tools.Migration to send usage metrics to Microsoft. 6 | 7 | .DESCRIPTION 8 | Disables the setting that allows Az.Tools.Migration to send usage metrics to Microsoft. 9 | 10 | Usage metrics are opted-in by default. To disable usage metrics, run this cmdlet. 11 | 12 | This setting is scoped to the user profile and persists between PowerShell sessions. 13 | 14 | .EXAMPLE 15 | PS C:\ Disable-AzUpgradeDataCollection 16 | Disables the metrics collection for Az.Tools.Migration. 17 | #> 18 | [CmdletBinding()] 19 | Param 20 | ( 21 | ) 22 | Process 23 | { 24 | Set-ModulePreference -DataCollectionEnabled $false 25 | } 26 | } -------------------------------------------------------------------------------- /powershell-module/Az.Tools.Migration/Functions/Public/Enable-AzUpgradeDataCollection.ps1: -------------------------------------------------------------------------------- 1 | function Enable-AzUpgradeDataCollection 2 | { 3 | <# 4 | .SYNOPSIS 5 | Enables the setting that allows Az.Tools.Migration to send usage metrics to Microsoft. 6 | 7 | .DESCRIPTION 8 | Enables the setting that allows Az.Tools.Migration to send usage metrics to Microsoft. 9 | 10 | Usage metrics are opted-in by default. To disable usage metrics, run the Disabled-AzUpgradeDataCollection cmdlet. 11 | 12 | This setting is scoped to the user profile and persists between PowerShell sessions. 13 | 14 | .EXAMPLE 15 | PS C:\ Enable-AzUpgradeDataCollection 16 | Enables the metrics collection for Az.Tools.Migration. 17 | #> 18 | [CmdletBinding()] 19 | Param 20 | ( 21 | ) 22 | Process 23 | { 24 | Set-ModulePreference -DataCollectionEnabled $true 25 | } 26 | } -------------------------------------------------------------------------------- /powershell-module/Az.Tools.Migration/Functions/Public/Get-AzUpgradeAliasSpec.ps1: -------------------------------------------------------------------------------- 1 | function Get-AzUpgradeAliasSpec 2 | { 3 | <# 4 | .SYNOPSIS 5 | Returns a dictionary containing cmdlet alias mappings for the specified Az module version. 6 | 7 | .DESCRIPTION 8 | Returns a dictionary containing cmdlet alias mappings for the specified Az module version. 9 | 10 | .PARAMETER ModuleVersion 11 | Specify the version of the module to import command aliases from. 12 | 13 | .EXAMPLE 14 | PS C:\> Get-AzUpgradeAliasSpec -ModuleVersion latest 15 | Returns the cmdlet alias mappings table for latest Az version 16 | #> 17 | [CmdletBinding()] 18 | Param 19 | ( 20 | [Parameter( 21 | Mandatory=$true, 22 | HelpMessage="Specify the version of the module to import command definitions from.")] 23 | [System.String] 24 | [ValidateNotNullOrEmpty()] 25 | [ValidateSet('latest')] 26 | $ModuleVersion 27 | ) 28 | Process 29 | { 30 | $path = Join-Path -Path $MyInvocation.MyCommand.Module.ModuleBase -ChildPath "\Resources\ModuleSpecs\Az\$ModuleVersion" 31 | $version = Get-ChildItem -Path $path -Name 32 | 33 | $aliasSpecFile = Join-Path -Path $path ` 34 | -ChildPath "$version\CmdletAliases\Aliases.json" 35 | 36 | if ((Test-Path -Path $aliasSpecFile) -eq $false) 37 | { 38 | throw "No alias spec files found for Az $ModuleVersion" 39 | } 40 | 41 | $specFileRawJson = Get-Content -Path $aliasSpecFile -Raw 42 | $specObjects = [Newtonsoft.Json.JsonConvert]::DeserializeObject($specFileRawJson, [AliasMapping[]]) 43 | 44 | $aliasMap = New-Object -TypeName 'System.Collections.Generic.Dictionary[System.String,System.String]' -ArgumentList (, [System.StringComparer]::OrdinalIgnoreCase) 45 | 46 | foreach ($aliasObject in $specObjects) 47 | { 48 | $aliasMap[$aliasObject.Name] = $aliasObject.ResolvedCommand 49 | } 50 | 51 | Write-Output -InputObject $aliasMap 52 | } 53 | } -------------------------------------------------------------------------------- /powershell-module/Az.Tools.Migration/Functions/Public/Get-AzUpgradeCmdletSpec.ps1: -------------------------------------------------------------------------------- 1 | function Get-AzUpgradeCmdletSpec 2 | { 3 | <# 4 | .SYNOPSIS 5 | Returns a dictionary containing cmdlet specification objects for the specified module. 6 | 7 | .DESCRIPTION 8 | Returns a dictionary containing cmdlet specification objects for the specified module. 9 | 10 | .PARAMETER ModuleName 11 | Specify the name of the module to load command definitions from. 12 | 13 | .PARAMETER ModuleVersion 14 | Specify the version of the module to load command definitions from. 15 | 16 | .EXAMPLE 17 | PS C:\> Get-AzUpgradeCmdletSpec -AzureRM 18 | Returns the dictionary containing cmdlet specification objects for AzureRM 6.13.1. 19 | #> 20 | [CmdletBinding()] 21 | Param 22 | ( 23 | [Parameter( 24 | Mandatory=$true, 25 | ParameterSetName = "AzureRM", 26 | HelpMessage="Import command definitions from AzureRM modules.")] 27 | [System.Management.Automation.SwitchParameter] 28 | $AzureRM, 29 | 30 | [Parameter( 31 | Mandatory=$true, 32 | ParameterSetName = "Az", 33 | HelpMessage="Import command definitions from Az modules.")] 34 | [System.Management.Automation.SwitchParameter] 35 | $Az, 36 | 37 | [Parameter( 38 | Mandatory=$true, 39 | ParameterSetName = "Az", 40 | HelpMessage="Specify the version of the module to import command definitions from.")] 41 | [System.String] 42 | [ValidateSet('latest')] 43 | [ValidateNotNullOrEmpty()] 44 | $ModuleVersion 45 | ) 46 | Process 47 | { 48 | $ModuleSpecFolder = Join-Path -Path $MyInvocation.MyCommand.Module.ModuleBase ` 49 | -ChildPath "Resources\ModuleSpecs" 50 | if ($PSBoundParameters.ContainsKey('AzureRM')) { 51 | $ModuleSpecFolder = Join-Path -Path $ModuleSpecFolder -ChildPath "AzureRM\6.13.1" 52 | } else { 53 | $version = Get-ChildItem -Path "$ModuleSpecFolder/Az/$ModuleVersion" -Name 54 | $ModuleSpecFolder = Join-Path -Path $ModuleSpecFolder -ChildPath "Az\$ModuleVersion\$version" 55 | } 56 | 57 | if ((Test-Path -Path $ModuleSpecFolder) -eq $false) 58 | { 59 | throw "No module spec files found for module: $ModuleName $version under $ModuleSpecFolder" 60 | } 61 | 62 | $ModuleSpecFiles = Get-ChildItem -Path $ModuleSpecFolder -File 63 | 64 | if ($ModuleSpecFiles -eq $null) 65 | { 66 | throw "No module spec files found for module: $ModuleName $version under $ModuleSpecFolder" 67 | } 68 | 69 | $results = New-Object -TypeName 'System.Collections.Generic.Dictionary[System.String,CommandDefinition]' -ArgumentList (, [System.StringComparer]::OrdinalIgnoreCase) 70 | 71 | foreach ($specFile in $ModuleSpecFiles) 72 | { 73 | try 74 | { 75 | $specFileRawJson = Get-Content -Path $specFile.FullName -Raw 76 | $specObjects = [Newtonsoft.Json.JsonConvert]::DeserializeObject($specFileRawJson, [CommandDefinition[]]) 77 | 78 | foreach ($specObject in $specObjects) 79 | { 80 | $results[$specObject.Command] = $specObject 81 | } 82 | } 83 | catch 84 | { 85 | Write-Warning -Message "Failed to load module spec file: $($specFile.Name): $_" 86 | } 87 | } 88 | 89 | Write-Output -InputObject $results 90 | } 91 | } -------------------------------------------------------------------------------- /powershell-module/Az.Tools.Migration/Resources/Assembly/Microsoft.ApplicationInsights.2.12.0/Microsoft.ApplicationInsights.dll: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Azure/azure-powershell-migration/55f68b18251e6916545c2feab910e8c1cc404b29/powershell-module/Az.Tools.Migration/Resources/Assembly/Microsoft.ApplicationInsights.2.12.0/Microsoft.ApplicationInsights.dll -------------------------------------------------------------------------------- /powershell-module/Az.Tools.Migration/Resources/Assembly/Newtonsoft.Json.12.0.3/Newtonsoft.Json.dll: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Azure/azure-powershell-migration/55f68b18251e6916545c2feab910e8c1cc404b29/powershell-module/Az.Tools.Migration/Resources/Assembly/Newtonsoft.Json.12.0.3/Newtonsoft.Json.dll -------------------------------------------------------------------------------- /powershell-module/Az.Tools.Migration/Resources/ModuleSpecs/AzureRM/6.13.1/AzureRM.Billing.0.14.6.Cmdlets.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "Command": "Get-AzureRmBillingInvoice", 4 | "IsAlias": false, 5 | "SourceModule": "AzureRM.Billing", 6 | "Version": "0.14.6", 7 | "Parameters": [ 8 | { 9 | "Name": "Latest", 10 | "Aliases": null 11 | }, 12 | { 13 | "Name": "Name", 14 | "Aliases": null 15 | }, 16 | { 17 | "Name": "MaxCount", 18 | "Aliases": null 19 | }, 20 | { 21 | "Name": "GenerateDownloadUrl", 22 | "Aliases": null 23 | }, 24 | { 25 | "Name": "DefaultProfile", 26 | "Aliases": [ 27 | "AzureRmContext", 28 | "AzureCredential" 29 | ] 30 | } 31 | ] 32 | }, 33 | { 34 | "Command": "Get-AzureRmBillingPeriod", 35 | "IsAlias": false, 36 | "SourceModule": "AzureRM.Billing", 37 | "Version": "0.14.6", 38 | "Parameters": [ 39 | { 40 | "Name": "Name", 41 | "Aliases": null 42 | }, 43 | { 44 | "Name": "MaxCount", 45 | "Aliases": null 46 | }, 47 | { 48 | "Name": "DefaultProfile", 49 | "Aliases": [ 50 | "AzureRmContext", 51 | "AzureCredential" 52 | ] 53 | } 54 | ] 55 | }, 56 | { 57 | "Command": "Get-AzureRmEnrollmentAccount", 58 | "IsAlias": false, 59 | "SourceModule": "AzureRM.Billing", 60 | "Version": "0.14.6", 61 | "Parameters": [ 62 | { 63 | "Name": "ObjectId", 64 | "Aliases": null 65 | }, 66 | { 67 | "Name": "DefaultProfile", 68 | "Aliases": [ 69 | "AzureRmContext", 70 | "AzureCredential" 71 | ] 72 | } 73 | ] 74 | } 75 | ] 76 | -------------------------------------------------------------------------------- /powershell-module/Az.Tools.Migration/Resources/ModuleSpecs/AzureRM/6.13.1/AzureRM.MarketplaceOrdering.0.2.7.Cmdlets.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "Command": "Get-AzureRmMarketplaceTerms", 4 | "IsAlias": false, 5 | "SourceModule": "AzureRM.MarketplaceOrdering", 6 | "Version": "0.2.7", 7 | "Parameters": [ 8 | { 9 | "Name": "Publisher", 10 | "Aliases": null 11 | }, 12 | { 13 | "Name": "Product", 14 | "Aliases": null 15 | }, 16 | { 17 | "Name": "Name", 18 | "Aliases": null 19 | }, 20 | { 21 | "Name": "DefaultProfile", 22 | "Aliases": [ 23 | "AzureRmContext", 24 | "AzureCredential" 25 | ] 26 | } 27 | ] 28 | }, 29 | { 30 | "Command": "Set-AzureRmMarketplaceTerms", 31 | "IsAlias": false, 32 | "SourceModule": "AzureRM.MarketplaceOrdering", 33 | "Version": "0.2.7", 34 | "Parameters": [ 35 | { 36 | "Name": "Publisher", 37 | "Aliases": null 38 | }, 39 | { 40 | "Name": "Product", 41 | "Aliases": null 42 | }, 43 | { 44 | "Name": "Name", 45 | "Aliases": null 46 | }, 47 | { 48 | "Name": "Accept", 49 | "Aliases": null 50 | }, 51 | { 52 | "Name": "Reject", 53 | "Aliases": null 54 | }, 55 | { 56 | "Name": "Terms", 57 | "Aliases": null 58 | }, 59 | { 60 | "Name": "InputObject", 61 | "Aliases": null 62 | }, 63 | { 64 | "Name": "DefaultProfile", 65 | "Aliases": [ 66 | "AzureRmContext", 67 | "AzureCredential" 68 | ] 69 | }, 70 | { 71 | "Name": "WhatIf", 72 | "Aliases": [ 73 | "wi" 74 | ] 75 | }, 76 | { 77 | "Name": "Confirm", 78 | "Aliases": [ 79 | "cf" 80 | ] 81 | } 82 | ] 83 | } 84 | ] 85 | -------------------------------------------------------------------------------- /powershell-module/Az.Tools.Migration/Resources/ModuleSpecs/AzureRM/6.13.1/AzureRM.Tags.4.0.5.Cmdlets.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "Command": "Remove-AzureRmTag", 4 | "IsAlias": false, 5 | "SourceModule": "AzureRM.Tags", 6 | "Version": "4.0.5", 7 | "Parameters": [ 8 | { 9 | "Name": "Name", 10 | "Aliases": null 11 | }, 12 | { 13 | "Name": "Value", 14 | "Aliases": null 15 | }, 16 | { 17 | "Name": "PassThru", 18 | "Aliases": null 19 | }, 20 | { 21 | "Name": "DefaultProfile", 22 | "Aliases": [ 23 | "AzureRmContext", 24 | "AzureCredential" 25 | ] 26 | }, 27 | { 28 | "Name": "WhatIf", 29 | "Aliases": [ 30 | "wi" 31 | ] 32 | }, 33 | { 34 | "Name": "Confirm", 35 | "Aliases": [ 36 | "cf" 37 | ] 38 | } 39 | ] 40 | }, 41 | { 42 | "Command": "Get-AzureRmTag", 43 | "IsAlias": false, 44 | "SourceModule": "AzureRM.Tags", 45 | "Version": "4.0.5", 46 | "Parameters": [ 47 | { 48 | "Name": "Name", 49 | "Aliases": null 50 | }, 51 | { 52 | "Name": "Detailed", 53 | "Aliases": null 54 | }, 55 | { 56 | "Name": "DefaultProfile", 57 | "Aliases": [ 58 | "AzureRmContext", 59 | "AzureCredential" 60 | ] 61 | } 62 | ] 63 | }, 64 | { 65 | "Command": "New-AzureRmTag", 66 | "IsAlias": false, 67 | "SourceModule": "AzureRM.Tags", 68 | "Version": "4.0.5", 69 | "Parameters": [ 70 | { 71 | "Name": "Name", 72 | "Aliases": null 73 | }, 74 | { 75 | "Name": "Value", 76 | "Aliases": null 77 | }, 78 | { 79 | "Name": "DefaultProfile", 80 | "Aliases": [ 81 | "AzureRmContext", 82 | "AzureCredential" 83 | ] 84 | } 85 | ] 86 | } 87 | ] 88 | -------------------------------------------------------------------------------- /powershell-module/Az.Tools.Migration/Resources/ModuleSpecs/AzureRM/6.13.1/AzureRM.UsageAggregates.4.0.5.Cmdlets.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "Command": "Get-UsageAggregates", 4 | "IsAlias": false, 5 | "SourceModule": "AzureRM.UsageAggregates", 6 | "Version": "4.0.5", 7 | "Parameters": [ 8 | { 9 | "Name": "ReportedStartTime", 10 | "Aliases": null 11 | }, 12 | { 13 | "Name": "ReportedEndTime", 14 | "Aliases": null 15 | }, 16 | { 17 | "Name": "AggregationGranularity", 18 | "Aliases": null 19 | }, 20 | { 21 | "Name": "ShowDetails", 22 | "Aliases": null 23 | }, 24 | { 25 | "Name": "ContinuationToken", 26 | "Aliases": null 27 | }, 28 | { 29 | "Name": "DefaultProfile", 30 | "Aliases": [ 31 | "AzureRmContext", 32 | "AzureCredential" 33 | ] 34 | } 35 | ] 36 | } 37 | ] -------------------------------------------------------------------------------- /powershell-module/Az.Tools.Migration/Resources/TestFiles/FunctionExample-MultipleCommands.ps1: -------------------------------------------------------------------------------- 1 | function Invoke-MyCmdlet 2 | { 3 | <# 4 | .SYNOPSIS 5 | Invokes my test cmdlet. 6 | 7 | .DESCRIPTION 8 | Invokes my test cmdlet. 9 | 10 | .EXAMPLE 11 | PS C:\> Invoke-MyCmdlet 12 | Runs the test cmdlet. 13 | #> 14 | [CmdletBinding()] 15 | Param 16 | ( 17 | [Parameter( 18 | Mandatory=$true, 19 | HelpMessage="Specify the target name.")] 20 | [System.String] 21 | $TargetName 22 | ) 23 | Process 24 | { 25 | Test-Connection -TargetName $TargetName -IPv4 -Count 5 26 | 27 | try 28 | { 29 | Get-ChildItem -Path "C:\users\user" 30 | } 31 | catch 32 | { 33 | throw "Error!" 34 | } 35 | 36 | Get-Help *content* 37 | } 38 | } -------------------------------------------------------------------------------- /powershell-module/Az.Tools.Migration/Resources/TestFiles/FunctionExample-OneCommand.ps1: -------------------------------------------------------------------------------- 1 | function Invoke-MyCmdlet 2 | { 3 | <# 4 | .SYNOPSIS 5 | Invokes my test cmdlet. 6 | 7 | .DESCRIPTION 8 | Invokes my test cmdlet. 9 | 10 | .EXAMPLE 11 | PS C:\> Invoke-MyCmdlet 12 | Runs the test cmdlet. 13 | #> 14 | [CmdletBinding()] 15 | Param 16 | ( 17 | [Parameter( 18 | Mandatory=$true, 19 | HelpMessage="Specify the target name.")] 20 | [System.String] 21 | $TargetName 22 | ) 23 | Process 24 | { 25 | Test-Connection -TargetName $TargetName -IPv4 -Count 5 26 | } 27 | } -------------------------------------------------------------------------------- /powershell-module/Az.Tools.Migration/Resources/TestFiles/FunctionExample-SubExpressionLineContinuation.ps1: -------------------------------------------------------------------------------- 1 | function Invoke-MyCmdlet 2 | { 3 | <# 4 | .SYNOPSIS 5 | Invokes my test cmdlet. 6 | 7 | .DESCRIPTION 8 | Invokes my test cmdlet. 9 | 10 | .EXAMPLE 11 | PS C:\> Invoke-MyCmdlet 12 | Runs the test cmdlet. 13 | #> 14 | [CmdletBinding()] 15 | Param 16 | ( 17 | [Parameter( 18 | Mandatory=$true, 19 | HelpMessage="Specify the target name.")] 20 | [System.String] 21 | $TargetName 22 | ) 23 | Process 24 | { 25 | try 26 | { 27 | Test-Connection -TargetName $TargetName ` 28 | -IPv4 ` 29 | -Count (Get-RequestCount -Test "Value") ` 30 | -OriginalCommandParam "Value2" 31 | } 32 | catch 33 | { 34 | throw "Error!" 35 | } 36 | } 37 | } -------------------------------------------------------------------------------- /powershell-module/Az.Tools.Migration/Resources/TestFiles/ScriptExample-LineContinuation.ps1: -------------------------------------------------------------------------------- 1 | Test-Connection -TargetName $TargetName ` 2 | -IPv4 ` 3 | -Count 5 -------------------------------------------------------------------------------- /powershell-module/Az.Tools.Migration/Resources/TestFiles/ScriptExample-MultipleCommands.ps1: -------------------------------------------------------------------------------- 1 | Test-Connection -TargetName $TargetName -IPv4 -Count 5 2 | 3 | Get-ChildItem -Path "C:\users\user" 4 | 5 | Get-Help *content* -------------------------------------------------------------------------------- /powershell-module/Az.Tools.Migration/Resources/TestFiles/ScriptExample-OneCommand.ps1: -------------------------------------------------------------------------------- 1 | Test-Connection -TargetName $TargetName -IPv4 -Count 5 -------------------------------------------------------------------------------- /powershell-module/Az.Tools.Migration/Resources/TestFiles/ScriptExample-ParameterSplatting1.ps1: -------------------------------------------------------------------------------- 1 | # example 1: hashtable splatted arguments (supported) 2 | $splattedParams = @{ 3 | TargetName = $TargetName 4 | Count = 5 5 | IPv4 = $true 6 | } 7 | Test-Connection @splattedParams -Delay 3 -------------------------------------------------------------------------------- /powershell-module/Az.Tools.Migration/Resources/TestFiles/ScriptExample-ParameterSplatting2.ps1: -------------------------------------------------------------------------------- 1 | # example 2: hashtable splatted arguments with quote characters around key names (supported) 2 | $splattedParams = @{ 3 | "TargetName" = $TargetName 4 | "Count" = 5 5 | 'IPv4' = $true 6 | } 7 | Test-Connection @splattedParams -Delay 3 -------------------------------------------------------------------------------- /powershell-module/Az.Tools.Migration/Resources/TestFiles/ScriptExample-ParameterSplatting3.ps1: -------------------------------------------------------------------------------- 1 | # example 3: hashtable splatted arguments with variable expressions in keynames (not supported, but should not break parser) 2 | $keyName1 = "TargetName" 3 | $keyName2 = "Count" 4 | $keyName3 = "IPv4" 5 | $splattedParams = @{ 6 | "$keyName1" = $TargetName 7 | "$($keyName2)" = 5 8 | $keyName3 = $true 9 | } 10 | Test-Connection @splattedParams -Delay 3 -------------------------------------------------------------------------------- /powershell-module/Az.Tools.Migration/Resources/TestFiles/ScriptExample-ParameterSplatting4.ps1: -------------------------------------------------------------------------------- 1 | # example 4: array splatted arguments (not supported, but should not break parser) 2 | $ArraySplattedArguments = "test.txt", "test2.txt" 3 | Copy-Item @ArraySplattedArguments -WhatIf -------------------------------------------------------------------------------- /powershell-module/Az.Tools.Migration/Resources/TestFiles/ScriptExample-ParameterSplatting5.ps1: -------------------------------------------------------------------------------- 1 | # example 5: hashtable splatted arguments are used, but not defined in the file. 2 | # they would be from another scope, so this scenario is also not supported. 3 | 4 | Test-Connection @splattedParams -Delay 3 -------------------------------------------------------------------------------- /powershell-module/Az.Tools.Migration/Resources/TestFiles/ScriptExample-ParameterSplatting6.ps1: -------------------------------------------------------------------------------- 1 | # example 6: hashtable splatted arguments with an ordered hashtable (supported) 2 | $splattedParams = [ordered]@{ 3 | TargetName = $TargetName 4 | Count = 5 5 | IPv4 = $true 6 | } 7 | Test-Connection @splattedParams -Delay 3 -------------------------------------------------------------------------------- /powershell-module/Az.Tools.Migration/Resources/TestFiles/ScriptExample-ParameterSplatting7.ps1: -------------------------------------------------------------------------------- 1 | # example 7: tests for GitHub issue #73 2 | # assigning a hashtable to an object property (member) shouldn't break the splatted parameter detection. 3 | 4 | $testObject.Property1 = @{ key1 = $value1 } 5 | 6 | if ($true) { 7 | $testObject.Property2 += @{ key2 = $value2 } 8 | } 9 | 10 | Test-Connection -TargetName $TargetName -IPv4 -Count 5 -------------------------------------------------------------------------------- /powershell-module/Az.Tools.Migration/Resources/TestFiles/ScriptExample-ParameterSplatting8.ps1: -------------------------------------------------------------------------------- 1 | # example 8: tests for GitHub issue #73 2 | # assigning a nested hashtable to an object property (member) shouldn't break the splatted parameter detection. 3 | 4 | if ($true) { 5 | $testObject.Property1 = @{ 6 | NestedTable = @{ 7 | NestedProperty = $true 8 | } 9 | } 10 | } 11 | 12 | Test-Connection -TargetName $TargetName -IPv4 -Count 5 -------------------------------------------------------------------------------- /powershell-module/Az.Tools.Migration/Resources/TestFiles/ScriptExample-SubExpressionCommand.ps1: -------------------------------------------------------------------------------- 1 | Test-Connection -TargetName $TargetName -IPv4 -Count (Get-RequestCount -Test "Value") -------------------------------------------------------------------------------- /powershell-module/Az.Tools.Migration/Resources/TestFiles/ScriptExample-SubExpressionCommandAfterParams.ps1: -------------------------------------------------------------------------------- 1 | Test-Connection -TargetName $TargetName -IPv4 -Count (Get-RequestCount -Test "Value") -OriginalCommandParam "Value2" -------------------------------------------------------------------------------- /powershell-module/Az.Tools.Migration/Resources/TestFiles/ScriptExample-SubExpressionLineContinuation.ps1: -------------------------------------------------------------------------------- 1 | Test-Connection -TargetName $TargetName ` 2 | -IPv4 ` 3 | -Count (Get-RequestCount -Test "Value") ` 4 | -OriginalCommandParam "Value2" -------------------------------------------------------------------------------- /powershell-module/Az.Tools.Migration/Tests/Functions/Private/Confirm-StringBuilderSubstring.tests.ps1: -------------------------------------------------------------------------------- 1 | Import-Module Az.Tools.Migration -Force 2 | 3 | InModuleScope -ModuleName Az.Tools.Migration -ScriptBlock { 4 | Describe 'Confirm-StringBuilderSubstring tests' { 5 | It 'Should not throw if the offset matches' { 6 | # arrange 7 | $scriptBuilder = New-Object -TypeName System.Text.StringBuilder 8 | $null = $scriptBuilder.AppendLine("Write-host 'test'") 9 | $null = $scriptBuilder.AppendLine("Set-AzureRmWebApp -ResourceGroupName 'Default-Web-WestUS' ``") 10 | $null = $scriptBuilder.AppendLine(" -Name 'ContosoWebApp' ``") 11 | $null = $scriptBuilder.AppendLine(" -HttpLoggingEnabled `$true") 12 | 13 | # act / assert 14 | { Confirm-StringBuilderSubstring -FileContent $scriptBuilder -Substring 'Set-AzureRmWebApp' -StartOffset 19 -EndOffset 35 } | Should Not Throw 15 | } 16 | It 'Should throw if the offset does not match' { 17 | # arrange 18 | $scriptBuilder = New-Object -TypeName System.Text.StringBuilder 19 | $null = $scriptBuilder.AppendLine("Write-host 'test'") 20 | $null = $scriptBuilder.AppendLine("Set-AzWebApp -ResourceGroupName 'Default-Web-WestUS' ``") # does not match, because it has already been upgraded. 21 | $null = $scriptBuilder.AppendLine(" -Name 'ContosoWebApp' ``") 22 | $null = $scriptBuilder.AppendLine(" -HttpLoggingEnabled `$true") 23 | 24 | # act / assert 25 | { Confirm-StringBuilderSubstring -FileContent $scriptBuilder -Substring 'Set-AzureRmWebApp' -StartOffset 19 -EndOffset 35 } | Should Throw "Upgrade step failed: Offset positions are unexpected" 26 | } 27 | It 'Should throw if the offset extends past the file contents length' { 28 | # arrange 29 | $scriptBuilder = New-Object -TypeName System.Text.StringBuilder 30 | $null = $scriptBuilder.AppendLine("Write-host 'test'") 31 | $null = $scriptBuilder.AppendLine("Set-AzWebApp -ResourceGroupName 'Default-Web-WestUS' ``") 32 | $null = $scriptBuilder.AppendLine(" -Name 'ContosoWebApp' ``") 33 | $null = $scriptBuilder.AppendLine(" -HttpLoggingEnabled `$true") 34 | 35 | # act / assert 36 | { Confirm-StringBuilderSubstring -FileContent $scriptBuilder -Substring 'Set-AzureRmWebApp' -StartOffset 1119 -EndOffset 1135 } | Should Throw "Upgrade step failed: Offset positions are beyond" 37 | } 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /powershell-module/Az.Tools.Migration/Tests/Functions/Private/Get-ModulePreferences.tests.ps1: -------------------------------------------------------------------------------- 1 | Import-Module Az.Tools.Migration -Force 2 | 3 | InModuleScope -ModuleName Az.Tools.Migration -ScriptBlock { 4 | Describe 'Get-ModulePreferences tests' { 5 | It 'Should be able to generate a new module preferences object' { 6 | # arrange 7 | # mock that the file doesn't exist 8 | Mock -CommandName Test-Path -Verifiable -MockWith { return $false } 9 | 10 | # mock that the folder creation worked 11 | Mock -CommandName New-Item -Verifiable -MockWith { } 12 | 13 | # mock that the config file save worked 14 | Mock -CommandName Out-File -Verifiable -MockWith { } 15 | 16 | # act 17 | $result = Get-ModulePreferences 18 | 19 | # assert 20 | $result | Should Not Be $null 21 | $result.GetType().FullName | Should Be 'ModulePreferences' 22 | $result.DataCollectionEnabled | Should Be $true 23 | Assert-VerifiableMock 24 | } 25 | It 'Should be able to return an existing module preferences object with data collection enabled' { 26 | # arrange 27 | # mock that the file does exist 28 | Mock -CommandName Test-Path -Verifiable -MockWith { return $true } 29 | 30 | # mock the file contents 31 | Mock -CommandName Get-Content -Verifiable -MockWith { return '{ "DataCollectionEnabled": true }' } 32 | 33 | # act 34 | $result = Get-ModulePreferences 35 | 36 | # assert 37 | $result | Should Not Be $null 38 | $result.GetType().FullName | Should Be 'ModulePreferences' 39 | $result.DataCollectionEnabled | Should Be $true 40 | Assert-VerifiableMock 41 | } 42 | It 'Should be able to return an existing module preferences object with data collection disabled' { 43 | # arrange 44 | # mock that the file does exist 45 | Mock -CommandName Test-Path -Verifiable -MockWith { return $true } 46 | 47 | # mock the file contents 48 | Mock -CommandName Get-Content -Verifiable -MockWith { return '{ "DataCollectionEnabled": false }' } 49 | 50 | # act 51 | $result = Get-ModulePreferences 52 | 53 | # assert 54 | $result | Should Not Be $null 55 | $result.GetType().FullName | Should Be 'ModulePreferences' 56 | $result.DataCollectionEnabled | Should Be $false 57 | Assert-VerifiableMock 58 | } 59 | It 'Should still return module preferences in case of error' { 60 | # arrange 61 | # mock that the file does exist 62 | Mock -CommandName Test-Path -Verifiable -MockWith { return $true } 63 | 64 | # mock an I/O error from get-content 65 | Mock -CommandName Get-Content -Verifiable -MockWith { throw 'FileNotFound' } 66 | 67 | # act 68 | $result = Get-ModulePreferences 69 | 70 | # assert 71 | $result | Should Not Be $null 72 | $result.GetType().FullName | Should Be 'ModulePreferences' 73 | $result.DataCollectionEnabled | Should Be $false 74 | Assert-VerifiableMock 75 | } 76 | } 77 | } 78 | -------------------------------------------------------------------------------- /powershell-module/Az.Tools.Migration/Tests/Functions/Private/New-ModifiedFileName.tests.ps1: -------------------------------------------------------------------------------- 1 | Import-Module Az.Tools.Migration -Force 2 | 3 | InModuleScope -ModuleName Az.Tools.Migration -ScriptBlock { 4 | Describe 'New-ModifiedFileName tests' { 5 | It 'Can correctly provide a new name for .ps1 files' { 6 | # arrange / act 7 | # act 8 | $result = New-ModifiedFileName -Path 'C:\scripts\test.ps1' 9 | 10 | # assert 11 | $result | Should Be 'C:\scripts\test_az_upgraded.ps1' 12 | } 13 | It 'Can correctly provide a new name for .psm1 files' { 14 | # arrange / act 15 | # act 16 | $result = New-ModifiedFileName -Path 'C:\scripts\test-two-module.psm1' 17 | 18 | # assert 19 | $result | Should Be 'C:\scripts\test-two-module_az_upgraded.psm1' 20 | } 21 | It 'Can correctly provide a new name for extensionless files' { 22 | # arrange / act 23 | # act 24 | $result = New-ModifiedFileName -Path 'C:\scripts\test-two-extensionless' 25 | 26 | # assert 27 | $result | Should Be 'C:\scripts\test-two-extensionless_az_upgraded' 28 | } 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /powershell-module/Az.Tools.Migration/Tests/Functions/Private/Send-MetricsIfDataCollectionEnabled.tests.ps1: -------------------------------------------------------------------------------- 1 | Import-Module Az.Tools.Migration -Force 2 | 3 | InModuleScope -ModuleName Az.Tools.Migration -ScriptBlock { 4 | Describe 'Send-MetricsIfDataCollectionEnabled tests' { 5 | It 'Should not send telemetry if data collection is disabled' { 6 | # arrange 7 | Mock -CommandName Get-ModulePreferences ` 8 | -ModuleName Az.Tools.Migration ` 9 | -Verifiable ` 10 | -MockWith { return [PsCustomObject]@{ DataCollectionEnabled = $false } } 11 | 12 | Mock -CommandName Send-PageViewTelemetry ` 13 | -ModuleName Az.Tools.Migration ` 14 | -Verifiable ` 15 | -MockWith { } 16 | 17 | $metricProps = [PSCustomObject]@{ 18 | AzureCmdletCount = 24 19 | AzureModuleName = "AzureRM" 20 | AzureModuleVersion = "6.13.1" 21 | FileCount = 7 22 | } 23 | 24 | $duration = [System.Timespan]::FromSeconds(1) 25 | 26 | # act 27 | Send-MetricsIfDataCollectionEnabled -Operation 'Find' -ParameterSetName 'TestParamSet' -Duration $duration -Properties $metricProps 28 | 29 | # assert 30 | Assert-MockCalled Send-PageViewTelemetry -Times 0 31 | Assert-MockCalled Get-ModulePreferences -Times 1 32 | } 33 | It 'Should send telemetry if data collection is enabled' { 34 | # arrange 35 | 36 | Mock -CommandName Get-ModulePreferences ` 37 | -ModuleName Az.Tools.Migration ` 38 | -Verifiable ` 39 | -MockWith { return [PsCustomObject]@{ DataCollectionEnabled = $true } } 40 | 41 | Mock -CommandName Send-PageViewTelemetry ` 42 | -ModuleName Az.Tools.Migration ` 43 | -Verifiable ` 44 | -MockWith { } 45 | 46 | $metricProps = [PSCustomObject]@{ 47 | AzureCmdletCount = 24 48 | AzureModuleName = "AzureRM" 49 | AzureModuleVersion = "6.13.1" 50 | FileCount = 7 51 | } 52 | 53 | $duration = [System.Timespan]::FromSeconds(1) 54 | 55 | # act 56 | Send-MetricsIfDataCollectionEnabled -Operation 'Find' -ParameterSetName 'TestParamSet' -Duration $duration -Properties $metricProps 57 | 58 | # assert 59 | Assert-MockCalled Send-PageViewTelemetry -Times 1 60 | Assert-MockCalled Get-ModulePreferences -Times 1 61 | } 62 | It 'Should not bubble up exceptions to the caller.' { 63 | # arrange 64 | 65 | Mock -CommandName Get-ModulePreferences ` 66 | -ModuleName Az.Tools.Migration ` 67 | -Verifiable ` 68 | -MockWith { return [PsCustomObject]@{ DataCollectionEnabled = $true } } 69 | 70 | Mock -CommandName Send-PageViewTelemetry ` 71 | -ModuleName Az.Tools.Migration ` 72 | -Verifiable ` 73 | -MockWith { throw 'test error' } 74 | 75 | $metricProps = [PSCustomObject]@{ 76 | AzureCmdletCount = 24 77 | AzureModuleName = "AzureRM" 78 | AzureModuleVersion = "6.13.1" 79 | FileCount = 7 80 | } 81 | 82 | $duration = [System.Timespan]::FromSeconds(1) 83 | 84 | # act / assert 85 | { 86 | Send-MetricsIfDataCollectionEnabled -Operation 'Find' -ParameterSetName 'TestParamSet' -Duration $duration -Properties $metricProps 87 | } | Should Not Throw 88 | 89 | Assert-MockCalled Send-PageViewTelemetry -Times 1 90 | Assert-MockCalled Get-ModulePreferences -Times 1 91 | } 92 | } 93 | } 94 | -------------------------------------------------------------------------------- /powershell-module/Az.Tools.Migration/Tests/Functions/Private/Set-ModulePreference.tests.ps1: -------------------------------------------------------------------------------- 1 | Import-Module Az.Tools.Migration -Force 2 | 3 | InModuleScope -ModuleName Az.Tools.Migration -ScriptBlock { 4 | Describe 'Set-ModulePreference tests' { 5 | It 'Can correctly disable data collection preference' { 6 | # arrange 7 | Mock -CommandName Out-File -Verifiable -MockWith { } 8 | Mock -CommandName Get-ModulePreferences ` 9 | -Verifiable ` 10 | -ModuleName Az.Tools.Migration ` 11 | -MockWith ` 12 | { 13 | return ([PSCustomObject]@{ 14 | DataCollectionEnabled = $true 15 | }) 16 | } 17 | 18 | # act 19 | $result = Set-ModulePreference -DataCollectionEnabled $false 20 | 21 | # assert 22 | $result | Should Not Be $null 23 | $result.DataCollectionEnabled | Should Be $false 24 | } 25 | It 'Can correctly enable data collection preference' { 26 | # arrange 27 | Mock -CommandName Out-File -Verifiable -MockWith { } 28 | Mock -CommandName Get-ModulePreferences ` 29 | -Verifiable ` 30 | -ModuleName Az.Tools.Migration ` 31 | -MockWith ` 32 | { 33 | return ([PSCustomObject]@{ 34 | DataCollectionEnabled = $false 35 | }) 36 | } 37 | 38 | # act 39 | $result = Set-ModulePreference -DataCollectionEnabled $true 40 | 41 | # assert 42 | $result | Should Not Be $null 43 | $result.DataCollectionEnabled | Should Be $true 44 | } 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /powershell-module/Az.Tools.Migration/Tests/Functions/Public/Disable-AzUpgradeDataCollection.tests.ps1: -------------------------------------------------------------------------------- 1 | Import-Module Az.Tools.Migration -Force 2 | 3 | InModuleScope -ModuleName Az.Tools.Migration -ScriptBlock { 4 | Describe 'Disable-AzUpgradeDataCollection tests' { 5 | It 'Should be able to set the data collection setting correctly' { 6 | # arrange 7 | Mock -CommandName Set-ModulePreference ` 8 | -Verifiable ` 9 | -MockWith { } ` 10 | -ParameterFilter { $DataCollectionEnabled -eq $false } 11 | 12 | # act 13 | Disable-AzUpgradeDataCollection 14 | 15 | # assert 16 | Assert-MockCalled Set-ModulePreference -Times 1 -ParameterFilter { $DataCollectionEnabled -eq $false } 17 | } 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /powershell-module/Az.Tools.Migration/Tests/Functions/Public/Enable-AzUpgradeDataCollection.tests.ps1: -------------------------------------------------------------------------------- 1 | Import-Module Az.Tools.Migration -Force 2 | 3 | InModuleScope -ModuleName Az.Tools.Migration -ScriptBlock { 4 | Describe 'Enable-AzUpgradeDataCollection tests' { 5 | It 'Should be able to set the data collection setting correctly' { 6 | # arrange 7 | Mock -CommandName Set-ModulePreference ` 8 | -Verifiable ` 9 | -MockWith { } ` 10 | -ParameterFilter { $DataCollectionEnabled -eq $true } 11 | 12 | # act 13 | Enable-AzUpgradeDataCollection 14 | 15 | # assert 16 | Assert-MockCalled Set-ModulePreference -Times 1 -ParameterFilter { $DataCollectionEnabled -eq $true } 17 | } 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /powershell-module/Az.Tools.Migration/Tests/Functions/Public/Get-AzUpgradeAliasSpec.tests.ps1: -------------------------------------------------------------------------------- 1 | Import-Module Az.Tools.Migration -Force 2 | 3 | InModuleScope -ModuleName Az.Tools.Migration -ScriptBlock { 4 | Describe 'Get-AzUpgradeAliasSpec tests' { 5 | It 'Should be able to import the Az alias mapping spec' { 6 | # arrange/act 7 | $expectedAliasCount = 2626 8 | $spec = Get-AzUpgradeAliasSpec -ModuleVersion latest 9 | 10 | # assert 11 | $spec | Should Not Be $null 12 | $spec.Count | Should Be $expectedAliasCount 13 | } 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /powershell-module/Az.Tools.Migration/Tests/Functions/Public/Get-AzUpgradeCmdletSpec.tests.ps1: -------------------------------------------------------------------------------- 1 | Import-Module Az.Tools.Migration -Force 2 | 3 | InModuleScope -ModuleName Az.Tools.Migration -ScriptBlock { 4 | Describe 'Get-AzUpgradeCmdletSpec tests' { 5 | It 'Should be able to import the AzureRM 6.13.1 spec' { 6 | # arrange/act 7 | $expectedCommandCount = 2346 8 | $spec = Get-AzUpgradeCmdletSpec -AzureRM 9 | 10 | # assert 11 | $spec | Should Not Be $null 12 | $spec.Count | Should Be $expectedCommandCount 13 | } 14 | It 'Should be able to import the Az spec' { 15 | # arrange/act 16 | $expectedCommandCount = 5645 17 | $spec = Get-AzUpgradeCmdletSpec -Az -ModuleVersion latest 18 | 19 | # assert 20 | $spec | Should Not Be $null 21 | $spec.Count | Should Be $expectedCommandCount 22 | } 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /powershell-module/Az.Tools.Migration/Tests/Functions/Public/Invoke-SamplesTesting.tests.ps1: -------------------------------------------------------------------------------- 1 | Import-Module Az.Tools.Migration -Force 2 | 3 | InModuleScope -ModuleName Az.Tools.Migration -ScriptBlock { 4 | Describe 'Invoke-SamplesTesting tests' { 5 | $TestFileDirectory = Resolve-Path -Path "..\..\common\code-upgrade-samples\" 6 | 7 | # ensure we don't send telemetry during tests. 8 | Mock -CommandName Send-MetricsIfDataCollectionEnabled -ModuleName Az.Tools.Migration -MockWith { } 9 | 10 | foreach ($TestFile in (Get-ChildITem (Join-Path $TestFileDirectory "azurerm") )) { 11 | Copy-Item -Path $TestFile.FullName -Destination "TestDrive:\$($TestFile.name)" 12 | Write-Debug "File being tested = $($TestFile.Name)" 13 | 14 | It "Can perform upgrade of $($TestFile.Name)" { 15 | $AzureRMFilePath = Join-Path -Path $TestDrive -ChildPath $TestFile.Name 16 | $AzFilePath = Join-Path -Path $TestFileDirectory -ChildPath "az\$($TestFile.Name)" 17 | 18 | $Plan = New-AzUpgradeModulePlan -FromAzureRmVersion 6.13.1 -ToAzVersion latest -FilePath $AzureRMFilePath 19 | Invoke-AzUpgradeModulePlan -Plan $Plan -FileEditMode ModifyExistingFiles -Confirm:$false 20 | 21 | # act 22 | $Results = Get-Content -Path $AzureRMFilePath 23 | Write-Debug "Converted file content `n $Results `n" 24 | $ExpectedResults = Get-Content -Path $AzFilePath 25 | Write-Debug "Expected results `n $ExpectedResults `n" 26 | $Delta = Compare-Object $Results $ExpectedResults 27 | 28 | # assertions 29 | $Results | Should Not Be $null 30 | $Delta | Should Be $null 31 | } 32 | } 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /powershell-module/ChangeLog.md: -------------------------------------------------------------------------------- 1 | 20 | ## Upcoming Release 21 | ## 11.0.2 22 | * Added Support for AzureRm version 6.13.2 [#132] 23 | 24 | ## 11.0.1 25 | * Fixed bug DataFactory cmdlet name cannot be recognized [#117] 26 | 27 | ## 11.0.0 28 | * Supported AzureRM to Az 11.0.0 migration. Now the major version of Az.Tools.Migration is aligned with the targeted Az version. 29 | * Fixed bug when using `Find-AzUpgradeCommandReference -DirectoryPath` [#121] 30 | 31 | ## 2.0.0 32 | * Supported AzureRM to Az 10.3 migration 33 | * `Get-AzUpgradeAliasSpec` 34 | * Parameter `ModuleVersion` now accept value 'latest' only [BreakingChange] 35 | * `Get-AzUpgradeCmdletSpec` 36 | * Parameter `ModuleName` removed` [BreakingChange] 37 | * Added switch parameters `AzureRM` and `Az` 38 | * Parameter `ModuleVersion` now accept value 'latest' only and has to be used with `Az` [BreakingChange] 39 | * `New-AzUpgradeModulePlan` 40 | * Parameter `ToAzVersion` now accept value 'latest' only [BreakingChange] 41 | * Parameter `FilePath` now accept relative file path 42 | 43 | ## 1.1.4 44 | * Upgraded Az Version to 9.3.0 45 | 46 | ## 1.1.3 47 | * Upgrade Az version to 8.0.0 48 | 49 | ## 1.1.2 50 | * Upgrade Az version to 6.1.0 51 | 52 | ## 1.1.1 53 | * Fixed a bug in Invoke-AzUpgradeModulePlan where dynamic parameters are incorrectly updated (issue #81). 54 | 55 | ## 1.1.0 56 | * Upgrade Az version to 5.6.0 57 | * Fixed a bug where New-AzUpgradeModulePlan throws errors when analyzing hashtable code (issue #73). 58 | * Updated scanning results for Az cmdlets that implement dynamic parameters to use clearer warnings. 59 | * Updated Get-AzUpgradeCmdletSpec to improve performance. 60 | * Updated quickstart guide to remove outdated guidance on splatted parameter detection. 61 | 62 | ## 1.0.0 63 | * General availability of 'Az.Tools.Migration' module 64 | * Upgraded Az version to 5.2 65 | 66 | ## 0.1.0 67 | * The first preview release 68 | -------------------------------------------------------------------------------- /powershell-module/PSScriptAnalyzerSettings.psd1: -------------------------------------------------------------------------------- 1 | @{ 2 | # Use Severity when you want to limit the generated diagnostic records to a 3 | # subset of: Error, Warning and Information. 4 | # Uncomment the following line if you only want Errors and Warnings but 5 | # not Information diagnostic records. 6 | Severity = @('Error', 'Warning') 7 | 8 | # Use IncludeRules when you want to run only a subset of the default rule set. 9 | #IncludeRules = @('PSAvoidDefaultValueSwitchParameter', 10 | # 'PSMissingModuleManifestField', 11 | # 'PSReservedCmdletChar', 12 | # 'PSReservedParams', 13 | # 'PSShouldProcess', 14 | # 'PSUseApprovedVerbs', 15 | # 'PSUseDeclaredVarsMoreThanAssigments') 16 | 17 | # Use ExcludeRules when you want to run most of the default set of rules except 18 | # for a few rules you wish to "exclude". Note: if a rule is in both IncludeRules 19 | # and ExcludeRules, the rule will be excluded. 20 | ExcludeRules = @('PSPossibleIncorrectComparisonWithNull', 'PSUseSingularNouns', 'PSUseShouldProcessForStateChangingFunctions') 21 | 22 | # You can use the following entry to supply parameters to rules that take parameters. 23 | # For instance, the PSAvoidUsingCmdletAliases rule takes a whitelist for aliases you 24 | # want to allow. 25 | Rules = @{ 26 | PSPlaceOpenBrace = @{ 27 | Enable = $true 28 | OnSameLine = $false 29 | NewLineAfter = $true 30 | IgnoreOneLineBlock = $true 31 | } 32 | PSPlaceCloseBrace = @{ 33 | Enable = $true 34 | NoEmptyLineBefore = $true 35 | IgnoreOneLineBlock = $true 36 | NewLineAfter = $true 37 | } 38 | PSUseConsistentWhitespace = @{ 39 | Enable = $true 40 | CheckInnerBrace = $false 41 | CheckOpenBrace = $false 42 | CheckOpenParen = $true 43 | CheckOperator = $false 44 | CheckPipe = $true 45 | CheckPipeForRedundantWhitespace = $false 46 | CheckSeparator = $true 47 | CheckParameter = $false 48 | } 49 | PSUseConsistentIndentation = @{ 50 | Enable = $true 51 | IndentationSize = 4 52 | PipelineIndentation = 'IncreaseIndentationForFirstPipeline' 53 | Kind = 'space' 54 | } 55 | } 56 | } -------------------------------------------------------------------------------- /powershell-module/README.md: -------------------------------------------------------------------------------- 1 | # Az.Tools.Migration 2 | 3 | Az.Tools.Migration is a PowerShell module for automatically upgrading your PowerShell scripts and 4 | script modules from AzureRM to the Az PowerShell module. 5 | 6 | The major version of Az.Tools.Migration is aligned with the targeted Az Version. For example, if you would like to migrate to `Az 11.0.0`, you should use `Az.Tools.Migration 11.x.x`. 7 | 8 | ## Contents 9 | 10 | * [Getting started](#getting-started) 11 | * [Description](#description) 12 | * [Usage Instructions](#usage-instructions) 13 | * [Limitations](#limitations) 14 | 15 | ## Description 16 | 17 | The Az.Tools.Migration PowerShell module contains cmdlets that perform the following actions: 18 | 19 | 1. Detect AzureRM cmdlet references in PowerShell scripts and script modules. 20 | 1. Generate an upgrade plan to convert AzureRM module references to Az module commands. 21 | 1. Execute the upgrade plan to modify your PowerShell codebase. 22 | 23 | ## Getting started 24 | 25 | You can use either method to use this module: 26 | 27 | 1. Install this module from the [PowerShell gallery](https://www.powershellgallery.com/packages/Az.Tools.Migration). 28 | 29 | ``` 30 | Install-Module -Name Az.Tools.Migration 31 | ``` 32 | 33 | 2. Clone this repository and import the module locally. 34 | Use this option if you want to make changes to the module and test it out. 35 | 36 | ``` 37 | git clone https://github.com/Azure/azure-powershell-migration.git 38 | import-module './azure-powershell-migration/powershell-module/Az.Tools.Migration/Az.Tools.Migration.psd1' 39 | ``` 40 | 41 | ## Usage Instructions 42 | 43 | ### Requirements 44 | 45 | Update your existing PowerShell codebase to the latest version of the AzureRM PowerShell module. The 46 | Az.Tools.Migration module detects commands based on AzureRM 6.13.1. 47 | 48 | ### Step 1: Backup your code 49 | 50 | **IMPORTANT**: There is no undo operation. Always ensure that you have a backup copy of your PowerShell scripts 51 | and modules that you're attempting to upgrade. 52 | 53 | ### Step 2: Generate an upgrade plan 54 | 55 | Generate an upgrade plan for moving the AzureRM references in your codebase to the Az PowerShell 56 | module. This step doesn't execute the plan, it only generates the upgrade steps. 57 | 58 | **IMPORTANT**: Review the warnings and errors in the plan results. The output may 59 | contain commands or parameters that couldn't be upgraded automatically. These items require manual 60 | intervention during the upgrade. 61 | 62 | This step can optionally be run for a single file by specifying the `FilePath` parameter instead of the 63 | `DirectoryPath` parameter. 64 | 65 | ```powershell 66 | # Generate an upgrade plan for the script and module files in the specified folder and save it to a variable. 67 | $plan = New-AzUpgradeModulePlan -FromAzureRmVersion 6.13.1 -ToAzVersion latest -DirectoryPath 'C:\Scripts' 68 | 69 | # shows the entire upgrade plan 70 | $plan 71 | 72 | # filter plan result to only show warnings and errors 73 | $plan | where PlanResult -ne ReadyToUpgrade | format-list 74 | ``` 75 | 76 | ### Step 3: Execute the upgrade plan 77 | 78 | The upgrade plan is executed when you run the `Invoke-AzUpgradeModulePlan` cmdlet. This command performs 79 | an upgrade of the specified file or folders except for any errors that were identified by the `New-AzUpgradeModulePlan` cmdlet. 80 | 81 | This command requires you to specify if the files should be modified in place or if new files should be saved 82 | alongside your original files (leaving originals unmodified). 83 | 84 | ```powershell 85 | # Execute the automatic upgrade plan and save the results to a variable. 86 | # Specify 'ModifyExistingFiles' to the -FileEditMode parameter if you would like the files to be modified in place instead of having new files created. 87 | $result = Invoke-AzUpgradeModulePlan -Plan $plan -FileEditMode SaveChangesToNewFiles 88 | 89 | # shows the entire upgrade operation result 90 | $result 91 | 92 | # filter results to show errors 93 | $results | where UpgradeResult -ne UpgradeCompleted | format-list 94 | ``` 95 | 96 | ## Limitations 97 | 98 | * File I/O operations use default encoding. Unusual file encoding situations may cause problems. 99 | * AzureRM cmdlets passed as arguments to Pester unit test mock statements aren't detected. 100 | -------------------------------------------------------------------------------- /powershell-module/Scripts/Publish-Module.ps1: -------------------------------------------------------------------------------- 1 | <# 2 | 3 | .SYNOPSIS 4 | Create nuget packages for module. 5 | 6 | .PARAMETER ApiKey 7 | ApiKey used to publish nuget to PS repository. 8 | 9 | .PARAMETER RepositoryLocation 10 | Location we want to publish too. 11 | #> 12 | param( 13 | [Parameter(Mandatory = $true)] 14 | [string]$RepositoryLocation 15 | ) 16 | try { 17 | $tempRepoName = ([System.Guid]::NewGuid()).ToString() 18 | Register-PSRepository -Name $tempRepoName -SourceLocation $RepositoryLocation -PublishLocation $RepositoryLocation -InstallationPolicy Trusted -PackageManagementProvider NuGet 19 | $modulePath = Join-Path $RepositoryLocation Az.Tools.Migration -Resolve 20 | Publish-Module -Path $modulePath -Repository $tempRepoName -Force 21 | } catch { 22 | $Errors = $_ 23 | Write-Error ($_ | Out-String) 24 | } finally { 25 | Unregister-PSRepository -Name $tempRepoName 26 | } 27 | 28 | 29 | -------------------------------------------------------------------------------- /powershell-module/build.proj: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 6 | pwsh -NonInteractive -NoLogo -NoProfile -Command 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | -------------------------------------------------------------------------------- /powershell-module/help/Az.Tools.Migration.md: -------------------------------------------------------------------------------- 1 | --- 2 | Module Name: Az.Tools.Migration 3 | Module Guid: cb471070-37cc-4484-9665-adf1502b4e3a 4 | Download Help Link: https://learn.microsoft.com/powershell/module/az.tools.migration 5 | Help Version: 1.0.1.0 6 | Locale: en-US 7 | --- 8 | 9 | # Az.Tools.Migration Module 10 | ## Description 11 | Commands to help migrate from AzureRM to Az PowerShell modules. 12 | 13 | ## Az.Tools.Migration Cmdlets 14 | ### [Disable-AzUpgradeDataCollection](Disable-AzUpgradeDataCollection.md) 15 | Disables the setting that allows **Az.Tools.Migration** to send usage metrics to Microsoft. 16 | 17 | ### [Enable-AzUpgradeDataCollection](Enable-AzUpgradeDataCollection.md) 18 | Enables the setting that allows** Az.Tools.Migration** to send usage metrics to Microsoft. 19 | 20 | ### [Find-AzUpgradeCommandReference](Find-AzUpgradeCommandReference.md) 21 | Searches for **AzureRM** PowerShell command references in the specified file or folder. 22 | 23 | ### [Get-AzUpgradeAliasSpec](Get-AzUpgradeAliasSpec.md) 24 | Returns a dictionary containing cmdlet alias mappings for the specified **Az** module version. 25 | 26 | ### [Get-AzUpgradeCmdletSpec](Get-AzUpgradeCmdletSpec.md) 27 | Returns a dictionary containing cmdlet specification objects for the specified module. 28 | 29 | ### [Invoke-AzUpgradeModulePlan](Invoke-AzUpgradeModulePlan.md) 30 | Invokes the specified module upgrade plan. 31 | 32 | ### [New-AzUpgradeModulePlan](New-AzUpgradeModulePlan.md) 33 | Generates a new upgrade plan for migrating to the **Az** PowerShell module. 34 | 35 | -------------------------------------------------------------------------------- /powershell-module/help/Disable-AzUpgradeDataCollection.md: -------------------------------------------------------------------------------- 1 | --- 2 | external help file: Az.Tools.Migration-help.xml 3 | Module Name: Az.Tools.Migration 4 | online version: 5 | schema: 2.0.0 6 | --- 7 | 8 | # Disable-AzUpgradeDataCollection 9 | 10 | ## SYNOPSIS 11 | Disables the setting that allows **Az.Tools.Migration** to send usage metrics to Microsoft. 12 | 13 | ## SYNTAX 14 | 15 | ``` 16 | Disable-AzUpgradeDataCollection [] 17 | ``` 18 | 19 | ## DESCRIPTION 20 | 21 | Disables the setting that allows **Az.Tools.Migration** to send usage metrics to Microsoft. Usage 22 | metrics are opted-in by default. To disable usage metrics, run this cmdlet. This setting is scoped 23 | to the user profile and persists between PowerShell sessions. 24 | 25 | ## EXAMPLES 26 | 27 | ### EXAMPLE 1 28 | 29 | Disables the metrics collection for Az.Tools.Migration. 30 | 31 | ```powershell 32 | Disable-AzUpgradeDataCollection 33 | ``` 34 | 35 | ## PARAMETERS 36 | 37 | ### CommonParameters 38 | This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). 39 | 40 | ## INPUTS 41 | 42 | ## OUTPUTS 43 | 44 | ## NOTES 45 | 46 | ## RELATED LINKS 47 | -------------------------------------------------------------------------------- /powershell-module/help/Enable-AzUpgradeDataCollection.md: -------------------------------------------------------------------------------- 1 | --- 2 | external help file: Az.Tools.Migration-help.xml 3 | Module Name: Az.Tools.Migration 4 | online version: 5 | schema: 2.0.0 6 | --- 7 | 8 | # Enable-AzUpgradeDataCollection 9 | 10 | ## SYNOPSIS 11 | Enables the setting that allows** Az.Tools.Migration** to send usage metrics to Microsoft. 12 | 13 | ## SYNTAX 14 | 15 | ``` 16 | Enable-AzUpgradeDataCollection [] 17 | ``` 18 | 19 | ## DESCRIPTION 20 | 21 | Enables the setting that allows **Az.Tools.Migration** to send usage metrics to Microsoft. Usage 22 | metrics are opted-in by default. To disable usage metrics, run the 23 | `Disabled-AzUpgradeDataCollection` cmdlet. This setting is scoped to the user profile and persists 24 | between PowerShell sessions. 25 | 26 | ## EXAMPLES 27 | 28 | ### EXAMPLE 1 29 | 30 | Enables the metrics collection for **Az.Tools.Migration**. 31 | 32 | ```powershell 33 | Enable-AzUpgradeDataCollection 34 | ``` 35 | 36 | ## PARAMETERS 37 | 38 | ### CommonParameters 39 | This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). 40 | 41 | ## INPUTS 42 | 43 | ## OUTPUTS 44 | 45 | ## NOTES 46 | 47 | ## RELATED LINKS 48 | -------------------------------------------------------------------------------- /powershell-module/help/Find-AzUpgradeCommandReference.md: -------------------------------------------------------------------------------- 1 | --- 2 | external help file: Az.Tools.Migration-help.xml 3 | Module Name: Az.Tools.Migration 4 | online version: 5 | schema: 2.0.0 6 | --- 7 | 8 | # Find-AzUpgradeCommandReference 9 | 10 | ## SYNOPSIS 11 | Searches for **AzureRM** PowerShell command references in the specified file or folder. 12 | 13 | ## SYNTAX 14 | 15 | ### ByFileAndModuleSpec 16 | ``` 17 | Find-AzUpgradeCommandReference -FilePath 18 | -AzureRmModuleSpec 19 | [] 20 | ``` 21 | 22 | ### ByFileAndModuleVersion 23 | ``` 24 | Find-AzUpgradeCommandReference -FilePath -AzureRmVersion [] 25 | ``` 26 | 27 | ### ByDirectoryAndModuleSpec 28 | ``` 29 | Find-AzUpgradeCommandReference -DirectoryPath 30 | -AzureRmModuleSpec 31 | [] 32 | ``` 33 | 34 | ### ByDirectoryAndModuleVersion 35 | ``` 36 | Find-AzUpgradeCommandReference -DirectoryPath -AzureRmVersion [] 37 | ``` 38 | 39 | ## DESCRIPTION 40 | 41 | Searches for **AzureRM** PowerShell command references in the specified file or folder. When 42 | reviewing the specified file or folder, all of the cmdlets used in the files will be analyzed and 43 | compared against known **AzureRM** PowerShell commands. If commands match a known **AzureRM** 44 | cmdlet, then output will be returned that shows the position/offset for each usage. 45 | 46 | ## EXAMPLES 47 | 48 | ### EXAMPLE 1 49 | 50 | The following example finds **AzureRM** PowerShell command references in the specified file. 51 | 52 | ```powershell 53 | Find-AzUpgradeCommandReference -FilePath 'C:\Scripts\test.ps1' -AzureRmVersion '6.13.1' 54 | ``` 55 | 56 | ### EXAMPLE 2 57 | 58 | Find-AzUpgradeCommandReference -DirectoryPath 'C:\Scripts' -AzureRmVersion '6.13.1' 59 | 60 | ``` 61 | The following example finds AzureRM PowerShell command references in the specified directory and subfolders. 62 | ``` 63 | 64 | ### EXAMPLE 3 65 | 66 | The following example finds **AzureRM** PowerShell command references in the specified directory and 67 | subfolders but with a pre-loaded module specification. This is helpful to avoid reloading the module 68 | specification if the `Find-AzUpgradeCommandReference` command needs to be executed several times. 69 | 70 | ```powershell 71 | $moduleSpec = Get-AzUpgradeCmdletSpec -AzureRM 72 | Find-AzUpgradeCommandReference -DirectoryPath 'C:\Scripts1' -AzureRmModuleSpec $moduleSpec 73 | Find-AzUpgradeCommandReference -DirectoryPath 'C:\Scripts2' -AzureRmModuleSpec $moduleSpec 74 | Find-AzUpgradeCommandReference -DirectoryPath 'C:\Scripts3' -AzureRmModuleSpec $moduleSpec 75 | ``` 76 | 77 | ## PARAMETERS 78 | 79 | ### -AzureRmModuleSpec 80 | 81 | Specifies a dictionary containing cmdlet specification objects, returned from 82 | `Get-AzUpgradeCmdletSpec`. 83 | 84 | ```yaml 85 | Type: System.Collections.Generic.Dictionary`2[System.String,CommandDefinition] 86 | Parameter Sets: ByFileAndModuleSpec, ByDirectoryAndModuleSpec 87 | Aliases: 88 | 89 | Required: True 90 | Position: Named 91 | Default value: None 92 | Accept pipeline input: False 93 | Accept wildcard characters: False 94 | ``` 95 | 96 | ### -AzureRmVersion 97 | 98 | Specifies the **AzureRM** module version used in your existing PowerShell file(s) or modules. Supported versions include: '6.13.1', '6.13.2' 99 | 100 | ```yaml 101 | Type: System.String 102 | Parameter Sets: ByFileAndModuleVersion, ByDirectoryAndModuleVersion 103 | Aliases: 104 | 105 | Required: True 106 | Position: Named 107 | Default value: None 108 | Accept pipeline input: False 109 | Accept wildcard characters: False 110 | ``` 111 | 112 | ### -DirectoryPath 113 | 114 | Specifies the path to the folder where PowerShell scripts or modules reside. 115 | 116 | ```yaml 117 | Type: System.String 118 | Parameter Sets: ByDirectoryAndModuleSpec, ByDirectoryAndModuleVersion 119 | Aliases: 120 | 121 | Required: True 122 | Position: Named 123 | Default value: None 124 | Accept pipeline input: False 125 | Accept wildcard characters: False 126 | ``` 127 | 128 | ### -FilePath 129 | 130 | Specifies the path to a single PowerShell file. 131 | 132 | ```yaml 133 | Type: System.String 134 | Parameter Sets: ByFileAndModuleSpec, ByFileAndModuleVersion 135 | Aliases: 136 | 137 | Required: True 138 | Position: Named 139 | Default value: None 140 | Accept pipeline input: False 141 | Accept wildcard characters: False 142 | ``` 143 | 144 | ### CommonParameters 145 | This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). 146 | 147 | ## INPUTS 148 | 149 | ## OUTPUTS 150 | 151 | ## NOTES 152 | 153 | ## RELATED LINKS 154 | -------------------------------------------------------------------------------- /powershell-module/help/Get-AzUpgradeAliasSpec.md: -------------------------------------------------------------------------------- 1 | --- 2 | external help file: Az.Tools.Migration-help.xml 3 | Module Name: Az.Tools.Migration 4 | online version: 5 | schema: 2.0.0 6 | --- 7 | 8 | # Get-AzUpgradeAliasSpec 9 | 10 | ## SYNOPSIS 11 | Returns a dictionary containing cmdlet alias mappings for the specified **Az** module version. 12 | 13 | ## SYNTAX 14 | 15 | ``` 16 | Get-AzUpgradeAliasSpec [-ModuleVersion] [] 17 | ``` 18 | 19 | ## DESCRIPTION 20 | 21 | Returns a dictionary containing cmdlet alias mappings for the specified **Az** module version. 22 | 23 | ## EXAMPLES 24 | 25 | ### EXAMPLE 1 26 | 27 | Returns the cmdlet alias mappings table for latest Az version. 28 | 29 | ```powershell 30 | Get-AzUpgradeAliasSpec -ModuleVersion latest 31 | ``` 32 | 33 | ## PARAMETERS 34 | 35 | ### -ModuleVersion 36 | 37 | Specify the version of the module to import command aliases from. 38 | 39 | ```yaml 40 | Type: System.String 41 | Parameter Sets: (All) 42 | Aliases: 43 | 44 | Required: True 45 | Position: 1 46 | Default value: None 47 | Accept pipeline input: False 48 | Accept wildcard characters: False 49 | ``` 50 | 51 | ### CommonParameters 52 | This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). 53 | 54 | ## INPUTS 55 | 56 | ## OUTPUTS 57 | 58 | ## NOTES 59 | 60 | ## RELATED LINKS 61 | -------------------------------------------------------------------------------- /powershell-module/help/Get-AzUpgradeCmdletSpec.md: -------------------------------------------------------------------------------- 1 | --- 2 | external help file: Az.Tools.Migration-help.xml 3 | Module Name: Az.Tools.Migration 4 | online version: 5 | schema: 2.0.0 6 | --- 7 | 8 | # Get-AzUpgradeCmdletSpec 9 | 10 | ## SYNOPSIS 11 | Returns a dictionary containing cmdlet specification objects for the specified module. 12 | 13 | ## SYNTAX 14 | 15 | ### AzureRM 16 | ``` 17 | Get-AzUpgradeCmdletSpec [-AzureRM] [] 18 | ``` 19 | 20 | ### Az 21 | ``` 22 | Get-AzUpgradeCmdletSpec [-Az] -ModuleVersion [] 23 | ``` 24 | 25 | ## DESCRIPTION 26 | 27 | Returns a dictionary containing cmdlet specification objects for the specified module. 28 | 29 | ## EXAMPLES 30 | 31 | ### EXAMPLE 1 32 | 33 | Returns the dictionary containing cmdlet specification objects for **AzureRM** 6.13.1. 34 | 35 | ```powershell 36 | Get-AzUpgradeCmdletSpec -AzureRM 37 | ``` 38 | ### EXAMPLE 2 39 | 40 | Returns the dictionary containing cmdlet specification objects for latest Az major version. 41 | 42 | ```powershell 43 | Get-AzUpgradeCmdletSpec -Az 'latest' 44 | ``` 45 | 46 | ## PARAMETERS 47 | 48 | ### -Az 49 | 50 | Import command definitions from Az modules. 51 | 52 | ```yaml 53 | Type: System.Management.Automation.SwitchParameter 54 | Parameter Sets: Az 55 | Aliases: 56 | 57 | Required: True 58 | Position: Named 59 | Default value: False 60 | Accept pipeline input: False 61 | Accept wildcard characters: False 62 | ``` 63 | 64 | ### -AzureRM 65 | 66 | Import command definitions from **AzureRM** modules. 67 | 68 | ```yaml 69 | Type: System.Management.Automation.SwitchParameter 70 | Parameter Sets: AzureRM 71 | Aliases: 72 | 73 | Required: True 74 | Position: Named 75 | Default value: False 76 | Accept pipeline input: False 77 | Accept wildcard characters: False 78 | ``` 79 | 80 | ### -ModuleVersion 81 | 82 | Specify the version of the module to load command definitions from. 83 | 84 | ```yaml 85 | Type: System.String 86 | Parameter Sets: Az 87 | Aliases: 88 | 89 | Required: True 90 | Position: Named 91 | Default value: None 92 | Accept pipeline input: False 93 | Accept wildcard characters: False 94 | ``` 95 | 96 | ### CommonParameters 97 | This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). 98 | 99 | ## INPUTS 100 | 101 | ## OUTPUTS 102 | 103 | ## NOTES 104 | 105 | ## RELATED LINKS 106 | -------------------------------------------------------------------------------- /vscode-extension/.eslintrc.json: -------------------------------------------------------------------------------- 1 | { 2 | "root": true, 3 | "parser": "@typescript-eslint/parser", 4 | "parserOptions": { 5 | "ecmaVersion": 6, 6 | "sourceType": "module" 7 | }, 8 | "plugins": [ 9 | "@typescript-eslint" 10 | ], 11 | "rules": { 12 | "@typescript-eslint/semi": "warn", 13 | "curly": "warn", 14 | "no-throw-literal": "warn", 15 | "semi": "off" 16 | }, 17 | "extends": [ 18 | "eslint:recommended", 19 | "plugin:@typescript-eslint/recommended" 20 | ] 21 | } -------------------------------------------------------------------------------- /vscode-extension/.gitignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | out -------------------------------------------------------------------------------- /vscode-extension/.vscode/extensions.json: -------------------------------------------------------------------------------- 1 | { 2 | // See http://go.microsoft.com/fwlink/?LinkId=827846 3 | // for the documentation about the extensions.json format 4 | "recommendations": [ 5 | "dbaeumer.vscode-eslint" 6 | ] 7 | } 8 | -------------------------------------------------------------------------------- /vscode-extension/.vscode/launch.json: -------------------------------------------------------------------------------- 1 | // A launch configuration that compiles the extension and then opens it inside a new window 2 | // Use IntelliSense to learn about possible attributes. 3 | // Hover to view descriptions of existing attributes. 4 | // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 5 | { 6 | "version": "0.2.0", 7 | "configurations": [ 8 | { 9 | "name": "Run Extension", 10 | "type": "extensionHost", 11 | "request": "launch", 12 | "runtimeExecutable": "${execPath}", 13 | "args": [ 14 | "--extensionDevelopmentPath=${workspaceFolder}" 15 | ], 16 | "outFiles": [ 17 | "${workspaceFolder}/out/**/*.js" 18 | ], 19 | "preLaunchTask": "${defaultBuildTask}" 20 | }, 21 | { 22 | "name": "Extension Tests", 23 | "type": "extensionHost", 24 | "request": "launch", 25 | "runtimeExecutable": "${execPath}", 26 | "args": [ 27 | "--extensionDevelopmentPath=${workspaceFolder}", 28 | "--extensionTestsPath=${workspaceFolder}/out/test/suite/index" 29 | ], 30 | "outFiles": [ 31 | "${workspaceFolder}/out/test/**/*.js" 32 | ], 33 | "preLaunchTask": "${defaultBuildTask}" 34 | } 35 | ] 36 | } 37 | -------------------------------------------------------------------------------- /vscode-extension/.vscode/settings.json: -------------------------------------------------------------------------------- 1 | // Place your settings in this file to overwrite default and user settings. 2 | { 3 | "files.exclude": { 4 | "out": false // set this to true to hide the "out" folder with the compiled JS files 5 | }, 6 | "search.exclude": { 7 | "out": true // set this to false to include "out" folder in search results 8 | }, 9 | // Turn off tsc task auto detection since we have the necessary tasks as npm scripts 10 | "typescript.tsc.autoDetect": "off" 11 | } -------------------------------------------------------------------------------- /vscode-extension/.vscode/tasks.json: -------------------------------------------------------------------------------- 1 | { 2 | "version": "2.0.0", 3 | "tasks": [ 4 | { 5 | "type": "npm", 6 | "script": "compile", 7 | "group": "build", 8 | "presentation": { 9 | "panel": "dedicated", 10 | "reveal": "never" 11 | }, 12 | "problemMatcher": [ 13 | "$tsc" 14 | ] 15 | }, 16 | { 17 | "type": "npm", 18 | "script": "watch", 19 | "isBackground": true, 20 | "group": { 21 | "kind": "build", 22 | "isDefault": true 23 | }, 24 | "presentation": { 25 | "panel": "dedicated", 26 | "reveal": "never" 27 | }, 28 | "problemMatcher": [ 29 | "$tsc-watch" 30 | ] 31 | } 32 | ] 33 | } -------------------------------------------------------------------------------- /vscode-extension/.vscodeignore: -------------------------------------------------------------------------------- 1 | .vscode/** 2 | .vscode-test/** 3 | out/test/** 4 | src/** 5 | .gitignore 6 | vsc-extension-quickstart.md 7 | **/tsconfig.json 8 | **/.eslintrc.json 9 | **/*.map 10 | **/*.ts 11 | server/** 12 | !server/module/** 13 | resources/** -------------------------------------------------------------------------------- /vscode-extension/CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Azure PowerShell Extension Release History 2 | ## 0.3.0 3 | - Integrated with latest Az.Tools.Migration instead of fixed version 4 | 5 | ## 0.2.0 6 | 7 | Code refactoring and user experience optimization: 8 | - Adjusted product architecture - let extension communicate to Az.Tools.Migration directly 9 | - Displayed the diagnostic with migration information automatically when open a Powershell file 10 | - Made extension more lightweight and use fewer resources 11 | 12 | ## 0.1.0 13 | 14 | First preview release with the following features: 15 | - AzureRM commands highlighting 16 | - Quick Fix for compatible AzureRM cmdlets 17 | -------------------------------------------------------------------------------- /vscode-extension/LICENSE.txt: -------------------------------------------------------------------------------- 1 | Copyright (c) Microsoft Corporation. 2 | 3 | MIT License 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 | -------------------------------------------------------------------------------- /vscode-extension/README.md: -------------------------------------------------------------------------------- 1 | # Azure Powershell Tools 2 | 3 | [![Version](https://img.shields.io/visual-studio-marketplace/v/azps-tools.azps-tools)](https://marketplace.visualstudio.com/items?itemName=azps-tools.azps-tools) 4 | [![Installs](https://img.shields.io/visual-studio-marketplace/i/azps-tools.azps-tools)](https://marketplace.visualstudio.com/items?itemName=azps-tools.azps-tools) 5 | 6 | Effortlessly migrate your PowerShell scripts from AzureRM to the Az PowerShell module. 7 | 8 | ![Azure Powershell Tools overview](resources/readme/overview.gif) 9 | 10 | ## Features 11 | 12 | - AzureRM commands highlighting. 13 | - Quick Fix for some AzureRM commands. 14 | 15 | ## Installing the Extension 16 | 17 | You can install the official release of the Azure PowerShell extension by following the steps 18 | in the [Visual Studio Code documentation](https://code.visualstudio.com/docs/editor/extension-gallery). 19 | In the Extensions pane, search for "Azure PowerShell" extension and install it there. You will 20 | get notified automatically about any future extension updates! 21 | 22 | ## Usage 23 | 24 | PowerShell scripts are analyzed automatically whenever they are opened or saved. AzureRM cmdlets will be identified and marked with suggestions of how to migrate. 25 | 26 | - Quick Fix 27 | ![quick-fix](resources/readme/quick-fix.png) 28 | 29 | ## License 30 | 31 | This extension is [licensed under the MIT License](LICENSE.txt). 32 | -------------------------------------------------------------------------------- /vscode-extension/build.proj: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | -------------------------------------------------------------------------------- /vscode-extension/logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Azure/azure-powershell-migration/55f68b18251e6916545c2feab910e8c1cc404b29/vscode-extension/logo.png -------------------------------------------------------------------------------- /vscode-extension/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "azps-tools", 3 | "displayName": "Azure PowerShell Tools", 4 | "description": "(preview) Automate the migration of Azure PowerShell scripts and modules from AzureRM to the Az PowerShell module.", 5 | "version": "0.3.0", 6 | "publisher": "azps-tools", 7 | "license": "MIT", 8 | "icon": "logo.png", 9 | "preview": true, 10 | "repository": { 11 | "type": "git", 12 | "url": "https://github.com/Azure/azure-powershell-migration.git" 13 | }, 14 | "engines": { 15 | "vscode": "^1.47.0" 16 | }, 17 | "categories": [ 18 | "Azure" 19 | ], 20 | "activationEvents": [ 21 | "onLanguage:powershell" 22 | ], 23 | "main": "./out/extension.js", 24 | "contributes": {}, 25 | "scripts": { 26 | "vscode:prepublish": "npm run compile", 27 | "compile": "tsc -p ./", 28 | "watch": "tsc -watch -p ./", 29 | "pretest": "npm run compile && npm run lint", 30 | "lint": "eslint src --ext ts", 31 | "test": "node ./out/test/runTest.js" 32 | }, 33 | "dependencies": { 34 | "node-powershell": "^4.0.0" 35 | }, 36 | "devDependencies": { 37 | "@types/vscode": "^1.47.0", 38 | "@types/glob": "^7.1.3", 39 | "@types/mocha": "^8.2.2", 40 | "@types/node": "^13.13.51", 41 | "eslint": "^7.27.0", 42 | "@typescript-eslint/eslint-plugin": "^4.26.0", 43 | "@typescript-eslint/parser": "^4.26.0", 44 | "glob": "^7.1.7", 45 | "mocha": "^8.4.0", 46 | "typescript": "^4.3.2", 47 | "vscode-test": "^1.5.2" 48 | } 49 | } -------------------------------------------------------------------------------- /vscode-extension/resources/readme/command-palette.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Azure/azure-powershell-migration/55f68b18251e6916545c2feab910e8c1cc404b29/vscode-extension/resources/readme/command-palette.png -------------------------------------------------------------------------------- /vscode-extension/resources/readme/overview.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Azure/azure-powershell-migration/55f68b18251e6916545c2feab910e8c1cc404b29/vscode-extension/resources/readme/overview.gif -------------------------------------------------------------------------------- /vscode-extension/resources/readme/quick-fix.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Azure/azure-powershell-migration/55f68b18251e6916545c2feab910e8c1cc404b29/vscode-extension/resources/readme/quick-fix.png -------------------------------------------------------------------------------- /vscode-extension/resources/readme/select-version.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Azure/azure-powershell-migration/55f68b18251e6916545c2feab910e8c1cc404b29/vscode-extension/resources/readme/select-version.png -------------------------------------------------------------------------------- /vscode-extension/src/diagnostic.ts: -------------------------------------------------------------------------------- 1 | /*--------------------------------------------------------- 2 | * Copyright (C) Microsoft Corporation. All rights reserved. 3 | *--------------------------------------------------------*/ 4 | 5 | import * as vscode from 'vscode'; 6 | import { PowershellProcess } from './powershell'; 7 | import { Logger } from "./logging"; 8 | import { UpgradePlan } from "./types/migraion"; 9 | /** 10 | * Updates all the diagnostics items in document. 11 | * @param documentUri : file path 12 | * @param diagcCollection : manage the diagnostics 13 | * @param powershell : powershell process manager 14 | * @param azureRmVersion : version of azureRM 15 | * @param azVersion : version of az 16 | * @param log : Logger 17 | */ 18 | export async function updateDiagnostics( 19 | documentUri: vscode.Uri, 20 | diagcCollection: vscode.DiagnosticCollection, 21 | powershell: PowershellProcess, 22 | azureRmVersion: string, 23 | log: Logger): Promise { 24 | if (documentUri) { 25 | //exec the migration powershell command 26 | let planResult: string; 27 | try { 28 | log.write(`Start analyzing ${documentUri.fsPath}`); 29 | planResult = await powershell.getUpgradePlanToLatest(documentUri.fsPath, azureRmVersion); 30 | log.write(`Node-Powershell Success. -- ${documentUri.fsPath}`); 31 | } 32 | catch (e) { 33 | log.writeError(`Error: Node-Powershell failed.` + e.message); 34 | } 35 | 36 | //update the content of diagnostic 37 | if (planResult) { 38 | const diagnostics: vscode.Diagnostic[] = formatPlanstToDiag(planResult, log); 39 | diagcCollection.set(documentUri, diagnostics); 40 | log.write(`Diagnostics Number : ${diagnostics.length} `); 41 | } 42 | else { 43 | log.write(`This file is not need to be migrated.`); 44 | } 45 | 46 | 47 | } else { 48 | diagcCollection.clear(); 49 | } 50 | 51 | } 52 | 53 | /** 54 | * Format the palnStr to diganostic. 55 | * @param plansStr : The result(string) of migration. 56 | * @param log : Logger 57 | * @returns : diagnostics 58 | */ 59 | function formatPlanstToDiag(plansStr: string, log: Logger): vscode.Diagnostic[] { 60 | let plans: UpgradePlan[]; 61 | try { 62 | plans = JSON.parse(plansStr); 63 | } 64 | catch { 65 | log.writeError("The result of Migration is wrong!"); 66 | return []; 67 | } 68 | 69 | const diagnostics: vscode.Diagnostic[] = []; 70 | plans.forEach( 71 | plan => { 72 | const range = new vscode.Range(new vscode.Position(plan.SourceCommand.StartLine - 1, plan.SourceCommand.StartColumn - 1), 73 | new vscode.Position(plan.SourceCommand.EndLine - 1, plan.SourceCommand.EndPosition - 1)); 74 | const message = plan.PlanResultReason; 75 | const diagnostic = new vscode.Diagnostic(range, message); 76 | if (plan.PlanSeverity == 1) { 77 | diagnostic.severity = vscode.DiagnosticSeverity.Error; 78 | diagnostic.code = "DO_NOTHING"; 79 | diagnostic.source = ''; 80 | } 81 | else if (plan.PlanSeverity == 2) { 82 | diagnostic.severity = vscode.DiagnosticSeverity.Information; 83 | diagnostic.code = "DO_NOTHING"; 84 | diagnostic.source = ''; 85 | } 86 | else { //plan.PlanSeverity == 3 87 | diagnostic.severity = vscode.DiagnosticSeverity.Warning; 88 | diagnostic.code = "RENAME"; 89 | diagnostic.source = plan.Replacement; 90 | } 91 | diagnostics.push(diagnostic); 92 | } 93 | ); 94 | 95 | return diagnostics; 96 | } 97 | 98 | -------------------------------------------------------------------------------- /vscode-extension/src/quickFix.ts: -------------------------------------------------------------------------------- 1 | /*--------------------------------------------------------- 2 | * Copyright (C) Microsoft Corporation. All rights reserved. 3 | *--------------------------------------------------------*/ 4 | 5 | import * as vscode from 'vscode'; 6 | 7 | export const BREAKING_CHANGE = 'breaking change'; 8 | export const DEPRECATED_CMDLET = 'deprecated cmdlet'; 9 | export const CMDLET_RENAME = 'cmdlet rename'; 10 | export const PARAMETER_CHANGE = 'parameter change'; 11 | export const DO_NOTHING = 'do nothing'; 12 | 13 | export const GET_INFO_COMMAND = 'getInfo'; 14 | export const GET_DEPRE_INFO_COMMAND = 'getdepreInfo'; 15 | 16 | /** 17 | * Run CodeAction when click the "Quick Fix" 18 | */ 19 | export class QuickFixProvider implements vscode.CodeActionProvider { 20 | 21 | 22 | public static readonly providedCodeActionKinds = [ 23 | vscode.CodeActionKind.QuickFix 24 | ]; 25 | 26 | public provideCodeActions(document: vscode.TextDocument, range: vscode.Range | vscode.Selection, context: vscode.CodeActionContext): vscode.CodeAction[] { 27 | 28 | return context.diagnostics.map(diagnostic => this.getAutoFixCodeAction(diagnostic)); 29 | 30 | } 31 | 32 | private getAutoFixCodeAction(diagnostic: vscode.Diagnostic): vscode.CodeAction { 33 | const fix = new vscode.CodeAction("", vscode.CodeActionKind.QuickFix); 34 | fix.edit = new vscode.WorkspaceEdit(); 35 | const editor = vscode.window.activeTextEditor; 36 | 37 | if (!editor) { 38 | return fix; 39 | } 40 | 41 | const document = editor.document; 42 | const range = diagnostic.range; 43 | const targetCmdletName: string = diagnostic.source; 44 | 45 | switch (diagnostic.code) { 46 | case "RENAME": { 47 | fix.title = "Auto fix to " + targetCmdletName; 48 | fix.edit.replace(document.uri, range, targetCmdletName); 49 | break; 50 | } 51 | case "DO_NOTHING": { 52 | return null; 53 | } 54 | } 55 | 56 | return fix; 57 | } 58 | } -------------------------------------------------------------------------------- /vscode-extension/src/test/runTest.ts: -------------------------------------------------------------------------------- 1 | import * as path from 'path'; 2 | 3 | import { runTests } from 'vscode-test'; 4 | 5 | async function main() { 6 | try { 7 | // The folder containing the Extension Manifest package.json 8 | // Passed to `--extensionDevelopmentPath` 9 | const extensionDevelopmentPath = path.resolve(__dirname, '../../'); 10 | 11 | // The path to test runner 12 | // Passed to --extensionTestsPath 13 | const extensionTestsPath = path.resolve(__dirname, './suite/index'); 14 | 15 | // Download VS Code, unzip it and run the integration test 16 | await runTests({ extensionDevelopmentPath, extensionTestsPath }); 17 | } catch (err) { 18 | console.error('Failed to run tests'); 19 | process.exit(1); 20 | } 21 | } 22 | 23 | main(); 24 | -------------------------------------------------------------------------------- /vscode-extension/src/test/suite/extension.test.ts: -------------------------------------------------------------------------------- 1 | import * as assert from 'assert'; 2 | 3 | // You can import and use all API from the 'vscode' module 4 | // as well as import your extension to test it 5 | import * as vscode from 'vscode'; 6 | // import * as myExtension from '../../extension'; 7 | 8 | suite('Extension Test Suite', () => { 9 | vscode.window.showInformationMessage('Start all tests.'); 10 | 11 | test('Sample test', () => { 12 | assert.equal(-1, [1, 2, 3].indexOf(5)); 13 | assert.equal(-1, [1, 2, 3].indexOf(0)); 14 | }); 15 | }); 16 | -------------------------------------------------------------------------------- /vscode-extension/src/test/suite/index.ts: -------------------------------------------------------------------------------- 1 | import * as path from 'path'; 2 | import * as Mocha from 'mocha'; 3 | import * as glob from 'glob'; 4 | 5 | export function run(): Promise { 6 | // Create the mocha test 7 | const mocha = new Mocha({ 8 | ui: 'tdd', 9 | color: true 10 | }); 11 | 12 | const testsRoot = path.resolve(__dirname, '..'); 13 | 14 | return new Promise((c, e) => { 15 | glob('**/**.test.js', { cwd: testsRoot }, (err, files) => { 16 | if (err) { 17 | return e(err); 18 | } 19 | 20 | // Add files to the test suite 21 | files.forEach(f => mocha.addFile(path.resolve(testsRoot, f))); 22 | 23 | try { 24 | // Run the mocha test 25 | mocha.run(failures => { 26 | if (failures > 0) { 27 | e(new Error(`${failures} tests failed.`)); 28 | } else { 29 | c(); 30 | } 31 | }); 32 | } catch (err) { 33 | console.error(err); 34 | e(err); 35 | } 36 | }); 37 | }); 38 | } 39 | -------------------------------------------------------------------------------- /vscode-extension/src/types/migraion.ts: -------------------------------------------------------------------------------- 1 | export enum UpgradeStepType { 2 | Cmdlet, 3 | CmdletParameter 4 | } 5 | 6 | export enum PlanResultReasonCode { 7 | ReadyToUpgrade = 0, 8 | WarningSplattedParameters = 1, // deprecated 9 | ErrorNoUpgradeAlias = 2, 10 | ErrorNoModuleSpecMatch = 3, 11 | ErrorParameterNotFound = 4, 12 | WarningDynamicParameter = 5 13 | } 14 | 15 | export enum DiagnosticSeverity { 16 | Error = 1, 17 | Warning = 2, 18 | Information = 3, 19 | Hint = 4 20 | } 21 | 22 | export interface CommandReferenceParameter { 23 | FileName: string, 24 | FullPath: string, 25 | Name: string, 26 | StartLine: number, 27 | StartColumn: number, 28 | EndLine: number, 29 | EndPosition: number, 30 | StartOffset: number, 31 | EndOffset: number, 32 | Location: string 33 | } 34 | 35 | export interface CommandReference { 36 | FileName: string, 37 | FullPath: string, 38 | StartLine: number, 39 | StartColumn: number, 40 | EndLine: number, 41 | EndPosition: number, 42 | StartOffset: number, 43 | EndOffset: number, 44 | Location: string, 45 | HasSplattedArguments: boolean, 46 | CommandName: string, 47 | Parameters: CommandReferenceParameter[] 48 | } 49 | 50 | 51 | export interface UpgradePlan { 52 | Order: number, 53 | UpgradeType: UpgradeStepType, 54 | PlanResult: PlanResultReasonCode, 55 | PlanSeverity: DiagnosticSeverity, 56 | PlanResultReason: string 57 | SourceCommand: CommandReference, 58 | SourceCommandParameter: CommandReferenceParameter, 59 | Location: string, 60 | FullPath: string, 61 | StartOffset: number, 62 | Original: string, 63 | Replacement: string 64 | } -------------------------------------------------------------------------------- /vscode-extension/src/types/node-powershell.d.ts: -------------------------------------------------------------------------------- 1 | declare module 'node-powershell' { 2 | class shell { 3 | constructor(options: ShellOptions); 4 | public addCommand(command: string): void; 5 | public invoke(): Promise; 6 | public dispose(): Promise; 7 | public invocationStateInfo: string; 8 | public pid: number; 9 | } 10 | interface ShellOptions { 11 | executionPolicy: string; 12 | noProfile: boolean; 13 | } 14 | export = shell; 15 | } 16 | 17 | -------------------------------------------------------------------------------- /vscode-extension/src/utils.ts: -------------------------------------------------------------------------------- 1 | /*--------------------------------------------------------- 2 | * Copyright (C) Microsoft Corporation. All rights reserved. 3 | *--------------------------------------------------------*/ 4 | 5 | "use strict"; 6 | 7 | import fs = require("fs"); 8 | import os = require("os"); 9 | import path = require("path"); 10 | 11 | export const PowerShellLanguageId = "powershell"; 12 | 13 | export function ensurePathExists(targetPath: string): void { 14 | // Ensure that the path exists 15 | try { 16 | fs.mkdirSync(targetPath); 17 | } catch (e) { 18 | // If the exception isn't to indicate that the folder exists already, rethrow it. 19 | if (e.code !== "EEXIST") { 20 | throw e; 21 | } 22 | } 23 | } 24 | 25 | export function getPipePath(pipeName: string): string { 26 | if (os.platform() === "win32") { 27 | return "\\\\.\\pipe\\" + pipeName; 28 | } else { 29 | // Windows uses NamedPipes where non-Windows platforms use Unix Domain Sockets. 30 | // This requires connecting to the pipe file in different locations on Windows vs non-Windows. 31 | return path.join(os.tmpdir(), `CoreFxPipe_${pipeName}`); 32 | } 33 | } 34 | 35 | export interface IEditorServicesSessionDetails { 36 | status: string; 37 | reason: string; 38 | detail: string; 39 | powerShellVersion: string; 40 | channel: string; 41 | languageServicePort: number; 42 | debugServicePort: number; 43 | languageServicePipeName: string; 44 | debugServicePipeName: string; 45 | } 46 | 47 | export type IReadSessionFileCallback = (details: IEditorServicesSessionDetails) => void; 48 | 49 | const sessionsFolder = path.resolve(__dirname, "..", "..", "sessions/"); 50 | const sessionFilePathPrefix = path.resolve(sessionsFolder, "PSES-VSCode-" + process.env.VSCODE_PID); 51 | 52 | // Create the sessions path if it doesn't exist already 53 | ensurePathExists(sessionsFolder); 54 | 55 | export function getSessionFilePath(uniqueId: number): string { 56 | return `${sessionFilePathPrefix}-${uniqueId}`; 57 | } 58 | 59 | export function getDebugSessionFilePath(): string { 60 | return `${sessionFilePathPrefix}-Debug`; 61 | } 62 | 63 | export function writeSessionFile(sessionFilePath: string, sessionDetails: IEditorServicesSessionDetails): void { 64 | ensurePathExists(sessionsFolder); 65 | 66 | const writeStream = fs.createWriteStream(sessionFilePath); 67 | writeStream.write(JSON.stringify(sessionDetails)); 68 | writeStream.close(); 69 | } 70 | 71 | 72 | export function readSessionFile(sessionFilePath: string): IEditorServicesSessionDetails { 73 | const fileContents = fs.readFileSync(sessionFilePath, "utf-8"); 74 | return JSON.parse(fileContents); 75 | } 76 | 77 | export function deleteSessionFile(sessionFilePath: string): void { 78 | try { 79 | fs.unlinkSync(sessionFilePath); 80 | } catch (e) { 81 | // TODO: Be more specific about what we're catching 82 | } 83 | } 84 | 85 | export function checkIfFileExists(filePath: string): boolean { 86 | try { 87 | fs.accessSync(filePath, fs.constants.R_OK); 88 | return true; 89 | } catch (e) { 90 | return false; 91 | } 92 | } 93 | 94 | export function getTimestampString(): string { 95 | const time = new Date(); 96 | return `[${time.getHours()}:${time.getMinutes()}:${time.getSeconds()}]`; 97 | } 98 | 99 | export function sleep(ms: number): Promise { 100 | return new Promise(resolve => setTimeout(resolve, ms)); 101 | } 102 | 103 | export const isMacOS: boolean = process.platform === "darwin"; 104 | export const isWindows: boolean = process.platform === "win32"; 105 | export const isLinux: boolean = !isMacOS && !isWindows; 106 | -------------------------------------------------------------------------------- /vscode-extension/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "module": "commonjs", 4 | "target": "es6", 5 | "outDir": "out", 6 | "lib": [ 7 | "es2017", 8 | "DOM" 9 | ], 10 | "sourceMap": true, 11 | "rootDir": "src" 12 | }, 13 | "exclude": [ 14 | "node_modules" 15 | ] 16 | } --------------------------------------------------------------------------------