PowerShell: How to Get Relative Path of File


You can use the following syntax in PowerShell to get the relative path of a specific file:

Get-Item coaches\team_info1.txt | Resolve-Path -Relative

This particular example will get the relative path of the file named team_info1.txt located in the subfolder named coaches.

By using the Resolve-Path cmdlet with the -Relative parameter, we’re able to specify that we would like to get the path of a specific file relative to the current directory.

The following example shows how to use this syntax in practice.

Example: How to Get Relative Path of File in PowerShell

Suppose that our current directory has the following path:

  • C:\Users\bobbi\data1

And suppose that we would like to get the relative path of a file named team_info1.txt located in a subfolder named coaches in the current directory.

We can use the following syntax to do so:

Get-Item coaches\team_info1.txt | Resolve-Path -Relative

The following screenshot shows how to use this syntax in practice:

PowerShell get relative path of file

Notice that this returns the relative path of the team_info1.txt file:

  • .\coaches\team_info1.txt

Note that you could also use the following syntax to get the relative path of all files located in the subfolder named coaches in the current directory:

Get-Item coaches\* | Resolve-Path -Relative

The following screenshot shows how to use this syntax in practice:

PowerShell get relative path of all files in subfolder

Notice that this returns the relative path of each file in the subfolder named coaches:

  • .\coaches\team_info1.txt
  • .\coaches\team_info2.txt
  • .\coaches\team_info3.txt

By using the wildcard character ( * ) we are able to reference all files located in the coaches subfolder.

Note: You can find the complete documentation for the Resolve-Path cmdlet in PowerShell here.

Related Tutorials

The following tutorials explain how to perform other common tasks in PowerShell:

PowerShell: How to Use Test-Path to Check Multiple Paths
PowerShell: How to Get File Name from Path
PowerShell: How to Get Last Folder in Path

Leave a Reply