Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get the absolute path based on either relative or absolute paths in PowerShell?

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?

like image 317
sk22 Avatar asked Oct 29 '25 15:10

sk22


1 Answers

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:\'
like image 118
Steve Avatar answered Oct 31 '25 12:10

Steve



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!