PowerShell - 捕获svn.exe调用的输出

时间:2014-12-16 16:07:09

标签: powershell svn error-handling automation powershell-v4.0

我正在使用PowerShell v4来调用svn命令行工具,并且无法解决执行基本错误处理的问题。我已经尝试使用try-catch块将任何svn命令的结果捕获到变量,甚至捕获异常也不起作用

以下结帐有意在控制台中生成“身份验证失败”错误:

trap [SystemException]
{
    Write-Output "ERROR: $_";exit 1
}
try
{
    $log = svn.exe checkout $Url $Path --no-auth-cache --non-interactive --username "username" --password "Password"
}
catch
{
    write-host "$_"
}

在控制台窗格中,显示错误:

  

svn.exe:svn:E215004:身份验证失败并且是交互式的   提示被禁用;请参阅--force-interactive选项At   C:\ dev \ Temp \ script.ps1:30 char:8   + $ log = svn.exe checkout $ Url $ Path --no-auth-cache --non-interactive --username ...   + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~       + CategoryInfo:NotSpecified:(svn:E215004:A ... eractive option:String)[],RemoteException       + FullyQualifiedErrorId:NativeCommandError svn:E215004:无法连接到URL上的存储库   “http://source.com/”身份验证失败

永远不会为$log变量分配上述输出,同时忽略try-catch块和泛型陷阱。

当然有人已经自动化了一些SVN,如果没有基本的错误处理,自动化的效果如何?

2 个答案:

答案 0 :(得分:3)

一些简单的选择,取决于你想做什么。

如果要捕获命令的输出,请使用Invoke-Expression

$log = Invoke-Expression "svn.exe checkout $Url $Path --no-auth-cache --non-interactive --username `"username`" --password `"Password`""

如果要检查命令是否成功,请使用$?

svn.exe checkout $Url $Path --no-auth-cache --non-interactive --username "username" --password "Password" | out-null
echo $?

您还可以查看使用Start-Process cmdlet,甚至使用System.Diagnostics.Process对象来更好地控制流程执行。

答案 1 :(得分:1)

我最终选择的解决方案并不包括结帐,因为TeamCity会自动执行此操作。

以下是最终脚本如何检查currrent PowerShell会话是否通过SVN身份验证以及$PSScriptRoot脚本目录是否为SVN工作副本:

svn info "$PSScriptRoot" 2>&1 | Tee-Object -Variable svnResult

if (($svnResult -notmatch '\d{6}:'))
{
    write-host "`nVerified the connection to SVN"
}
else
{
    throw "`nAn error occurred verifying the connection to SVN"
}

2>&1将所有错误重定向到标准输出流,然后Tee-Object cmdlet将输出发送到$svnResult变量。

由于所有SVN错误消息都包含6个数字后跟冒号,\d{6}:正则表达式会检查$svnResult变量是否出现此情况,如果找到,则会引发错误。

有关PowerShell重定向的更多信息,请访问:

https://technet.microsoft.com/en-us/library/hh847746.aspx