Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Powershell, get join-path to work with $null and empty string

Tags:

powershell

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

like image 921
pico Avatar asked May 03 '26 19:05

pico


1 Answers

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
like image 122
Santiago Squarzon Avatar answered May 06 '26 21:05

Santiago Squarzon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!