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

后端 未结 2 726
悲哀的现实
悲哀的现实 2020-12-12 01:59

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 Wi

2条回答
  •  旧巷少年郎
    2020-12-12 02:34

    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  -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.

提交回复
热议问题