且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何连接到Azure Windows VM并使用PowerShell运行远程脚本?

更新时间:2023-10-21 16:07:34

根据您的描述,我们可以使用New-Pssession执行脚本来停止/启动服务,如下所示:

According to your description, we can use New-Pssession to execute script to stop/start service, like this:

$username = 'jason'
$pass = ConvertTo-SecureString -string 'password' -AsPlainText -Force
$cred = New-Object -typename System.Management.Automation.PSCredential -argumentlist $username, $pass
$s = New-PSSession -ConnectionUri 'http://23.99.82.2:5985' -Credential $cred -SessionOption (New-PSSessionOption -SkipCACheck -SkipCNCheck -SkipRevocationCheck)
Invoke-Command -Session $s -ScriptBlock {Get-Process PowerShell}

结果如下:

另一种方法,我们可以使用Azure自定义脚本扩展来运行脚本,可以将脚本上传到Azure存储帐户,并使用Set-AzureRmVMCustomScriptExtension设置自定义脚本:

Another way, we can use Azure custom script extension to run script, we can upload script to Azure storage account, and use Set-AzureRmVMCustomScriptExtension to set custom script:

PS C:\> Set-AzureRmVMCustomScriptExtension -ResourceGroupName "ResourceGroup11" -Location "Central US" -VMName "VirtualMachine07" -Name "ContosoTest" -TypeHandlerVersion "1.1" -StorageAccountName "Contoso" -StorageAccountKey <StorageKey> -FileName "ContosoScript.exe" -ContainerName "Scripts"

但是自定义脚本只能运行一次,如果要重新运行此脚本,我们应该使用此命令Remove-AzureRmVMCustomScriptExtension将其删除,然后重新设置. 有关Azure自定义脚本扩展的详细信息,请参考此

But custom script only can run one time, if you want to re-run this script, we should remove it with this command Remove-AzureRmVMCustomScriptExtension, then re-set it. More information about Azure custom script extension, please refer to this link.