Invoke-AzVMRunCommand 日志输出、错误处理

问题描述 投票:0回答:2

一旦我们运行命令“Invoke-AzVMRunCommand”在远程虚拟机上执行 PS 脚本,它总是会成功,即使实际上失败了。我知道远程虚拟机那里有日志文件:

“C:\Packages\Plugins\Microsoft.CPlat.Core.RunCommandWindows .1.3\Status”

问题:

但是如何在本地powershell、try-catch等上检索错误并没有显示。 使用“Invoke-AzVMRunCommand”进行正确的错误处理是什么,最好以 .txt 形式获取结果,例如:

|输出文件-文件路径 xxx.txt

谢谢你。

powershell powershell-remoting remotecommand
2个回答
3
投票

最终经过长时间的测试,我最终得到了这个解决方案,它会从远程脚本执行中引发错误并将其记录在 .txt 文件中:

$result = Invoke-AzVMRunCommand -ErrorAction Stop -ResourceGroupName "MyRg" -Name "MyVM" -CommandId 'RunPowerShellScript' -ScriptPath MyScript.ps1
Remove-Item -path script.ps1 

if ($result.value.Message -like '*error*') 
{  

    Write-Output "Failed. An error occurred: `n $($result.value.Message)" | Out-File -Filepath C:\OutputLog.txt -Append
    throw $($result.value.Message)        
}
else
{
    Write-Output "Success" | Out-File -Filepath C:\OutputLog.txt -Append
} 

0
投票

由于这是我在寻找这个问题时得到的最重要的结果之一,我想我应该添加一些额外的信息,了解如何在 Invoke-AzVMRunCommand 中使用 -AsJob 参数(通常用于并行性或状态)时获取作业的输出跟踪。)

当您将 -AsJob 与 Invoke-AzVMRunCommand 结合使用时,它会创建一个 PowerShell 作业对象来跟踪任务的状态。然后,您可以使用 Get-Job 检索作业信息。但是,任务的“输出”不会出现在这些结果中。您需要将作业的对象传递给 Receive-Job cmdlet 以获取输出信息。此 cmdlet 返回更多信息,并具有一个“Values”属性,其中至少包含两个(根据我的观察)项目。 [0] 的索引包含标准输出流消息,[1] 的索引包含标准错误输出流消息。

所以总的来说,它看起来像这样:

$VM = Get-AzVM -Name 'SomeVM'

Invoke-AzVMRunCommand -AsJob -VM $VM -CommandId 'RunPowerShellScript' -ScriptPath ".\MyScript.ps1"

#Use whatever method you want for waiting - a loop to check the job status or a delay (when using -AsJob, Invoke-AzRunCommand is asynchronous)

#Recevives the standard output stream for all jobs
(Get-Job -IncludeChildJob | Receive-Job).Value[0].Message

#Recevives the standard error stream for all jobs
(Get-Job -IncludeChildJob | Receive-Job).Value[1].Message

如果您想要特定的工作,您可以指定工作名称或 ID。 请注意,一旦您对作业执行“接收作业”,其结果就会从内存中清除,因此如果您希望重新使用它们,请将它们存储在变量中。

© www.soinside.com 2019 - 2024. All rights reserved.