3

Powershell 5 says "no way Jose", can't join path with null or empty string. I say why not? Is there a way to get join-path to be more "Flexible" without adding more if-else blocks?

    $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

pico
  • 1,660
  • 4
  • 22
  • 52

2 Answers2

4

Join-Path will not allow $null values or [string]::Empty. You can use Path.Combine Method for that:

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

PS \> [System.IO.Path]::Combine('C:\', 'Documents', "runit.exe")
C:\Documents\runit.exe
Santiago Squarzon
  • 41,465
  • 5
  • 14
  • 37
2

Santiago Squarzon's helpful answer shows you how to work around the inability to pass $null or '' to Join-Path via direct use of a .NET API.

An alternative is to bypass both Join-Path and [System.IO.Path]::Combine() altogether and join the path components manually:

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

The above relies on the fact that both $null and '' (the empty string), when coerced to a Boolean ([bool]), return $false, whereas any nonempty string returns $true. In turn, when used as an array index ([...]), $false maps to index 0, and $true to 1 - see the bottom section of this answer for a summary of PowerShell's to-Boolean conversion rules.


In PowerShell (Core) 7+ you can express this intent more clearly, using ?:, the ternary conditional operator, relying on the fact that both $null and '' also implicitly convert to $false in a Boolean context:

$tool = $mydir + ($mydir ? '\' : '') + "runit.exe"
mklement0
  • 382,024
  • 64
  • 607
  • 775