PowerShell is a powerful scripting tool for automation. Discover cool and useful commands to boost productivity and enhance your scripting skills.
If PowerShell’s learning curve has kept you from embracing it, “cool” might not be a word you’d associate with it. But PowerShell is here to stay. It’s a core part of Microsoft 365, Azure, and Windows Server 2022 and has immense power.
In this article, TechRepublic will offer a few tricks that could come in handy. Besides, it is always cooler when you amaze someone with the solution from the command line. Having someone watch you right-click and fix something doesn’t have the same appeal.
Note: Be careful, very careful
Yes, this is a tool worthy of the name. PowerShell can easily cause massive configuration changes, positive or negative — so protect yourself and establish a test environment for your learning experiences. Also, consider using the -confirm
parameter to test configurations before execution for certain commands.
1. Report all of the USB devices installed
PowerShell is Windows Management Instrumentation aware. From PowerShell, you can make a WMI call to retrieve the USB devices installed in a local or remote system:
gwmi Win32_USBControllerDevice -computername SERVER1 |fl Antecedent,Dependent
This filter will bring back the antecedent and dependent fields from the SERVER1 computer. Should you want the full export, you can omit the pipe, | , and filter statement to comprehensively export the USB devices on a system.
This could be useful for maintaining a report for servers with a USB license device installed to maintain connectivity from the device’s perspective.
2. Perform your favorite Command Prompt tasks
All tasks performed in the Command Prompt can also be done within PowerShell. This could help you become more familiar with the interface.
Launch PowerShell in the Run dialog box with the command powershell
. You can also assign a shortcut key to PowerShell so Ctrl + Shift + P launches it directly.
3. Kill a process in PowerShell instead of Task Manager
When you have a Windows service running that will not respond to stop commands, you can use PowerShell to perform the equivalent actions of ending the task within Task Manager. For instance, you’d do the following for BadThread.exe:
get-process BadTh*
The results will be similar to this:
Handles NPM(K) PM(K) WS(K) VM(M) CPU(s) Id ProcessName
------- ------ ----- ----- ----- ------ -- -----------
28 4 -210844 -201128 -163 25.67 2792 BadThread
Once the Process ID has been identified, you can kill the errant process by entering:
stop-process -id 2792
At that point, the BadThread example will be hard stopped and you can resume your attempt to start the service. You can do that right here in PowerShell as well.
But, if the process doesn’t terminate gracefully, you can use the -Force parameter:
stop-process -id 2792 -Force
Be cautious when using it, as it could result in data loss or corruption if the process is in the middle of a task.
4. Use PSDrive to view more than just drives
The PSDrive command lets you view objects of the Windows environment beyond traditional network, local, or removable drives. One popular view is the HKLM PSDrive, which allows you to view the HKEY_LOCAL_MACHINE top-level hive of the registry. To get into the registry, enter the following command:
PS C:> cd HKLM:
PS HKLM:/>
You are then transported into the registry hive and can view and even delete items, should you wish.
5. Export NTFS folder permissions — recursive or not
Managing NTFS permissions is a separate matter, but with PowerShell, you can export the permissions to audit access or take a quick look at access control lists for the security configuration. This can be a great accountability mechanism to run in a scripted format periodically — or you can run it on demand to diagnose a particular issue.
For example, take the following iteration:
PS E:>Get-Acl N:Data
This will give you a quick report of your security rights to the specified path (note that it won’t give the shared access). That alone is nothing too exciting, as it will report only the single specified path. But if you want to include recursion for the entire path, you can use other strategies.
For the same N:\Data path, you’d use the Get-ChildItem
command within PowerShell, combined with the Get-Acl
command. Consider the following example:
PS E:>Get-ChildItem N:Data -recurse | Get-Acl
This will span the entire N:\Data path and display the ACLs for the contents of the path. What happens here is that the Get-ChildItem
provides an inventory of the file system objects, and that collection is passed to Get-Acl
to provide the results for each item.
If you want to archive this to a comma-separated variable (CSV) document, you pass | export-csv c:\filename.csv
at the end of the command. You can also pass the normal > C:\filename.txt
to the end of the command to get it exported to a text file.
Note that when you use the -recurse
option, it does just that and will traverse the entire path you specify. So be careful when doing it across a large volume or over the network.
6. Background a time-consuming task
If you have a command, or cmdlet, that will take some time to run, you can use PowerShell to send it to the background to complete. In this way, you can send a series of commands to execute at once and let them complete on their schedule.
The command to launch a background job leads with the start-psjob
parameter. You can query PowerShell on the status of any of the jobs with the following command:
PS C:>get-psjob
You’ll see a table of results showing the status of your jobs, with a unique session identifier for each one. You can remove any failed jobs by running the following command:
PS C:>remove-psjob 9
7. Insert timestamps into PowerShell outputs
For your PowerShell tasks, you can have a timestamp entered in series to determine how long a single step occurs or use it as a logging mechanism for your scripts.
To insert a timestamp, enter one of the following commands as a single line within your .ps1 file:
Date format | Command | Output example |
---|---|---|
General short (g ) | $(Get-Date -format g) Start logging | 12/12/2024 9:15 PM |
Full date/time (F ) | $(Get-Date -format F) Start logging | Thursday, December 12, 2024 9:15:13 PM |
Round trip (o ) | $(Get-Date -format o) Start logging | 2024-12-12T21:15:13.0368750-05:00 |
There are many other formats for the Get-Date
command, but these three options would generally suit most applications for timestamp purposes.
8. Test your network connection
There are several ways to test your network connection in PowerShell. The Test-Connection command checks if a remote host is reachable over the network:
Test-Connection -ComputerName techrepublic.com
This will send ICMP Echo Requests to TechRepublic.com and report whether it’s reachable and the round-trip time in milliseconds. You can also replace the URL with a device’s IP address.
You can test port availability with the command Test-NetConnection
, too:
Test-Connection -ComputerName techrepublic.com -Port 80
This checks if port 80 on techrepublic.com is reachable and, if so, will denote this with a TcpTestSucceeded
output of True
. Without adding a port number, this command will verify DNS resolution — i.e., whether the domain name can be resolved to a remote host’s IP address.
You can also use the traditional ping
command with a URL or IP within PowerShell for network testing.
9. Retrieve a file hash
Retrieving a file hash is useful for verifying the file’s integrity. By comparing the hash of a file to a known reference value, you can ensure it is not altered, corrupted, or malicious. To retrieve a file hash in PowerShell, you can use the Get-FileHash
command and -Algorithm
parameter:
Get-FileHash -Path “N:\Data\Report.txt” -Algorithm SHA1
If you don’t define a cryptographic hash algorithm, SHA256 will be assumed as default.
10. Stop and smell the roses
Within PowerShell, some commands have results that scroll through the screen very quickly. If you are not exporting the results to a file, it may be impossible to view the onscreen interaction.
Let’s again use the Get-ChildItem
command from the previous example. This command can return many results depending on your path contents. We’ll create a function called EasyView
to make it easy to view the results onscreen by displaying one line every half-second. The EasyView function would be created as follows:
function EasyView { process { $_; Start-Sleep -seconds .5}}
The $_ represents the current object being processed in the pipeline
. To make a PowerShell command, use the EasyView function, call it with a pipe at the end of the command, and then the function name as shown below:
Get-ChildItem N:Data | EasyView
The EasyView function is configured to display lines at a half-second interval. You can also use milliseconds for the value.
credit: Fiona Jackson