Powershell: Support Question - Best practice for cross-platform paths

Created on 23 Jun 2019  路  3Comments  路  Source: PowerShell/PowerShell

Support Question

If I'm on *nix, my paths use /; if I'm on Windows, my paths use \. This isn't much of an issue, as I believe it mostly only affects aesthetics of printed paths. What is the best practice for maintaining consistent path output cross-platform?

Possibly related--
If I'm on *nix, my PATHs use : delimeters; if I'm on Windows, my PATHs use ; delimiters. Would a similar strategy apply?

Issue-Question Resolution-Answered

All 3 comments

You have a couple options. One is to just avoid dealing with paths directly, and always use Joi-Path and Split-Path as needed. I tend to do this a fair bit.

Another option is to use a variable separator, for example the slash for paths on the current system is exposed in [System.IO.Path]::DirectorySeparatorChar so you can just define a variable like ${/} = [IO.Path]::DirectorySeparatorChar and just use that variable to insert platform appropriate slashes.

With respect to PATH separators, a similar thing applies; you can pull the appropriate character frow [System.IO.Path]::PathSeparator

Also, where slashes are concerned you can often cheat a bit and just always use forward slashes in a lot of cases. Windows filesystems don't care which slash you want to use, but Unix only recognises forward slash, so you could opt to just always use forward slashes.

The simple answer is:

  • Always use forward slashes / -- Windows is more forgiving.
  • Always Convert-Path when passing paths to applications -- PowerShell's PSDrives result in paths that aren't real (e.g. the new Temp: drive in PS7)

Thanks all

Was this page helpful?
0 / 5 - 0 ratings