Get relative path of files/subfolders from the current directory in PowerShell

Sometimes you would need to get relative path of files/subfolders from current directory in PowerShell. For example, you are inside the folder called C:\Scripts and it contains a folder called prod and it contains further a script called wfmbackup.ps1. Then instead of getting absolute path like C:\Scripts\prod\wfmbackup.ps1, you just want to get relative path which is .\prod\wfmbackup.ps1.

This can be done using Resolve-Path cmdlet with -Relative parameter. For example, for our analogy we can use below commands:

Set-Location C:\Scripts
 $relativePath = Get-Item prod\wfmbackup.ps1 | Resolve-Path -Relative

You can also use Get-ChildItem -Recurse and pass output to Resolve-Path cmdlet and get the whole relative tree structure.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s