Change the Working Directory in PowerShell

Marion Paul Kenneth Mendoza Jan 03, 2023 Dec 13, 2021
Change the Working Directory in PowerShell

Many standard Command Prompt (CMD) commands work in the Windows PowerShell environment. The PowerShell environment carries these commands forward from the most basic commands like ping to the most utilized commands like ipconfig from the legacy environment using aliases.

One example of a CMD command that still works with Windows PowerShell is the change directory command or cd and chdir.

Though we can use the legacy command cd and chdir inside Windows PowerShell, it is better to use its PowerShell cmdlet Set-Location in specific situations for proper and cleaner code construction.

Use the Set-Location Cmdlet to Change the Working Directory in PowerShell

The Set-Location cmdlet similarly sets the working directory to a specified location like its legacy counterpart cd and chdir. The slight difference of this cmdlet from the legacy commands is that the Set-Location cmdlet will conveniently change both the working drive and directory simultaneously in which CMD.EXE cannot do.

If we need to change our working directory to another drive in Command Prompt, we still need to enter the <drive letter>: first, then initiate our cd and chdir commands to change the working directory path.

Command Prompt:

C:\> cd C:\Temp
C:\Temp> cd D:\Docs
#To change the working drive, type the drive letter
C:\Temp> D:


PS C:\> Set-Location C:\Temp
PS C:\Temp> Set-Location D:\Docs
PS D:\Docs>

The Set-Location cmdlet also differentiates itself from its legacy command because of additional parameters.

Here are some examples below.

Set-Location -Path C:\Temp

On the example snippet above, the -Path parameter will specify the new working directory of our scripting environment. However, if your path has spaces, remember to enclose them with single ('') or double ("") quotation marks.

Set-Location -Path "C:\Temp\Temporary Documents"

Another helpful parameter inside the Set-Location cmdlet is the -PassThru parameter. This parameter will return the new working directory that we can use to store the returned value to a variable.

Example Code:

$newDir = Set-Location -Path C:\Temp -PassThru
Write-Output $newDir.path



You can also only access the complete properties list of the Set-Location cmdlet if only you have the -PassThru parameter.

Example Code:

Set-Location -Path G: -PassThru | fl *


Drive        : G
Provider     : Microsoft.PowerShell.Core\FileSystem
ProviderPath : G:\
Path         : G:\

Lastly, aside from cd and chdir, Windows PowerShell also uses sl as another alias for Set-Location. You may use this for a faster and smoother scripting approach.

sl -Path C:\Temp
Marion Paul Kenneth Mendoza avatar Marion Paul Kenneth Mendoza avatar

Marion specializes in anything Microsoft-related and always tries to work and apply code in an IT infrastructure.


Related Article - PowerShell Directory