Start-DscConfiguration不会抛出异常?

时间:2014-11-29 10:40:56

标签: powershell dsc

我注意到如果通过Start-DscConfiguration应用配置失败,它会写入错误流但不会 扔一个例外?也就是说,如果我执行以下操作:

try{
    Start-DscConfiguration -Path ".\MyConfig" -Wait -Verbose
}catch{
    #...
}

...它永远不会在catch处理程序中结束。我怀疑这可能与没有"-Wait"的事实有关, Start-DscConfiguration为此启动异步作业,异步命令可能不会抛出异常,但在同步中 方案,我非常想知道我的配置是否可以应用。

确定Start-DscConfiguration是否已成功完成的正确方法是什么?

3 个答案:

答案 0 :(得分:5)

我知道的唯一方法是检查全局&​​#34; $错误"变量并比较调用Start-DscConfiguration之前和之后的错误记录数。如果之后有更多事情,那么在通话期间肯定会出现问题,所以抛出你自己的例外:

Configuration TestErrorHandling {
    Node "localhost" {
        Script ErroringResource {
            GetScript =  { return $null; }
            TestScript = { return $false; }
            SetScript = { throw new-object System.InvalidOperationException; }
        }
    }
}

$errorCount = $error.Count;

write-host "starting dsc configuration"
$mof = TestErrorHandling;
Start-DscConfiguration TestErrorHandling –Wait –Verbose;
write-host "dsc configuration finished"

if( $error.Count -gt $errorCount )
{
    $dscErrors = $error[$errorCount..($error.Count - 1)];
    write-host "the following errors occurred during dsc configuration";
    write-host ($dscErrors | fl * | out-string);
    throw $dscErrors[-1];
}

答案 1 :(得分:1)

还有另一种方法可以导致异常。尝试将其保存到 ErrorVariable ,如下所示:

try
{
   Start-DscConfiguration -Path ".\MyConfig" -Wait -Verbose -ErrorVariable ev
}
catch
{
    $myException = $_
}

奇怪的是,这会在出现错误时抛出异常(这就是你想要的)。您可以在$ myexception变量中获取异常的值,也可以使用$ ev

获得错误的单线描述

PS:请注意,虽然在errorVariable参数中提到ev,但是在没有'$'符号的情况下这样做 - 因为您只是指定变量'name'。

答案 2 :(得分:0)

在没有-Wait的情况下使用Start-DscConfiguration将创建一个作业对象 - 每个计算机名都有一个子作业。 PowerShell作业对象具有包含所有错误的错误流。你也可以检查这个流

$ job = Start-DscConfiguration -Force -Verbose -Path C:\ Temp \ Demo \ -ComputerName localhost

Receive-Job $ job -Wait

'工作中的错误=' +($ job.childjobs [0] .Error.Count)

相关问题