[英]How Connect to a Azure Windows VM and run a remote script with PowerShell?
我熟悉Linux env,並使用SSH從桌面運行遠程腳本和程序以及自動腳本。
我希望在Azure帳戶上擁有與Windows VM類似的工作流。 但是,我找不到關於如何構建本地PowerShell腳本的直接說明。
我只需要連接到VM並在其中調用一些腳本即可。
我能找到的最好的方法是來自MS https://docs.microsoft.com/zh-cn/azure/virtual-machines/windows/winrm的本指南
還是這是一篇比較老的博客文章。
http://fabriccontroller.net/using-remote-powershell-with-windows-azure-virtual-machines/
根據您的描述,我們可以使用New-Pssession
執行腳本來停止/啟動服務,如下所示:
$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
來設置自定義腳本:
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
將其Remove-AzureRmVMCustomScriptExtension
,然后重新設置它。 有關Azure自定義腳本擴展的更多信息,請參考此鏈接 。
使用接受的答案時,我遇到了很多麻煩,發現我想在遠程執行中使用SSL。 我找不到在這個地方簡明放置的東西,所以這對我有用。 本質上,請使用內置的Azure命令在VM上啟用遠程PowerShell,然后運行安全的遠程會話來滿足您的需求!
Invoke-AzureRmVMRunCommand -ResourceGroupName $vmResourceGroupName -Name $vmName -CommandId 'EnableRemotePS'
$cred = New-Object -typename System.Management.Automation.PSCredential -argumentlist $username, $secureStringPassword
$sessionOptions = New-PSSessionOption -SkipCACheck -SkipCNCheck
Invoke-Command -ComputerName $ipAddress -Credential $cred -UseSSL -SessionOption $sessionOptions -FilePath $scriptPath
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.