PowerTip: Use PowerShell to Help Build Paths

PowerTip: Use PowerShell to Help Build Paths

  • Comments 7
  • Likes

Summary: Use Windows PowerShell to build a path to the system32 directory.

Hey, Scripting Guy! Question I need to build a path to the Windows\system32 directory. How can I do this?

 

Hey, Scripting Guy! Answer Join-Path -path (get-item env:\windir).value -ChildPath system32

Your comment has been posted.   Close
Thank you, your comment requires moderation so it may take a while to appear.   Close
Leave a Comment
  • hi ed,

    here some variant:

    PS II> [Environment]::SystemDirectory

    PS II> [IO.Path]::Combine($env:SystemRoot,'system32')

    PS II> $PSHOME -replace '\\WindowsPowerShell.+$'

    PS II> "${env:windir}\system32"

  • Join-Path is the best PowerShell tool for this. Although in this particular example I'm always puzzled why people don't use syntax like this:

    join-path $env:windir system32

  • @Jeff -Because...

    This can be done in one line:

    & "$env:windir\system32\notepad.exe"

    Join path would take more typing.

  • jrv,

    That's a slightly different issue. I think the real point to this question is to use Join-Path instead of concatentation. I see many people try to do this:

    $a="c:\foo"

    $b="data"

    $f=$a + $b

    or this, which isn't necessarily that bad

    $f="$a\$b"

    But you have to pay close attention to things like slashes.  Join-Path is more forgiving

    '

    join-path $a $b

    Plus Join-Path has a nice parameter, -Resolve, so you can verify the path exists. The best practice should be to use cmdlets where possible.

  • @jeff

    I don't disagree however there are many times when it is not truly necesary.  If we are using variables that may be gatherd up along the way then I completely agree as the CmdLet does give extra error gurading and does eliminate the issue of slashes.

    19:49 PS>$a='c:\'

    19:49 PS>$b='\test\'

    19:49 PS>"$a\$b"

    c:\\\test\

    19:49 PS>join-path $a $b

    c:\test\

  • jrv,

    Agreed exceptions abound. If I know without a doubt all the components, I'm not adverse to an expression like this:

    dir $env:windir\system32

    But when building paths where you might not know the exact value ahead of time, Join-Path is a safer approach.

  • @Walid Toumi Great suggestions. Thanks.

    @Jeff Hicks The reason for my "example" is to simply show people some of the cool things that can be done, AND to stimulate discussion. I really DO like using JOIN-PATH however, because it really is safer.

    @JRV yes you can concatenate, and I do it sometimes, but really I am moving away from it because it is easy to mess up, AND it is hard to read, which also means it is hard to troubleshoot.