Files, paths and providers

PowerShell · Essentials · 10 min

Most automation reads or writes files, and providers let the same cmdlets reach other data stores.

File work uses a small, consistent set of cmdlets: Get-ChildItem (list), Set-Location (cd), New-Item, Copy-Item, Move-Item, Rename-Item, Remove-Item, Test-Path. Their -Path parameter accepts wildcards; use -LiteralPath for names that contain [ or ]. -Recurse walks subdirectories, and -Force includes hidden items or overwrites.

Reading and writing text:

  • Get-Content file returns an array of lines; add -Raw for a single string.
  • Set-Content replaces a file, Add-Content appends, Out-File writes formatted output.
  • In PowerShell 7 the default encoding is UTF-8 without a BOM; specify -Encoding when a tool expects something else.

Build paths with Join-Path and Split-Path instead of string concatenation; on Linux the separator is /, and both cmdlets handle it.

Destructive cmdlets support -WhatIf (show what would happen) and -Confirm (ask first): run Remove-Item -Recurse -WhatIf before the real thing.

The same cmdlets work on other providers, exposed as drives: Env: (environment variables), Variable:, Function:, Alias:, and on Windows HKLM: (the registry) and Cert: (certificates). Get-PSDrive lists them, so Get-ChildItem Env: lists environment variables just like files.

Example

$dir = Join-Path ([IO.Path]::GetTempPath()) 'ps-demo'
New-Item -ItemType Directory -Path $dir -Force | Out-Null
Set-Location $dir
Set-Content -Path notes.txt -Value 'first line'
Add-Content -Path notes.txt -Value 'second line'
Get-Content notes.txt                 # first line / second line
(Get-Content notes.txt).Count         # 2   (an array of lines)
Copy-Item notes.txt backup.txt
Test-Path backup.txt                  # True
Get-ChildItem -Filter *.txt | Select-Object -ExpandProperty Name   # backup.txt notes.txt
Remove-Item backup.txt -WhatIf        # What if: Performing the operation "Remove File" ...
Split-Path (Join-Path $dir 'notes.txt') -Leaf   # notes.txt
Get-ChildItem Env: | Select-Object -First 2 Name   # environment as a drive

Remember

  • Get-ChildItem, Copy-Item, Remove-Item and friends work on any provider
  • Get-Content returns lines; -Raw returns one string
  • Join-Path for paths, -WhatIf before destructive commands

Watch out for

  • Concatenating paths with '\' in scripts that must also run on Linux or macOS.

Check yourself

  1. What does `Get-Content log.txt` return for a 3-line file?
  2. What is `-WhatIf` for?

Sign in to answer, see the explanations, and get this lesson back as a quick review later.

Official docs: learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_providers