Try/catch not working in Powershell console, but works in ISE

谁都会走 提交于 2019-12-12 04:32:07

问题


I have a Powershell script with try/catch parts to write the errors into a logfile. This works perfectly fine in Powershell ISE, but not in the Powershell console. Here's the script:

$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"
    }
}

Any ideas? I have set the $ErrorActionPreference and $WarningPreference to "Stop" and enabled strict mode. In ISE the logfile is created and the content is something like this:

srv17: Error creating scheduled task - WARNING: Task may not run because /ST is earlier than current time.
srv18: Error creating scheduled task - WARNING: Task may not run because /ST is earlier than current time.

In Powershell console, the logfile is NOT created and all errors and warnings show in the console instead.


回答1:


You're running external commands. Those usually don't throw PowerShell exceptions. Evaluate $LASTEXITCODE instead:

$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"
}



回答2:


I also had the same issue so I found another way to handle erros:

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

}


来源:https://stackoverflow.com/questions/36999437/try-catch-not-working-in-powershell-console-but-works-in-ise

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!