【问题标题】:In Powershell, get join-path to work with $null and empty string在 Powershell 中,获取连接路径以使用 $null 和空字符串
【发布时间】:2021-11-02 22:37:36
【问题描述】:

Powershell 5 说“no way Jose”,不能加入带有 null 或空字符串的路径。我说为什么不呢?有没有办法在不添加更多 if-else 块的情况下让 join-path 更加“灵活”?

    $its_in_the_path = $true
    #$its_in_the_path = $false

    if ($its_in_the_path) {
        $mydir = ""
    }
    else {
        $mydir "C:\tool\path  
    }

    $tool = join-path $mydir "runit.exe"
Cannot bind argument to parameter 'Path' because it is an empty string.
daskljdhgfaklsuhfalhfluwherfluqwhrluq2345214723452345h2kjrwefqy345
At + ~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidData: (:) [frunsim], ParameterBindingValidationException
    + FullyQualifiedErrorId : ParameterArgumentValidationErrorEmptyStringNotAllowed,frunsim

【问题讨论】:

    标签: powershell


    【解决方案1】:

    Join-Path 将不允许 $null 值或 [string]::Empty。您可以为此使用Path.Combine Method

    PS \> [System.IO.Path]::Combine($null, "runit.exe")
    runit.exe
    
    PS \> [System.IO.Path]::Combine('C:\', 'Documents', "runit.exe")
    C:\Documents\runit.exe
    

    【讨论】:

      【解决方案2】:

      Santiago Squarzon's helpful answer 向您展示了如何解决无法通过直接使用 .NET API 将 $null'' 传递给 Join-Path 的问题。

      另一种方法是完全绕过Join-Path[System.IO.Path]::Combine() 并手动加入路径组件:

      $tool = $mydir + ('', '\')[[bool] $mydir] + "runit.exe"
      

      以上依赖于这样一个事实:$null''(空字符串)在强制转换为布尔值 ([bool]) 时返回 $false,而任何 非空字符串返回$true。反过来,当用作数组索引 ([...]) 时,$false 映射到索引0$true 映射到1 - 请参阅this answer 的底部以了解PowerShell 到布尔转换规则的总结。


      PowerShell (Core) 7+ 中,您可以更清楚地表达此意图,使用 ?:ternary conditional operator,这取决于 $null'' 也 隐式在布尔上下文中转换为$false

      $tool = $mydir + ($mydir ? '\' : '') + "runit.exe"
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-05-13
        • 1970-01-01
        • 2023-03-18
        • 1970-01-01
        • 2011-06-23
        • 1970-01-01
        • 1970-01-01
        • 2017-03-15
        相关资源
        最近更新 更多