【问题标题】:VBScript, Batch or PowerShell Script?VBScript、批处理还是 PowerShell 脚本?
【发布时间】:2009-11-05 18:45:37
【问题描述】:

我正在尝试使用来自Windows Sysinternals 的 psexec.exe 运行各种命令。我需要的是一个简单的脚本来读取这些命令的输出。

例如,如果一切正常,则返回 0。如果出现问题,则会吐出错误代码。

怎么做?

【问题讨论】:

    标签: powershell vbscript batch-file


    【解决方案1】:

    在 PowerShell 中,您将使用 $LastExitCode 变量来测试 psexec 是否成功,例如:

    $results = psexec <some command on remote system>
    if ($LastExitCode -ne 0) {
        throw "PSExec failed with error code $LastExitCode"
    }
    return 0
    

    【讨论】:

      【解决方案2】:

      在批处理文件中,您使用 %ERRORLEVEL% 变量或 IF ERRORLEVEL n 命令。例如:

      psexec \\host -i findstr.exe "test" c:\testfile
      if errorlevel 1 (
        echo A problem occurred
      )
      

      IF ERRORLEVEL 检查返回值是否等于或高于您指定的数字。

      这与捕获命令的输出不同。如果您确实想要输出,则需要在命令行中包含对输出文件的重定向:

      psexec \\host -i cmd.exe /c findstr "test" c:\testfile ^> c:\output.txt
      

      ^ 是转义 > 字符所必需的,否则重定向将发生在本地而不是远程计算机上。 cmd.exe 是必需的,因为重定向由 cmd 处理。

      【讨论】:

      • %errorlevel% 只是一个伪变量,由 shell 动态扩展。就像%time%%random% 和其他人一样。
      猜你喜欢
      • 1970-01-01
      • 2018-04-13
      • 1970-01-01
      • 2013-07-30
      • 2023-03-30
      • 1970-01-01
      • 2015-09-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多