How to use Push-Location and Pop-Location command in PowerShell?


Push-Location command in PowerShell is used to push (add) the current location to the location stack (Last In First Out (LIFO) - queue) while the Pop-Location is to retrieve the last location from the stack.

When the PowerShell console opens there are no locations set to the stack.

PS C:\> Get-Location -Stack
PS C:\>

When you type the Push-Location command it performs two operations at a time. First, it saves the current location to the top of the stack, and second, it browse the path specified. If there is no path specified then it only moves the current location to the stack. For example,

PS C:\> Push-Location
PS C:\> Get-Location -Stack
Path
----
C:\

We will specify the path now,

PS C:\> Push-Location C:\Temp\
PS C:\Temp> Get-Location -Stack
Path
----
C:\
C:\

In the above example, the current location was C:\ so the command pushed it to the stack and it moved to that specified directory. Let say we are pushing one more location to the stack.

PS C:\Temp> Push-Location C:\Temp\iisadministration\
PS C:\Temp\iisadministration> Get-Location -Stack
Path
----
C:\Temp
C:\
C:\

In the above example, C:\Temp was the current location so it is top of the stack. To jump to the last location we need to use the Pop-Location command. For example,

PS C:\Temp\iisadministration> Pop-Location
PS C:\Temp>

When you run the Pop-Location command, the last item (recent item) from the queue is deleted. Let’s check the stack.

PS C:\Temp> Get-Location -Stack
Path
----
C:\
C:\

You can also create a new stack to push the location and then you can retrieve the location using the Pop-Location command from the specific stack. For example,

PS C:\Windows\System32> Push-Location WindowsPowerShell -StackName Stack2
PS C:\Windows\System32\WindowsPowerShell> Get-Location -StackName Stack2
Path
----
C:\Windows\System32

In the above example, we have created a new stack called ‘Stack2’ and pushed a current location there, you can see the location was inserted in the new stack using the Get-Location command for the specific stack.

To retrieve the data from that stack,

PS C:\Windows\System32\WindowsPowerShell> Pop-Location -StackName stack2
PS C:\Windows\System32>

Updated on: 02-Nov-2020

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements