如何连接到Azure Windows VM并使用PowerShell运行远程脚本? [英] How Connect to a Azure Windows VM and run a remote script with PowerShell?
问题描述
我熟悉Linux env,并使用SSH在桌面上运行远程脚本和程序以及自动脚本.
I am familiar with Linux envs and using SSH to run remote scripts and programs and automatic scripts from my desktop.
我希望在Azure帐户上拥有与Windows VM类似的工作流.但是,我找不到关于如何构建本地PowerShell脚本的直接说明.
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.
我只需要连接到VM并在其中调用一些脚本即可.
I need only to connect to a VM and call some scripts within it.
我能找到的最好的方法是MS的本指南 https://docs.microsoft.com/zh-cn/azure/virtual-machines/windows/winrm
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-带Windows天蓝色虚拟机的远程Powershell/
推荐答案
根据您的描述,我们可以使用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.
这篇关于如何连接到Azure Windows VM并使用PowerShell运行远程脚本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!