【问题标题】:How to print error message into text file in Powershell如何在 Powershell 中将错误消息打印到文本文件中
【发布时间】:2021-08-07 17:49:06
【问题描述】:

我有一个简单的脚本,它将在 cmd 工具中执行 text.bat 并在 hello.txt 中打印结果。这是针对远程服务器完成的。

Invoke-Command -ComputerName 1.1.1.1 -Credential KOPI\Administrator -ScriptBlock {
Invoke-Expression -Command:"cmd.exe /c 'C:\Users\Administrator.KOPI\Documents\test.bat'"

} | out-file $psscriptroot\hello.txt

但是,bat文件遇到如下错误。

ERROR: The system was unable to find the specified registry key or value.
    + CategoryInfo          : NotSpecified: (ERROR: The syst...y key or value.:String) [], RemoteException
    + FullyQualifiedErrorId : NativeCommandError
    + PSComputerName        : 1.1.1.1

所以我的问题是,是否可以只打印错误消息 ERROR: The system was unable to find the specified registry key or value. into hello.txt?

【问题讨论】:

  • } | out-file ... -> } 2>&1 | out-file ...
  • OP 只要求提供错误消息。没有整个堆栈:)

标签: powershell powershell-remoting


【解决方案1】:

是的,您正在寻找的是捕获异常消息 ($_.Exception.Message)。

例如:

try {
    Invoke-Command -ComputerName 1.1.1.1 -Credential KOPI\Administrator -ScriptBlock {
        Invoke-Expression -Command:"cmd.exe /c 'C:\Users\Administrator.KOPI\Documents\test.bat'"
        } | out-file $psscriptroot\hello.txt
}
catch {
    $_.Exception.Message | Out-File $psscriptroot\hello.txt
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-26
    • 1970-01-01
    • 2014-01-05
    • 1970-01-01
    • 2019-10-29
    相关资源
    最近更新 更多