powershellpathfilepath

Defining path to a file with $PSScriptRoot


This is not exactly asking for help, more like kind of curiosity. I have a path to a file defined like this in my script:

$RootDir = $PSScriptRoot
$ExcelFile = $RootDir + "\" + $File + ".xlsx"

The $File variable is defined earlier in the script. This version works perfectly fine, but when I tried to simplify it like this to a single row, it didn't work:

$ExcelFile = $PSScriptRoot + "\" + $File + ".xlsx"

Any idea why the second version does not work? It says that the file could not be found. I can't see any logical reason for it.


Solution

  • For building paths use the Join-Path cmdlet:

    $ExcelFile = Join-Path $PSScriptRoot ($File + '.xlsx')
    

    In your particular case you could also go with a simple string with variables:

    $ExcelFile = "${PSScriptRoot}\${File}.xlsx"
    

    But Join-Path is the more resilient approach, because it automatically takes care of the path separator between the elements.