尝试/捕获不在Powershell控制台中工作,但在ISE中工作

时间:2016-05-03 08:40:18

标签: powershell try-catch powershell-v3.0 powershell-ise

我有一个带有try / catch部分的Powershell脚本,可以将错误写入日志文件。这在Powershell ISE中完全正常,但在Powershell控制台中却没有。这是脚本:

$serverfile = "C:\Serverlist.txt"
$Logfile = "C:\Deploy_Log.txt"

$startdate= "01/05/2016"
$starttime = 13

Set-StrictMode -Version latest
$ErrorActionPreference = "Stop"
$WarningPreference = "Stop"

function LogWrite {
    param([string]$logstring)
    Add-Content $Logfile -Value $logstring
}

function DeployTask {
    param([string]$server1)

    $arguments = '/Create', '/S', "$server1", '/RU', 'domain\user', '/RP', 'pa$$w0rd', '/SC', 'ONCE', '/st', "$starttime`:00:00", '/sd', "$startdate", '/TN', 'Task_InstallUpdates', '/TR', 'C:\patchday\InstallUpdates.bat', '/RL', 'HIGHEST', '/F'
    Write-Host "$startdate, $starttime`:00"

    if (Test-Connection $server1 -Quiet) {
        # delete scheduled task
        try {
            schtasks.exe /S $server1 /delete /tn Task_InstallUpdates /f
        } catch {
            $ErrorMessage = $_.Exception.Message
            LogWrite "$server1 : Error deleting scheduled task - $ErrorMessage"
        }

        # create scheduled task
        try {
            & schtasks.exe $arguments
        } catch {
            $ErrorMessage = $_.Exception.Message
            LogWrite "$server1 : Error creating scheduled task - $ErrorMessage"
        }
    } else {
        LogWrite "$server1 is not available"
    }
}

$servers = Get-Content -Path $serverfile
foreach ($server1 in $servers) {
    Write-Host $server1
    try {
        DeployTask $server1
    } catch {
        $ErrorMessage = $_.Exception.Message
        LogWrite "$server1 : $ErrorMessage"
    }
}

有什么想法吗?我已将$ErrorActionPreference$WarningPreference设置为“停止”并启用了严格模式。在ISE中,创建了日志文件,内容如下:

  

srv17:创建计划任务时出错 - 警告:由于/ ST早于当前时间,任务可能无法运行。
  srv18:创建计划任务时出错 - 警告:任务可能无法运行,因为/ ST早于当前时间。

在Powershell控制台中,未创建日志文件,而是在控制台中显示所有错误和警告。

2 个答案:

答案 0 :(得分:1)

您正在运行外部命令。那些通常不会抛出PowerShell异常。改为评估$LASTEXITCODE

$output = & schtasks.exe /S $server1 /delete /tn Task_InstallUpdates /f 2>&1
if ($LASTEXITCODE -ne 0) {
    LogWrite "$server1 : Error deleting scheduled task - $output"
}

# create scheduled task
$output = & schtasks.exe $arguments 2>&1
if ($LASTEXITCODE -ne 0) {
    LogWrite "$server1 : Error creating scheduled task - $output"
}

答案 1 :(得分:0)

我也遇到了同样的问题,所以我找到了另一种处理错误的方法:

$error.clear() #before the command
<you commands>
if ($error.Count -gt 0){ #adter the commands
    $problem = $Error[0].Exception.Message
    Write-Host $problem

}