How Connect to a Azure Windows VM and run a remote script with PowerShell?

青春壹個敷衍的年華 提交于 2019-11-27 08:24:05

问题


I am familiar with Linux envs and using SSH to run remote scripts and programs and automatic scripts from my desktop.

I would like to have a similar workflow with Windows VMs that I have on my Azure Account. However, I can´t find a straight forward instructions on how to build my local PowerShell scripts.

I need only to connect to a VM and call some scripts within it.

The best I could find would be this guide from MS https://docs.microsoft.com/en-us/azure/virtual-machines/windows/winrm

Or this a litte older blog post.

http://fabriccontroller.net/using-remote-powershell-with-windows-azure-virtual-machines/


回答1:


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}

Result like this:

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"

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.




回答2:


I ran into a lot of trouble using the accepted answer, and found I wanted to use SSL in my remote execution. I could not find anywhere this was succinctly put, so here's what worked for me. Essentially, use the built-in Azure command to enable remote PowerShell on the VM, and then run secure remote sessions to your heart's content!

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


来源:https://stackoverflow.com/questions/45196104/how-connect-to-a-azure-windows-vm-and-run-a-remote-script-with-powershell

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!