【问题标题】:How to test for an invalid path in powershell?如何在powershell中测试无效路径?
【发布时间】:2013-04-09 11:01:34
【问题描述】:

我有一个脚本尝试使用相对路径运行某些可执行文件。
所以我使用test-path 来验证可执行文件是否在它应该在的位置。 如果没有,我尝试其他位置。

if(test-path "$current../../../myexe.exe"){
   # found it!
}

但在这种情况下,如果 $current 是 C:/folder/,那么 test-path "C:/folder/../../../myexe.exe" 会失败并显示

路径 ... 引用了基础 'C:' 之外的项目

是否有一种干净而可靠的方法来测试路径,以便它返回真或假,并且不会给我带来一些意外错误?

【问题讨论】:

    标签: powershell path


    【解决方案1】:
    Test-Path ([io.path]::Combine($current,(Resolve-Path ../../../myexe.exe)))
    

    更多信息请见this thread

    【讨论】:

    • 我刚刚开始工作,我使用了 [IO.File]::Exists() 我认为 Resolve-Path 会抛出相同类型的异常
    • 我不会更改进程工作目录,leeholmes.com/blog/2006/06/26/…
    • 有趣,那么我应该使用 [IO.Path]::GetFullPath("$pwd\..\..\myexe.exe") 来避免解析路径的异常,然后File.Exists 避免测试路径异常
    • 您可以使用 Test-Path 代替 .net 类。
    • 嗯,没错,因为在这种情况下,GetFullPath 会处理有问题的异常。
    【解决方案2】:

    我使用 .NET File.Exists 让它工作,但如果你想正确解析相对路径,你必须先设置 Environment.CurrentDirectory

    编辑:在 Shay Levy 指出 CurrentDirectory 对其他后台进程可能是危险的之后不更改(请参阅 http://www.leeholmes.com/blog/2006/06/26/current-working-directory-with-powershell-and-net-calls/

     [环境]::CurrentDirectory = $pwd

    [System.IO.File].Exists("$pwd\$invalidRelativePath")
    False
    

    【讨论】:

      【解决方案3】:

      测试路径从根本上被破坏了。

      SilentlyContinue都坏了:

      Test-Path $MyPath -ErrorAction SilentlyContinue 
      

      如果 $MyPath 为 $null、空或不作为变量存在,这仍然会爆炸。

      如果 $MyPath 只是一个空格,它甚至会返回 $true。那个“”文件夹到底在哪里!

      以下是适用于以下情况的解决方法:

      $MyPath = "C:\windows"  #Test-Path return $True as it should
      $MyPath = " "       #Test-Path returns $true, Should return $False
      $MyPath = ""        #Test-Path Blows up, Should return $False
      $MyPath = $null      #Test-Path Blows up, Should return $False
      Remove-Variable -Name MyPath -ErrorAction SilentlyContinue  #Test-Path Blows up, Should return $False
      

      解决方案在于当 Test-Path 想要炸毁时,强制它返回 $False。

      if ( $(Try { Test-Path $MyPath.trim() } Catch { $false }) ) {  #Returns $false if $null, "" or " "
          write-host "path is GOOD"
      } Else {
          write-host "path is BAD"
      }
      

      【讨论】:

        【解决方案4】:

        你应该使用 Resolve-Path 或 Join-Path

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-07-09
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多