The Object-Oriented Command Shell
Last updated
Last updated
Code written for PowerShell Core should usually (hopefully) run as is on Windows PowerShell too, but the reverse is often not true.
In your scripts, you can test for which edition of PowerShell is being used:
There are five main Windows PowerShell "hosts" from Microsoft:
PowerShell Console
PowerShell ISE
Visual Studio Code
Windows Admin Center
Powershell Web Access
Information about the hosting process for the PowerShell engine in front of you right now can be displayed by using the built-in $host variable:
PowerShell Console
Visual Studio Code
To see what version of PowerShell you are running now:
To see which versions of PowerShell the current running shell is compatible with:
To test whether the OS and/or PowerShell are running the 64-bit versions:
Here are some tips for executing commands in PowerShell.
The key habit to learn in PowerShell is using tab completion. By typing a few letters of a cmdlet, function, parameter, or file, you can press the Tab key to auto-complete the name. This speeds up typing, reduces errors, and prevents fatigue from typing long names.
Tip: If you accidentally hit the Tab key too fast and go past what you wanted, hit Shift-Tab to go backward to the prior options
If you cannot run any scripts at all, run the following command (you only have to do it once):
A fast way to open a text file in a new tab in PowerShell ISE is from the command line:
In PowerShell ISE, if you open a script for editing, you can highlight one or more lines from that script and execute just those highlighted lines.
All of the following commands work in PowerShell just like they do in CMD:
To see what native commands must be run in powershell.exe, not ISE, run:
When you want to feed the output of one command into a second command as input, use the pipe ("|") operator.
If you want to redirect (">" or ">>") the output of a command to a file, it'll usually work as expected, but it is better to use cmdlets like Out-File and Export-Csv instead.
If you want to run multiple commands with a single line, just separate each command with a semicolon. A semicolon at the very end of a line or command is not required.
To get help about the get-help cmdlet itself:
To see a list of all cmdlets, aliases, providers, and help files:
To see a listing of cmdlets that match a particular pattern:
To get more detailed help for a cmdlet, including parameter syntax and examples:
To pop up a searchable graphical window to display the help text:
To update the local help files from Microsoft, if you have internet access:
To see a listing of all help files:
The following command will open a separate graphical window with the help text, and it includes a search box too:
The following command will open a separate graphical window with the help text, and it includes a search box too:
An "alias" is an alternative name for a frequently-used cmdlet, function, script, file, or executable.
dir
Get-ChildItem
ls
Get-ChildItem
cls
Clear-Host
echo
Write-Output
type
Get-Content
del
Remove-Item
ps
Get-process
cd
Set-Location
pwd
Get-Location
sort
Sort-Object
cp
Copy-Item
where
Where-Object
?
Where-Object
%
ForEach-Object
kill
Stop-Process
gm
Get-Member
select
Select-Object
To see all the aliases defined in the current shell:
To see how a particular alias, like "cd", is mapped:
To create a new alias for notepad.exe named "nn":
To change an existing alias to point toward some other target:
To read more about aliases and how to manage them:
Let's get an object that represents the LSASS.EXE process:
And a process object also has an interesting and dangerous method:
To show properties, methods, and class type:
If you have captured the output of a command to a variable, but you don't know what kind of data it is or what its members are, pipe that variable into get-member:
To see the members of the first item in an array and then see the members of the array itself (an array of objects is of type "System.Object[]"):
"Drives" are more than just disk volumes. To see your currently available drives:
To see your currently installed providers and their corresponding drive names:
Cmdlets for moving around in drives of any type, from any provider, with full support for relative path addressing (using "." and "..") and tab completion:
get-location (aliases: gl, $pwd)
set-location (aliases: sl, cd, chdir)
Cmdlets for manipulating items in drive containers:
new-item (alias: ni, but see also mkdir)
remove-item (aliases: ri, del, rm, rd, rmdir)
move-item (aliases: mi, move, mv)
copy-item (aliases: cpi, copy, cp)
rename-item (aliases: rni, rn, ren)
Cmdlets for accessing the properties of an item or multiple items:
get-item (alias: gi)
get-childitem (aliases: gci, dir, ls)
set-item (alias: si)
clear-item (alias: ci)
Cmdlets for accessing an individual property of an item:
get-itemproperty (alias: gp)
set-itemproperty (alias: sp)
clear-itemproperty (alias: clp)
rename-itemproperty (alias: rnp)
move-itemproperty (alias: mp)
remove-itemproperty (alias: rp)
copy-itemproperty (alias: cpp)
Cmdlets specifically for working with strings and the contents of files:
get-content (aliases: gc, type, cat)
set-content (alias: sc)
add-content (alias: ac)
clear-content (alias: clc)
To map the "share:" drive to the "\localhost\c$" UNC network path:
In Powershell to see all enviroment variables:
To create a new environment variable:
To use an environment variable in a string you are constructing:
There are other variables built into Powershell that we see very frequently.
Some of the more commonly used automatic variables are the following:
$? -> Contains $true if last operation succeeded, $false otherwise.
$_ -> Contains the current object in a pipeline.
$args -> Contains an array of the parameters passed to a function or script.
$false -> Contains the Boolean value of False ([Int] 0, or $null).
$home -> Contains the user's home directory path.
$input -> Contains objects piped into a function, filter, or script.
$lastexitcode -> Contains the error code of the last Win32 executable execution.
$matches -> Contains matches to a regular expression search.
$null -> Contains nothing and cannot have contents.
$pshome -> Contains the directory path where PowerShell is installed.
$profile -> Full path to your profile script.
$OFS -> Output Field Separator, used as the default delimiter when converting arrays to strings, and is a single space character by default.
$true -> Contains the Boolean value of True ([Int] 1, or -not $null).
Your own functions, aliases, variables in memory will exist only in the current session; hence, if you close PowerShell and open it again, these items are lost. By adding them to your profile, however, they can be reloaded every time you open PowerShell.
Note that the CurrentUserCurrentHost property is the default for the $profile variable, so these two commands will produce the same output:
"AllUsers" scripts run for anyone using PowerShell on the computer. "CurrentUser" scripts only run for the currently logged-in user and have unique paths for each user. But what do "CurrentHost" and "AllHosts" mean? And what is a PowerShell "host"?
In PowerShell, a host is the environment where PowerShell runs, like the PowerShell console, ISE, or any app using PowerShell. It acts as a bridge between the user and PowerShell.
CurrentHost: Affects only the current PowerShell session you're using, like the console or ISE.
AllHosts: Affects all PowerShell sessions on the machine, no matter which one you're using.
Use the $host
variable to see details about the current PowerShell engine.
Later scripts can change earlier ones since they run in order. This lets admins set global settings and users adjust them if needed. Group Policy can still manage these scripts.
Functions and cmdlets are code blocks with specific names. They usually come from modules and can be run in the command shell or scripts by using their names.
To see a list of the functions available in the current shell:
As you can see from the list of functions, "help", "more", and even "C:" are all functions. What does the "C:" function do? It simply executes "Set-Location C:".
To see the contents of a function, such as the mkdir function:
A cmdlet is a type of command in PowerShell, like Get-Process. Cmdlets are often compiled into .NET binary DLLs. You can think of a cmdlet as a compiled function, but it’s not stored in the Function:\ drive; it’s usually part of a module as a DLL.
A "module" is a group of files that includes cmdlets, functions, and other related resources. They are usually stored in folders named after the module. Modules help organize code into easy-to-manage parts.
A module's main file can be a PowerShell script (.psm1), a compiled binary (.dll), or a manifest file (.psd1).
To see the default folders where PowerShell searches for modules:
PowerShell first checks the user's local profile for a module, then looks in system-wide locations. Users can create and use their own modules without being local Administrators, but changing system-wide modules needs admin rights.
When a module is loaded, its cmdlets, functions, aliases, drives, and variables can be used. A module can load another module, forming a parent-child relationship. The first module loaded is the "root module," and any modules it loads are "nested modules."
To see which parent or "root" modules are currently loaded:
To see all currently loaded modules, including the nested modules:
To see which root modules are available for use, loaded or otherwise:
To see all available root and nested modules, including their folder paths:
To load or import a module to make its cmdlets and functions available for use:
A module can also be loaded by providing the full path to it:
To see the commands made available by a particular module:
Dot-sourcing loads a function into PowerShell but is outdated. Using modules is now recommended.
Dot-sourcing a script runs it in the current scope, like typing each line manually. If the script only has functions, they're added to memory without running. It's an alternative to importing a .PSM1 module.
To dot-source a script containing functions you want to load into the function:\ drive:
The PowerShell Gallery (www.PowerShellGallery.com) is the main site for PowerShell modules and scripts. It has code from Microsoft, third parties, and community members, and is supported by Microsoft.
You can quickly search the PowerShell Gallery directly in PowerShell, similar to using "apt-cache search" on Linux.
To list the available modules and scripts from the Gallery (requires internet access):
To download and save a module or script for testing (including DSC modules):
To install a script or module for all users, you need admin rights or the right permissions to access certain system folders.
To download and save a module to your personal folder ($env:USERPROFILE\Documents\WindowsPowerShell\Modules
) without needing admin rights:
To download and save a script for your own personal use into ($env:USERPROFILE\Documents\WindowsPowerShell\scripts
), without needing admin rights:
To download and save a module for all users in $env:ProgramFiles\WindowsPowerShell\Modules
, you need to be an Admin.
To download and save a script for all users in $env:ProgramFiles\WindowsPowerShell\Scripts
, you need to be an Admin.
To list all modules and scripts installed from the PowerShell Gallery using Install-Module or Install-Script:
To update all modules and scripts installed from the PowerShell Gallery using Install-Module or Install-Script in the past:
To update a specific module or script:
To uninstall a module or script that was installed from the PSGallery: