【问题标题】:PowerShell - Capture output of svn.exe callPowerShell - 捕获 svn.exe 调用的输出
【发布时间】:2014-12-16 16:07:09
【问题描述】:

我正在使用 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 选项 C:\dev\Temp\script.ps1:30 字符: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,即使没有基本的错误处理,自动化的效果如何?

【问题讨论】:

    标签: powershell svn error-handling automation powershell-4.0


    【解决方案1】:

    几个简单的选项,取决于你想做什么。

    如果要捕获命令的输出,请使用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 对象来获得对流程执行的更多控制。

    【讨论】:

      【解决方案2】:

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

      以下是最终脚本如何检查当前 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

      【讨论】:

        猜你喜欢
        • 2012-05-10
        • 2018-05-01
        • 2018-04-27
        • 1970-01-01
        • 2022-11-30
        • 2010-10-29
        • 2018-06-09
        • 1970-01-01
        • 2018-11-28
        相关资源
        最近更新 更多