I tend to use PowerShell Core on both macOS and Windows so whenever a script of mine needs to refer to some file (like a certificate in the example below) I usually have a snippet like this:
1 2 3 4 5 |
if ($PSVersionTable.OS -match "Windows") { $appCert = "$($Global:CertPath)\${certName}.pfx" } else { $appCert = "$($Global:CertPath)/${certName}.pfx" } |
The only thing the above does is use \
or /
in the path depending on the OS.
Then I realized I could shorten it a bit coz PowerShell has the $IsWindows
, $IsMacOS
, $Linux
variables so I started using the following instead:
1 2 |
if ($IsWindows) { $pathSeparator = "\" } else { $pathSeparator = "/" } $appCert = "$($Global:CertPath)${$pathSeparator}${certName}.pfx" |
Today I came across a different method thanks to this blog post: Tips for Writing Cross-Platform PowerShell Code. Use Join-Path
. Hence I can do:
1 2 3 4 |
Join-Path -Path $Global:CertPath -ChildPath "${certName}.pfx" # Or the shorter version Join-Path $Global:CertPath "${certName}.pfx" |
I also learnt from there of the [IO.Path]::DirectorySeparatorChar
property:
1 |
$Global:CertPath + [IO.Path]::DirectorySeparatorChar + "${certName}.pfx" |
More interesting stuff in that blog post above btw so check it out!