将cmd错误捕获到CURRENT目录中的文件? [英] Capture cmd error to file in CURRENT directory?

查看:93
本文介绍了将cmd错误捕获到CURRENT目录中的文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个PowerShell脚本,可以重新启动文件中列出的服务器。

I have a PowerShell script that restarts servers listed in a file.

foreach ($server in $servers) {
    try {
        cmd /c "shutdown.exe /r /f /m \\$server /t 0 /d p:0:0 /c 'PlannedRestart'" 
        "$server`tRestarted"
        "$server`tRestarted" | Out-File -FilePath .\RestartServers_LOG.txt -Append
    } catch {
        "$server`t" + cmd /c ">&1"
        "$server`t" + cmd /c "dir > .\RestartServers_LOG.txt 2>&1"
    }
}

我正在尝试捕获CMD可能发生的任何错误,以在PowerShell会话上输出以及在CURRENT目录中的文件上输出,因此在PowerShell中应为 .\ ,但我不知道CMD的当前目录规范是什么。除非是同一件事?

I am trying to catch any errors that may occur from the CMD to output on the PowerShell session as well as to a file in the CURRENT directory, so in PowerShell that would be .\ but I don't know what the current directory specification is for CMD. Unless its the same thing?

本质上,我希望完成一些类似于如何捕获PowerShell异常消息的事情:

Essentially, I am hoping to accomplish something similar to how we can capture the exception message of PowerShell like this:

"$server`t" + $_.Exception.Message.ToString().Split(":")[1].Replace("`n","") |
    Out-File -FilePath .\RestartServers_LOG.txt -Append

但是CMD不会

注意:我使用命令 shutdown.exe 是因为不幸的是,PowerShell无法重新启动计划的或计划外的。

Note: I am using the command shutdown.exe because PowerShell doesn't have ability to restart "planned" or "unplanned" unfortunately.

推荐答案

只需按PoSh方式即可:

Just do it the PoSh way:

$params = '/r', '/f',
          '/t', '0',
          '/d', 'p:0:0',
          '/c', 'PlannedRestart'

$servers | ForEach-Object {
    $output = & shutdown.exe /m "\\${_}" @params 2>&1
    if ($LastExitCode -eq 0) {
        "{0}`tRestarted" -f $_
    } else {
        "{0}`tRestart failed:`t{1}" -f $_, $output
    }
} | Set-Content '.\RestartServers_LOG.txt'

外部命令在第一个命令中不会引发异常位置,因此您的 try..catch 不会做任何事情。

External commands don't throw exceptions in the first place, so your try..catch wouldn't do anything anyway.

这篇关于将cmd错误捕获到CURRENT目录中的文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆