Consider the following situation: I have a parameter, or a config variable, that sets the output directory of a script. Obviously, this parameter should also be able to be absolute:
RepoBackup.ps1 -OutputDirectory .\out
RepoBackup.ps1 -OutputDirectory D:\backup
In the script, I use (Get-Item -Path './').FullName in combination with Join-Path to determine the absolute path of my output directory, because I might need to use Set-Location to change the current directory - which makes working with relative paths complicated.
But:
Join-Path C:\code\ .\out # => C:\code\.\out (which is exactly what i need)
Join-Path C:\code\ D:\ # => C:\code\D:\ (which is not only not what i need, but invalid)
I considered using Resolve-Path and do something like Resolve-Path D:\backup, but if the directory doesn't exist (yet), this yields an error about not being able to find the path.
So, how can I get the absolute path of my $OutputDirectory, accepting both absolute and relative input, as well as paths that don't yet exist?
You can use the .Net Path.Combine method, which does exactly what you want.
[IO.Path]::Combine('C:\code\', '.\out') # => 'C:\code\.\out'
[IO.Path]::Combine('C:\code\', 'D:\') # => 'D:\'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With