Providers, Drives, Aliases, and Native Commands
How PowerShell aliases differ across platforms, how providers expose the environment, registry and certificates as drives, and how to run native programs safely.
By The Dark DebuggerUpdated 23 min read
This article covers three things that decide whether a PowerShell script behaves the same
on your machine and on the next one: aliases, providers (the mechanism behind Env:,
HKLM: and Cert:), and native programs such as git, tar or terraform. You should
know cmdlets and parameters, the
pipeline and the operators
from the previous articles, especially & and splatting.
Examples were run in PowerShell 7.6.9 on Linux unless they are marked as Windows PowerShell 5.1. The registry and certificate examples only exist on Windows.
Why this matters
A script that works on your laptop fails in CI. The usual causes are in this article:
- It used
ls,sortorcurl, which are PowerShell aliases on Windows PowerShell 5.1 and completely different programs on Linux. - It read
$env:Path, which is$env:PATHon Linux, where environment variable names are case-sensitive. - It ran
terraform fmt -checkand carried on happily when the check failed, because a native program's non-zero exit code does not stop a PowerShell script.
Each of these is cheap to avoid once you know how the pieces work.
Aliases
An alias is an alternative name for a command. PowerShell ships with short aliases for the cmdlets you type most:
Get-Alias gci, gc, select, '%', '?' | Format-Table Name, Definition -AutoSize
Name Definition
---- ----------
gci Get-ChildItem
gc Get-Content
select Select-Object
% ForEach-Object
? Where-Object
% ForEach-Object
h Get-History
r Invoke-History
Look at the last three rows. Get-Alias treats its argument as a wildcard pattern, and ?
is the "any single character" wildcard, so '?' matched every one-letter alias. Search in
the other direction with -Definition to find the aliases of a command:
Get-Alias -Definition Get-ChildItem | Format-Table Name, Definition -AutoSize
Name Definition
---- ----------
dir Get-ChildItem
gci Get-ChildItem
Aliases differ by platform and version
That list is from Linux. On Windows, Get-ChildItem also has the alias ls. PowerShell
on Linux and macOS deliberately does not define aliases that would hide the system's own
programs:
Get-Alias lsGet-Alias: This command cannot find a matching alias because an alias with the name 'ls' does not exist.Get-Command ls, cat, sort, rm, ps, kill | Format-Table CommandType, Name, Source -AutoSize
CommandType Name Source
----------- ---- ------
Application ls /usr/bin/ls
Application cat /usr/bin/cat
Application sort /usr/bin/sort
Application rm /usr/bin/rm
Application ps /usr/bin/ps
Application kill /usr/bin/kill
Windows PowerShell 5.1 goes the other way. I ran this on the Windows host:
Get-Alias ls, curl, wget, sc, where, sort | Format-Table Name, Definition -AutoSize
Name Definition
---- ----------
ls Get-ChildItem
curl Invoke-WebRequest
wget Invoke-WebRequest
sc Set-Content
where Where-Object
sort Sort-Object
Every one of those has bitten someone:
curlandwgetin 5.1 areInvoke-WebRequest, so curl's options do not work. Mycurl --versionproducedcurl : The remote name could not be resolved: '--version': it treated the option as a host name. Typecurl.exeto get the real curl that ships with Windows 10 and 11. PowerShell 6 and later removed both aliases; my Linux 7.6.9 session has neither.scin 5.1 isSet-Content, sosc queryfrom an old batch-file habit writes a file namedqueryinstead of listing services. Usesc.exe.whereisWhere-Objecteverywhere. The Windows equivalent ofwhichiswhere.exe.
Even the number of aliases differs: (Get-Alias).Count returned 108 in PowerShell 7.6.9 on
Linux and 158 in Windows PowerShell 5.1.
When an alias name is also a program
Here is what an alias habit from Windows does on Linux. sort is no longer Sort-Object; it
is GNU sort, which receives text and treats CPU as a file name:
$services = @(
[pscustomobject]@{ Name = 'nginx'; CPU = 12.5 }
[pscustomobject]@{ Name = 'postgres'; CPU = 3.1 }
[pscustomobject]@{ Name = 'redis'; CPU = 40.2 }
)
$services | sort CPU/usr/bin/sort: cannot read: CPU: No such file or directoryWith the full cmdlet name it works on every platform:
$services | Sort-Object CPU
Name CPU
---- ---
postgres 3.10
nginx 12.50
redis 40.20
Command precedence
When a name could mean several things, PowerShell picks in this order: alias, function,
cmdlet, external program. Get-Command -All shows every candidate:
Get-Command echo -All | Format-Table CommandType, Name, Definition -AutoSize
CommandType Name Definition
----------- ---- ----------
Alias echo Write-Output
Application echo /usr/bin/echo
Application echo /bin/echo
echo runs Write-Output. To run the program, give its path (/usr/bin/echo) or, on
Windows, its extension (where.exe, curl.exe, sc.exe).
Creating your own aliases
Set-Alias creates or changes an alias for the current session (put it in your profile to
keep it):
Set-Alias -Name tf -Value terraform
tf version
Get-Alias tf | Format-Table Name, Definition -AutoSizeTerraform v1.17.1
on linux_amd64
Name Definition
---- ----------
tf terraform
An alias is only a name. It cannot carry parameters:
Set-Alias -Name ll -Value 'Get-ChildItem -Force'
llll: The term 'Get-ChildItem -Force' is not recognized as a name of a cmdlet, function, script file, or executable program.
Check the spelling of the name, or if a path was included, verify that the path is correct and try again.Write a function instead. @args passes along whatever else you type:
function ll { Get-ChildItem -Force @args }
ll ./logs -Nameapp.log
app.log.1Aliases belong at the prompt, not in scripts
Aliases are great for typing and bad for reading. In scripts, use full command names and
full parameter names: the script stays readable for the next person, and it does not change
meaning when it runs on a different platform or PowerShell version, as sort, curl and ls
just showed. The PSScriptAnalyzer linter flags aliases in scripts for exactly this reason
(rule PSAvoidUsingCmdletAliases).
Providers and drives
A provider makes a data store look like a file system, so the same cmdlets
(Get-ChildItem, Get-Item, New-Item, Remove-Item, Test-Path, Get-Content) work on
it. Each provider exposes one or more drives. In PowerShell 7.6.9 on Linux:
Get-PSProvider
Name Capabilities Drives
---- ------------ ------
Alias ShouldProcess {Alias}
Environment ShouldProcess {Env}
FileSystem Filter, ShouldProcess, Crede… {/, Temp}
Function ShouldProcess {Function}
Variable ShouldProcess {Variable}
Get-PSDrive
Name Used (GB) Free (GB) Provider Root
---- --------- --------- -------- ----
/ 55.75 951.11 FileSystem /
Alias Alias
Env Environment
Function Function
Temp 55.75 951.11 FileSystem /tmp/
Variable Variable
Temp: is a PowerShell 7 convenience that points at the system temp directory (in Windows
PowerShell 5.1, Get-PSDrive Temp fails with Cannot find drive). On Windows,
Windows PowerShell 5.1 adds the Registry and Certificate providers:
Get-PSDrive -PSProvider Registry, Certificate, Environment, Variable | Format-Table Name, Provider, Root -AutoSize
Name Provider Root
---- -------- ----
Cert Microsoft.PowerShell.Security\Certificate \
Env Microsoft.PowerShell.Core\Environment
HKCU Microsoft.PowerShell.Core\Registry HKEY_CURRENT_USER
HKLM Microsoft.PowerShell.Core\Registry HKEY_LOCAL_MACHINE
Variable Microsoft.PowerShell.Core\Variable
(When I ran Get-PSProvider first in a fresh 5.1 session, Certificate was missing from the
list. It belongs to the Microsoft.PowerShell.Security module, which loads the first time you
use it.)
Get-Item returns a different .NET type depending on the provider, but the cmdlet is the same:
(Get-Item ./logs).GetType().Name
(Get-Item Env:HOME).GetType().Name
(Get-Item Variable:PSVersionTable).GetType().Name
(Get-Item Alias:gci).GetType().Name
(Get-Item Function:prompt).GetType().NameDirectoryInfo
DictionaryEntry
PSVariable
AliasInfo
FunctionInfoEnv: environment variables
$env:NAME is shorthand for the Env: drive. The drive form is useful for listing,
wildcards and existence tests:
Get-ChildItem Env: | Where-Object Name -like 'POWERSHELL*'
$env:POWERSHELL_UPDATECHECK
Test-Path Env:CI
Name Value
---- -----
POWERSHELL_TELEMETRY_OPTOUT 1
POWERSHELL_UPDATECHECK Off
Off
FalseTest-Path Env:CI is the standard "am I running in a CI system?" check; most CI services set
CI. Creating and removing variables works like files:
$env:DEPLOY_COLOR = 'blue'
Get-Item Env:DEPLOY_COLOR
Remove-Item Env:DEPLOY_COLOR
Test-Path Env:DEPLOY_COLOR
Name Value
---- -----
DEPLOY_COLOR blue
FalseChanges made this way last for the current process and any program it starts. They do not change the user's or machine's persistent environment.
On Linux and macOS, environment variable names are case-sensitive, even in PowerShell:
$env:HOME
$env:home
"[$env:Home]"/home/sid
[]On Windows they are not, which is how $env:Path sneaks into scripts that later fail on a
Linux build agent. Use the canonical spelling (PATH, HOME) everywhere.
Variable:, Function: and Alias:
PowerShell's own variables, functions and aliases are drives too. The main practical use is
Test-Path, which checks whether something exists without triggering strict-mode errors:
$deployTarget = 'staging'
Get-Item Variable:deployTarget
Test-Path Variable:deployTarget
Test-Path Variable:notDefined
Get-ChildItem Variable:PS* | Select-Object -First 4 -ExpandProperty Name
Name Value
---- -----
deployTarget staging
True
False
PSDefaultParameterValues
PSStyle
PSEmailServer
PSSessionOptionThe Function: drive lets you list, read and delete functions. ${function:Name} is the
variable-style shortcut that returns the function's body:
function Get-DeployTarget { 'staging' }
(Get-ChildItem Function:*Deploy*).Name
${function:Get-DeployTarget}
Remove-Item Function:Get-DeployTarget
Get-DeployTargetGet-DeployTarget
'staging'
Get-DeployTarget: The term 'Get-DeployTarget' is not recognized as a name of a cmdlet, function, script file, or executable program.
Check the spelling of the name, or if a path was included, verify that the path is correct and try again.And the Alias: drive answers "which aliases point at this command?" with ordinary filtering:
Get-ChildItem Alias: | Where-Object Definition -eq 'Where-Object' | Format-Table Name, Definition -AutoSize
Name Definition
---- ----------
? Where-Object
where Where-Object
The registry: HKLM: and HKCU: (Windows only)
The registry provider maps HKEY_LOCAL_MACHINE to HKLM: and HKEY_CURRENT_USER to
HKCU:. The one idea to get right: keys are items, values are item properties. You
navigate keys with Get-ChildItem and Get-Item, and read values with Get-ItemProperty.
These ran in Windows PowerShell 5.1 on a Windows 11 machine:
Get-ItemProperty 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion' |
Select-Object ProductName, DisplayVersion, CurrentBuild, EditionID
ProductName DisplayVersion CurrentBuild EditionID
----------- -------------- ------------ ---------
Windows 10 Home 26H2 26300 CoreYes, a Windows 11 machine reports Windows 10 Home in ProductName; Microsoft never updated
that value. Inventory scripts should use CurrentBuild (22000 and above is Windows 11)
rather than trusting the name. For a single value, Get-ItemPropertyValue skips the object:
Get-ItemPropertyValue 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion' -Name CurrentBuild
(Get-Item 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion').GetType().Name
(Get-Item 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion').ValueCount26300
RegistryKey
32Two checks that appear in real patching and audit scripts: how a service is configured
(Start 2 is automatic, 3 manual, 4 disabled), and whether Windows is waiting for a reboot:
Get-ItemProperty HKLM:\SYSTEM\CurrentControlSet\Services\W32Time |
Select-Object DisplayName, Start, ImagePath | Format-List
Test-Path 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Component Based Servicing\RebootPending'
DisplayName : @%SystemRoot%\system32\w32time.dll,-200
Start : 3
ImagePath : C:\WINDOWS\system32\svchost.exe -k LocalService
FalseWriting uses the same item cmdlets. I did not run the following on the test machine, because it modifies the registry; it is here so you can see the shape:
# Not executed: creates a key and a value under HKCU, changes it, then deletes the key
$key = 'HKCU:\Software\ShellragDemo'
New-Item -Path $key -Force | Out-Null
New-ItemProperty -Path $key -Name DeployRing -Value 'canary' -PropertyType String -Force | Out-Null
Set-ItemProperty -Path $key -Name DeployRing -Value 'broad'
Get-ItemPropertyValue -Path $key -Name DeployRing
Remove-Item -Path $key -RecurseHKCU: changes need no elevation; anything under HKLM: needs an elevated session. Test
registry writes with -WhatIf first.
Certificates: Cert: (Windows only)
The certificate provider exposes the Windows certificate stores as
Cert:\<CurrentUser|LocalMachine>\<store>. Each certificate is an X509Certificate2 object
with Subject, NotAfter, Thumbprint and so on. Again in Windows PowerShell 5.1, against the
trusted root store:
(Get-ChildItem Cert:\LocalMachine\Root).Count
Get-ChildItem Cert:\LocalMachine\Root | Sort-Object NotAfter |
Select-Object -First 3 NotAfter, Subject | Format-Table -AutoSize
@(Get-ChildItem Cert:\LocalMachine\Root -ExpiringInDays 365).Count66
NotAfter Subject
-------- -------
12/30/1999 6:59:59 PM OU=Copyright (c) 1997 Microsoft Corp., OU=Microsoft Time Stamping Service Root, OU=Microsoft C...
12/31/1999 6:59:59 PM CN=Microsoft Authenticode(tm) Root Authority, O=MSFT, C=US
1/7/2004 6:59:59 PM OU="NO LIABILITY ACCEPTED, (c)97 VeriSign, Inc.", OU=VeriSign Time Stamping Service Root, OU="...
2-ExpiringInDays is a parameter the certificate provider adds to Get-ChildItem. Pointed at
Cert:\LocalMachine\My on a web server, the same line is the core of a "certificates
expiring this month" alert. (Those ancient root certificates are kept on purpose, for
verifying old timestamped signatures.)
Your own drives with New-PSDrive
New-PSDrive creates a shortcut drive for any provider path. It is handy for long paths in
interactive work and for scripts that should not hard-code a location:
New-PSDrive -Name Logs -PSProvider FileSystem -Root ./logs | Out-Null
Get-ChildItem Logs: -Name
Get-Content Logs:/app.log
Remove-PSDrive Logs
Test-Path Logs:app.log
app.log.1
2026-11-09 08:00:01 INFO service started
2026-11-09 08:09:41 ERROR timeout calling bank-gateway
FalseThese drives exist only in PowerShell and only for the session (or the scope that created
them). Native programs cannot see Logs:, so pass them real paths. On Windows,
New-PSDrive -Persist with a UNC root maps a real network drive letter that other programs
can use; I did not test that here.
Running native commands
Anything on your PATH that is not a PowerShell command runs as a native program, the same
way it would in Bash or cmd. Get-Command shows these as Application. The differences from
cmdlets are what this section is about: native programs return text, report failure
through an exit code, and receive arguments as strings that PowerShell has to quote
for them.
Output is an array of strings
PowerShell captures native output line by line. One line gives you a string, several lines give you an array of strings:
$kernel = uname -s
$kernel
$kernel.GetType().Name
$listing = ls -1 ./logs
$listing.GetType().Name
$listing.Count
$listing[1]Linux
String
Object[]
2
app.log.1When you need one block of text (to search across lines, or to put in an email), join it
yourself. Casting to [string] joins with spaces, which is rarely what you want:
$listing = ls -1 ./logs
[string]$listing
$listing -join "`n"
($listing | Out-String).GetType().Nameapp.log app.log.1
app.log
app.log.1
StringNumbers come back as strings too. grep -c prints a count, and you must convert it before
doing arithmetic or numeric comparisons (see the left-operand rule in
the operators article):
$found = grep -c ERROR ./app.log
$found
$found.GetType().Name
[int]$found + 11
String
2Exit codes: $LASTEXITCODE and $?
Every native program exits with a number; 0 means success. PowerShell stores it in
$LASTEXITCODE, and sets $? to $false when it is not 0:
grep -q 'ERROR' ./app.log
$LASTEXITCODE
grep -q 'CRITICAL' ./app.log
$?
$LASTEXITCODE0
False
1$? describes the last statement, whatever it was, so read it immediately. Look what
happens if you check $LASTEXITCODE first:
grep -q 'CRITICAL' ./app.log
$LASTEXITCODE
$?1
True$? is now True because displaying $LASTEXITCODE succeeded. In scripts, use
$LASTEXITCODE; it keeps its value until the next native program runs.
A failing program does not stop your script
$ErrorActionPreference = 'Stop' makes cmdlet errors terminate a script. It does not apply to
native exit codes by default:
$ErrorActionPreference = 'Stop'
ls /nonexistent
'script kept going'/usr/bin/ls: cannot access '/nonexistent': No such file or directory
script kept goingPowerShell 7.4 and later have a switch for this. With
$PSNativeCommandUseErrorActionPreference set to $true, a non-zero exit code becomes an
error that honours $ErrorActionPreference:
$ErrorActionPreference = 'Stop'
$PSNativeCommandUseErrorActionPreference = $true
ls /nonexistent
'script kept going'/usr/bin/ls: cannot access '/nonexistent': No such file or directory
NativeCommandExitException: Program "ls" ended with non-zero exit code: 2 (0x02).
script kept goingThe NativeCommandExitException is now a real error. The last line still ran here only because
each line was typed at a prompt; in a script, execution stops at the failing command. That is
the behaviour you want in CI. Error handling in general (including try/catch around native
calls) is covered in Error Handling. Windows PowerShell
5.1 has no such switch: check $LASTEXITCODE after every call that matters.
Standard error
By default a program's standard error goes straight to the console and is not captured. 2>&1
merges it into the output, where each stderr line arrives as an ErrorRecord rather than a
string, so you can tell them apart:
$result = ls -d /etc /nonexistent 2>&1
$result | ForEach-Object { '{0,-12} {1}' -f $_.GetType().Name, $_ }String /etc
ErrorRecord /usr/bin/ls: cannot access '/nonexistent': No such file or directory2>$null discards it. The exit code is still there for you to check:
$dirs = ls -d /etc /nonexistent 2>$null
$dirs
$LASTEXITCODE/etc
2How arguments are passed: $PSNativeCommandArgumentPassing
PowerShell parses your command line, then builds the argument list for the program. For years that step mangled empty strings and embedded quotes. PowerShell 7.3 fixed it and added a preference variable to choose the behaviour:
$PSNativeCommandArgumentPassing
printf '[%s]\n' 'two words' '' '"quoted"' 'C:\path\'Standard
[two words]
[]
["quoted"]
[C:\path\]Each argument arrived exactly as written, including the empty one and the literal quotes. Here is the old behaviour, which you can still select:
$PSNativeCommandArgumentPassing = 'Legacy'
printf '[%s]\n' 'two words' '' '"quoted"' 'C:\path\'[two words]
[quoted]
[C:\path\]The empty argument vanished and the quotes were stripped. Windows PowerShell 5.1 always
behaves like Legacy (the variable does not exist there). On Windows, PowerShell 7.3+ defaults
to a third mode, Windows, which uses Standard except for a list of programs such as
cmd.exe and msiexec.exe that parse their command lines in non-standard ways. I could only
test the Linux default (Standard) for this article.
To build arguments dynamically, put them in an array and splat it; each element becomes one argument, spaces included:
$printfArgs = '[%s]\n', 'web 01', 'db01'
printf @printfArgs[web 01]
[db01]The stop-parsing token --%
--% tells PowerShell to stop interpreting the rest of the line and hand it to the program
as-is. It exists for Windows programs with their own odd syntax. Compare a normal call and a
--% call on Linux:
$tag = 'v2.1'
printf '[%s]\n' $tag @(1, 2) 'a;b'
printf '[%s]\n' --% $tag @(1, 2) 'a;b'[v2.1]
[1]
[2]
[a;b]
[$tag]
[@(1,]
[2)]
['a;b']After --%, $tag was not expanded, the array syntax was split on spaces, and the single
quotes reached the program as literal characters, because there is no shell left to remove
them. On Windows, --% still expands cmd-style %VARIABLES%. In Windows PowerShell 5.1:
$tag = 'v2.1'
cmd.exe /c echo %OS% $tag
cmd.exe /c echo --% %OS% $tagWindows_NT v2.1
Windows_NT $tagIn practice, with Standard argument passing in PowerShell 7, you rarely need --%. Splatting
an array is clearer, and it works with variables.
Where you'll use this
A typical CI job runs several linters and must fail if any of them fails. In PowerShell that means running native tools, capturing their text, checking every exit code and returning a non-zero exit code yourself. The repository in this example has a shell script with an unquoted variable, a broken JSON file, and a Terraform file with bad indentation:
# run-checks.ps1 - run the same linters as CI, report every result, fail if any failed
$checks = @(
@{ Name = 'shellcheck'; Command = 'shellcheck'; Arguments = '--format=gcc', 'deploy.sh' }
@{ Name = 'json'; Command = 'jq'; Arguments = 'empty', 'config.json', 'broken.json' }
@{ Name = 'terraform'; Command = 'terraform'; Arguments = 'fmt', '-check', '-no-color' }
)
$results = foreach ($check in $checks) {
$arguments = $check.Arguments
$output = & $check.Command @arguments 2>&1 # capture stdout and stderr as text
[PSCustomObject]@{
Check = $check.Name
ExitCode = $LASTEXITCODE
Passed = $LASTEXITCODE -eq 0
Output = ($output | ForEach-Object { "$_" }) -join "`n"
}
}
$results | Format-Table Check, ExitCode, Passed -AutoSize
foreach ($r in $results | Where-Object { -not $_.Passed }) {
"--- $($r.Check) (exit code $($r.ExitCode))"
$r.Output
}
$failed = @($results | Where-Object { -not $_.Passed }).Count
if ($failed -gt 0) { exit 1 }./run-checks.ps1
"exit code: $LASTEXITCODE"
Check ExitCode Passed
----- -------- ------
shellcheck 1 False
json 5 False
terraform 3 False
--- shellcheck (exit code 1)
deploy.sh:4:7: note: Double quote to prevent globbing and word splitting. [SC2086]
--- json (exit code 5)
jq: parse error: Expected another key-value pair at line 4, column 1
--- terraform (exit code 3)
main.tf
exit code: 1What the script relies on from this article:
& $check.Command @argumentsruns a program whose name is in a variable, with an argument array splatted so each element arrives as one argument.2>&1captures error output too, and"$_"turns eachErrorRecordback into its text.$LASTEXITCODEis read immediately after each call. Each tool uses its own codes (jq 5 for a parse error,terraform fmt -check3 for unformatted files), so the script only asks "zero or not?".exit 1gives the CI system the exit code it understands. A CI step calls the script the same way any runner would, and sees the failure:
pwsh -NoProfile -File ./run-checks.ps1 > $null
"exit code: $LASTEXITCODE"exit code: 1The same wrapper pattern serves deployment scripts that call kubectl, az or aws,
backup jobs that call tar or robocopy, and build scripts around dotnet, npm or make.
Common mistakes
Using sort, ls, curl and friends in scripts. On Linux, $services | sort CPU fails
with /usr/bin/sort: cannot read: CPU: No such file or directory; in Windows PowerShell 5.1,
curl --version fails with The remote name could not be resolved: '--version'. Write
Sort-Object, Get-ChildItem, Invoke-WebRequest, or call the program explicitly
(curl.exe).
Giving an alias parameters. Set-Alias ll 'Get-ChildItem -Force' creates an alias to a
command named Get-ChildItem -Force, which does not exist. Use a function.
Checking $? late. Any statement in between, even displaying a variable, resets it. Read
$LASTEXITCODE instead, right after the native call.
Assuming a failed program stops the script. It does not, even with
$ErrorActionPreference = 'Stop', unless you are on PowerShell 7.4+ and set
$PSNativeCommandUseErrorActionPreference = $true. Otherwise check $LASTEXITCODE yourself.
Wrong environment variable case on Linux. $env:home is empty on Linux while
$env:HOME is /home/sid. Windows hides the mistake because it ignores case.
Passing a PowerShell drive to a native program. tar -czf logs.tgz Logs: fails, because
Logs: only exists inside PowerShell. Resolve it first with (Resolve-Path Logs:).ProviderPath
or pass the real path.
Summary
- Aliases are interactive shortcuts. They differ between platforms and versions (108 in
PowerShell 7.6.9 on Linux, 158 in Windows PowerShell 5.1), and on Linux names like
ls,sortandcatrun the system programs. Use full command names in scripts. - An alias cannot include parameters; write a function with
@argsinstead. Resolution order is alias, function, cmdlet, then external program. - Providers expose data stores as drives that the item cmdlets understand:
Env:,Variable:,Function:,Alias:,Temp:everywhere, plusHKLM:,HKCU:andCert:on Windows. Registry keys are items; registry values are item properties. Test-Path Env:NAMEandTest-Path Variable:nameare clean existence checks. Environment variable names are case-sensitive on Linux and macOS.- Native programs return arrays of strings (one per line) and report failure through
$LASTEXITCODE. Join output with-join "n", convert numbers before comparing, and read$LASTEXITCODE` straight after the call. - A non-zero exit code does not stop a script unless you use
$PSNativeCommandUseErrorActionPreference = $true(PowerShell 7.4+). - PowerShell 7.3+ passes arguments exactly (
Standard); 5.1 drops empty strings and strips embedded quotes. Build dynamic argument lists as arrays and splat them; keep--%for Windows programs with unusual syntax.
Exercises
You inherited a script full of ?, %, where, foreach and select. Use the Alias:
drive or Get-Alias to produce one table showing which cmdlet each of those names runs.
Show Solution
Get-Alias -Definition Where-Object, ForEach-Object, Select-Object | Format-Table Name, Definition -AutoSize
Name Definition
---- ----------
? Where-Object
where Where-Object
% ForEach-Object
foreach ForEach-Object
select Select-Object
Searching by -Definition avoids the wildcard problem: Get-Alias '?' would match every
one-character alias. (foreach is an alias only in a pipeline; at the start of a statement it
is the foreach loop keyword.)
A deployment script needs DATABASE_URL, API_TOKEN and LOG_LEVEL. Write the check that
prints the missing names, or all set. Test it with only DATABASE_URL and LOG_LEVEL set.
Show Solution
$required = 'DATABASE_URL', 'API_TOKEN', 'LOG_LEVEL'
$env:DATABASE_URL = 'postgres://app@db01/orders'
$env:LOG_LEVEL = 'Information'
$missing = $required | Where-Object { -not (Test-Path "Env:$_") }
if ($missing) { "missing: $($missing -join ', ')" } else { 'all set' }missing: API_TOKENTest-Path "Env:$_" asks the environment provider whether the variable exists, which is
more precise than testing $env: for an empty value. In a real script, replace the message
with throw so the deployment stops before it touches anything.
Create a PowerShell drive Ci: pointing at the ci folder from the CI example, list the
JSON files in it, read replicas from config.json through the drive, and remove the drive.
Show Solution
New-PSDrive -Name Ci -PSProvider FileSystem -Root ./ci | Out-Null
Get-ChildItem Ci: -Filter *.json -Name
(Get-Content Ci:/config.json | ConvertFrom-Json).replicas
Remove-PSDrive Cibroken.json
config.json
3| Out-Null hides the drive object that New-PSDrive returns. Every PowerShell cmdlet accepts
Ci: paths; a native program such as jq would need the real path.
Write a function Invoke-Checked that runs a native command with an array of arguments,
returns its output when the exit code is 0, and throws an error containing the exit code and
the error text otherwise. Test it with grep -c INFO on an existing file and on a missing one.
Hint
Capture with 2>&1, read $LASTEXITCODE immediately, and use throw with a message string.
Functions are covered fully in Functions and Advanced Functions.
Show Solution
function Invoke-Checked {
param([string]$Command, [string[]]$Arguments)
$output = & $Command @Arguments 2>&1
if ($LASTEXITCODE -ne 0) {
throw "$Command exited with $LASTEXITCODE`: $($output -join ' ')"
}
$output
}
Invoke-Checked -Command 'grep' -Arguments '-c', 'INFO', './app.log'
Invoke-Checked -Command 'grep' -Arguments '-c', 'INFO', './missing.log'1
Exception:
Line |
5 | throw "$Command exited with $LASTEXITCODE`: $($output -join ' …
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
| grep exited with 2: /usr/bin/grep: ./missing.log: No such file or directoryThe backtick before the colon stops PowerShell from reading $LASTEXITCODE: as a drive-qualified
variable. Because the function throws, a caller can stop the whole script on the first failed
command, or catch the error; see Error Handling. One
caveat: grep exits with 1 for "no match", which is not an error for many uses, so a real
wrapper often takes a list of acceptable exit codes.
Tested with: PowerShell 7.6.9 on Ubuntu 24.04 (WSL2) and Windows PowerShell 5.1 (5.1.26100)
on Windows 11, November 2026. The Linux examples were run as shown, using shellcheck 0.9, jq 1.7
and Terraform 1.17.1 for the CI example. The Windows examples (5.1 aliases, providers, registry,
certificates, cmd.exe with --%) are read-only and were run with powershell.exe -NoProfile on
the host; the registry-writing snippet and New-PSDrive -Persist were not executed, and the
Windows argument-passing mode of PowerShell 7 on Windows was not tested because PowerShell 7 was
not installed on that machine.
Written by The Dark Debugger
Engineer documenting the things that took me too long to learn, so they take you less time. Every PowerShell tutorial here is tested end to end before publishing.