🎓 A1Learner
🔍
0 of 52 lessons completed

PowerShell Working Directory

The working directory is the folder the shell currently looks in. Get-Location is the cmdlet that reports it, and Set-Location moves it to another folder.

Move into a folder you created

Create a folder named reports, move into it, and print only its last path part. The printed name is reports, not a full path.

Set-Location -Path $PSScriptRoot
$null = New-Item -ItemType Directory -Path "reports"
Set-Location -Path "reports"
Split-Path -Leaf (Get-Location).Path

Return with Push-Location and Pop-Location

Push-Location remembers where you were, and Pop-Location takes you back. Test-Path then proves the reports folder is still there.

Set-Location -Path $PSScriptRoot
$null = New-Item -ItemType Directory -Path "reports"
Push-Location -Path "reports"
Split-Path -Leaf (Get-Location).Path
Pop-Location
Test-Path "reports"

Create a file in the new folder

After moving into reports, a file created there lives inside it. Moving back up lets you read it by its folder and name.

Set-Location -Path $PSScriptRoot
$null = New-Item -ItemType Directory -Path "reports"
Set-Location -Path "reports"
Set-Content -Path "note.txt" -Value "weekly"
Set-Location -Path ".."
Get-Content -Path "reports/note.txt"

Example

Set-Location -Path $PSScriptRoot
$null = New-Item -ItemType Directory -Path "projects"
Set-Location -Path "projects"
Set-Content -Path "plan.txt" -Value "launch"
Split-Path -Leaf (Get-Location).Path
Get-Content -Path "plan.txt"
Set-Location -Path ".."
Test-Path "projects/plan.txt"

Key points

  • Get-Location: the cmdlet that reports the current working directory.
  • Set-Location: the cmdlet that moves the working directory to another folder.
  • Push-Location: the cmdlet that remembers the current folder before moving.
  • Pop-Location: the cmdlet that returns to the folder Push-Location remembered.
  • Split-Path: the cmdlet that keeps only the last part of a path, such as a folder name.

In this example, a projects folder is created and entered, and a plan file is written inside it. The folder name and the file content are printed, then the shell moves back up and Test-Path confirms the file is still in projects.

Note

print only the last part of a path, never a full path, because full paths differ on every machine.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

Which cmdlet moves the working directory into a folder named reports?