在Powershell脚本中运行时,Invoke-AzureRmVMRunCommand命令显示错误的输出

时间:2019-04-02 09:49:40

标签: azure powershell

我正在尝试运行以下powershell脚本

以下脚本用于列出VM中的本地用户


$subscriptions=Get-AzSubscription -SubscriptionId "##################"

foreach ($subscription in $subscriptions){

Select-AzSubscription -SubscriptionId $subscription.SubscriptionId

$instances=Get-AzVM -Status | Select-Object Name,PowerState,ResourceGroupName ,@{l='osType';e={$\_.StorageProfile.osDisk.osType}}

foreach ($instance in $instances){

    Write-Host $instance.Name.Name

    Write-Host $instance.osType

    if($instance.osType -eq "Windows"){

        Write-Host "Windows server"

        if($instance.PowerState -eq "VM running"){
$users=Invoke-AzVMRunCommand -ResourceGroupName $instance.ResourceGroupName -Name $instance.Name -CommandId 'RunPowerShellScript' -ScriptPath 'C:\Users\tushar.raichand\Desktop\sample.ps1'

Write-Host $users

Write-Host "####################################################"

foreach($user in $users){

Write-Host $user

}

        }

    }

    else{

        if($instance.PowerState -eq "running"){
Write-Host "Linux server"

        }



    }

}
}

Sample.ps1如下


$output = Get-LocalUser

Write-Output $output

$output

我为Invoke-AzVMRunCommand获得的输出是


Microsoft.Azure.Commands.Compute.Automation.Models.PSRunCommandResult

就像我刚在控制台中运行此命令时一样


Invoke-AzVMRunCommand -ResourceGroupName $instance.ResourceGroupName -Name $instance.Name -CommandId 'RunPowerShellScript' -ScriptPath 'C:\Users\tushar.raichand\Desktop\sample.ps1'

我正在获取用户列表。

1 个答案:

答案 0 :(得分:1)

好,我可以转载您的问题。该问题是由Write-Host $users引起的,您需要将其更改为Write-Output $users

enter image description here

示例

$users=Invoke-AzVMRunCommand -ResourceGroupName $instance.ResourceGroupName -Name $instance.Name -CommandId 'RunPowerShellScript' -ScriptPath 'C:\Users\joyw\Desktop\sample.ps1' 
Write-Output $users

enter image description here

此外,您的脚本有一些小错误,e={$\_.StorageProfile.osDisk.osType}应该是e={$_.StorageProfile.osDisk.osType}Write-Host $instance.Name.Name应该是Write-Host $instance.Name,就足够了。