Without going into the ‘why and wherefore’ of each PowerShell command, how about some of the PowerShell ‘one (or two)-liners’ that may be found useful?
(I have no doubt that others keep the same type of ‘cheat sheets’ that I do. Perhaps share?
![]() |
Patch reliability is unclear, but widespread attacks make patching prudent. Go ahead and patch, but watch out for potential problems. |
SIGN IN | Not a member? | REGISTER | PLUS MEMBERSHIP |
Home » Forums » Developers, developers, developers » DevOps Lounge » PowerShell – Useful one-liners (maybe two…)
Tags: one-liners PowerShell
Without going into the ‘why and wherefore’ of each PowerShell command, how about some of the PowerShell ‘one (or two)-liners’ that may be found useful?
(I have no doubt that others keep the same type of ‘cheat sheets’ that I do. Perhaps share?
Rick,
Just something to tuck away in your mind the Get-WmiObject is depreciated and is replaced by the Get-CimInstance command.
PS>(Get-CimInstance -class Win32_computersystem).workgroup
HOME
PS>
HTH
Many thanks, @retiredgeek. I wasn’t aware of this at all. Strange that it doesn’t seem to be well-known either… all I see are WMI queries.
Instead of fiddling around with quotes you can use the builtin variable $True.
Get-Ciminstance -class Win32_UserAccount -Filter LocalAccount=$True
HTH
Another way:
PS>(Get-CimInstance -ClassName win32_operatingsystem).lastbootuptime
Monday, June 24, 2019 10:59:03 AM
Thanks, @retiredgeek. The output is much cleaner… saves me having to strip the superfluous info.
BTW Get-CimInstance is also faster.
PS>Measure-Command -Expression {get-ciminstance -class win32_printer -filter Default=$true}
Days : 0
Hours : 0
Minutes : 0
Seconds : 0
Milliseconds : 156
Ticks : 1560909
TotalDays : 1.80660763888889E-06
TotalHours : 4.33585833333333E-05
TotalMinutes : 0.002601515
TotalSeconds : 0.1560909
TotalMilliseconds : 156.0909
PS>Measure-Command -Expression {Get-WmiObject -Query ” SELECT * FROM Win32_Printer WHERE Default=$true”}
Days : 0
Hours : 0
Minutes : 0
Seconds : 0
Milliseconds : 192
Ticks : 1926661
TotalDays : 2.22993171296296E-06
TotalHours : 5.35183611111111E-05
TotalMinutes : 0.00321110166666667
TotalSeconds : 0.1926661
TotalMilliseconds : 192.6661
Rick, which version of PowerShell are these commands for? I tried a sampling of the ones above on my Windows 7 PC using copy-and-paste from your posts, and got errors for Get-disk, Get-NetIPAddress, and Get-MpThreat.
My version of PowerShell is 3.0. On each of those commands, it returned a series of lines starting with the statement that the term is not recognized.
The commands that did work, however, were very cool. Let’s have more!
Here’s a Microsoft reference for PowerShell cmdlets by PS version, which should assist you.
PowerShell Module Browser – set to view v3.0, but can be used up to v6.
That list only goes back to v3.0; to access the v2.0 list, see TechNet here.
Additionally, you should be able to use “Get-Command” to get a list of cmdlets your version has.
Thank you, @Kirsty. Just the sort of helpful response I was hoping for whilst I try to get my head around PowerShell. My main PC is still running Win 7… so I’m often flummoxed why code I spot online doesn’t work for me until I test it on a Win 10 device. This reference will help enormously.
There are a number of useful Powershell resources on AskWoody. Check the topic tag (at the top of the topic), and this one has a number of very useful links:
PowerShell- Learning Virtually on MV Academy & MSDN Channel 9 from Videos, eBook
(it was a major effort put together by @photm)
I investigated updating my Win7 Powershell version, but I’ve never had the spare time to go ahead. It couldn’t be updated from the default installed version to 5.0 directly. I did find some useful resources others may find helpful though:
How to Install Windows PowerShell 4.0 (Technet)
(Check out the known issues, for example)
Windows PowerShell Portal (Technet)
Windows Management Framework (MS Docs)
This has multiple resources, incl. release notes for v.3 – 5.1, known issues, etc.
@Kirsty –
Good Evening!
The following link from MS says that you don’t need to uninstall 5.0 to install 5.1, just upgrade by installing directly over your existing installation of 5.0, which is no longer supported at all by MS. BUT, first make sure you’ve got .NET 4.5.2 or greater installed on your machine. I’m currently on PS version 2.0, which was my out-of-the-box version.
Be sure to read the contents of the blue box at the top of the page directly under the article’s title, AND the notes below the table listing the download links for specific versions of WMF, which PowerShell is a major component of.
https://docs.microsoft.com/en-gb/powershell/wmf/setup/install-configure
Hope this helps, when you finally get some time to perform the upgrade to 5.1!
Ah… Win7 comes with PS 2.0!
However, I have now discovered that the prior requirement to install WMF4 before installing WMF5 is no longer necessary (Windows Management Framework the package that includes Powershell, which can’t be installed on its own).
Windows Management Framework (WMF) 5.1 Released
By PowerShell Team | January 19th, 2017
Update March 28, 2017
Please note that for Windows 7 and Windows Server 2008 R2 the installation instructions have changed significantly. Please read the Install and Configure topic in the release notes. We have removed the requirement for pre-installing WMF 4 on Windows 7 and Windows Server 2008 R2, but to do so we had create a script for checking the prerequisites that accompanies the MSU in a ZIP file. WMF 5.1 requires .Net version 4.5.2, and cannot be installed on Windows 7 or Windows Server 2008 R2 if WMF 3.0 is installed. This affects only Windows 7 and Windows Server 2008 R2. The Install and Configure topic in the release notes provides details on using the script.
Read the full article here
Rick, which version of PowerShell are these commands for?
Good point, well made. I should have included this information for each command.
For example, the commands I’ve posted so far are mostly for PowerShell v5 (i.e. included by default in Win 10) as I struggle to become familiar with it.
Mea culpa… I’ll try to remember to include PS version info with any future posts.
@Cybertooth – I found out that you can update PowerShell (PS). For example, PS running on my main Windows 7 PC has currently been updated from v3 to v5:
Have a look at this MS Installing Windows PowerShell article.
Hope this helps…
I’m just a beginner with PowerShell (PS) (and an ‘improver’ with AskWoody ).
I just thought it would be easier to ask any further questions about an individual one-liner just by clicking on the ‘Quote’ link on each post.
For example, I’ve realised that some PS one-liners that are native to a particular version of Windows just don’t work with earlier versions of Windows… so WMI queries within PS need to be used instead of just native PS.
Then there’s the issue about PS itself… I’m finding it hugely powerful… and just as hugely complex to get my head around after being used to the (relative) simplicity of AutoHotkey (AHK).
For example, back in the days of Windows Secrets Lounge I wrote a tiny program called My WinVer in AHK (Sadly, only the follow-up made the transition here to AskWoody) which @RetiredGeek re-wrote in PS. I remarked at the time that the GUI commands in AHK took just a few lines whilst the PS equivalent took many dozens. I just like the comparative simplicity of AHK… PS has come as quite a culture shock and there’s no way that I’m ready to dip my toes in the murky pond of trying to create a GUI using PS.
Hope this helps…
For those contemplating updating/upgrading their installations of PowerShell from what they currently have to a newer version, please read the system requirements in their entirety, paying special attention to the version of .NET Framework or .NET that is required by the version of PowerShell you’re contemplating installing.
For example, if the PowerShell version you’d like to install requires version 4.0 or 4.5 of .NET, you may need to install .NET first before installing the version of PowerShell you’ve got your eye on. This may mean installing an older version of .NET than the one you currently have on your system. Some versions of PowerShell require a specific version of .NET, whereas other versions require a specific version or higher of .NET.
PowerShell 3.0 requires .NET Framework 4.0, whereas PowerShell 5.1 requires .NET framework 4.5 or above.
Based on the above, my advice to anyone wishing to upgrade to a newer version of PowerShell than what they currently have is to get the version that doesn’t require you to install yet another version of .NET on your system, so one that will work with the version/versions (yep, you can have more than one version of .NET installed at once) of .NET you already have installed on your system.
If you have not yet discovered it, PowerShell ISE is now built-in on every Windows 10 edition (I think . . .)
It allows you to visually edit your ps1 files, as well as run them, as well as debug. Like a mini-development platform for PowerShell.
~ Group "Weekend" ~
I’d also recommend Visual Studio Code which is free and will do some checking that the PS_ISE doesn’t do.
I do the vast majority of my PS development in the ISE but use VSCode to do some final checking to clean up my code.
HTH :cheers:
I’ve got the ISE built-in to my copy of Win7 Pro SP1 x64 with PowerShell 2.0 out-of-the-box! Looks pretty good, but not as good as it does on Win10!!
The ISE executable hides in the same locations (yes, locations for Win 7) that the regular command line executable hides in.
For Win 7, they’re in Windows\System32\WindowsPowerShell AND in \SysWOW64\WindowsPowerShell, whereas in Windows 10 Enterprise v. 1803 x64, I’ve only found them in the SysWOW64 folder.
I like the look of the command line and the ISE better in Win10 than what I’ve currently got in Win7.
Gee, maybe it’s time for me to upgrade my 10 year old Win 7 machines at home to Windows 10??? NOT!!!
My PS crashes upon loading and gets the “Controlled folder access blocked” message. Are folks leaving this active or just disabling it.
IMHO this is one of M$s worst boondogles, why no way to just say yes in perpetuity ? Why do I need to trace down executables, a pain IMH.
IMHO this is one of M$s worst boondogles, why no way to just say yes in perpetuity ? Why do I need to trace down executables, a pain IMH.
There is; you don’t:
Start, Settings, Update & Security, Windows Security, Virus & threat protection, Manage ransomware protection, Allow an app through Controlled folder access, Add an allowed app, Recently blocked apps
Add an Allowed App through Controlled Folder Access in Windows Defender Security Center
My PS crashes upon loading and gets the “Controlled folder access blocked” message. Are folks leaving this active or just disabling it.
IMHO this is one of M$s worst boondogles, why no way to just say yes in perpetuity ? Why do I need to trace down executables, a pain IMH.
That’s an optional feature in Windows Defender, (which, btw, now has awesome management abilities on Microsoft 365 for large deployments) but it does require quite a bit of initial config and tweaking, as well as manual updates to the safe list anytime you install something new.
Enable it, but be willing to manage it. As has always been the case for all White-List approaches to security.
Personally for small office/home machines I find it more useful to run myself and all other users as Standard Users, restricting my own admin level is much less stressful and almost as good unless I do something silly.
~ Group "Weekend" ~
That would be disabling the protection entirely,
It doesn’t.
or having to look up every exception and typing it [an annoyance]
You don’t have to type anything in.
Ok I mis spoke I will still need to hunt up the executable location rather that windows just offering to white list it
again [painful]
Ok I mis spoke I will still need to hunt up the executable location rather that windows just offering to white list it
again [painful]
Are you using version 1803?
You can’t complain too much about inconvenience if you’re two versions behind current.
On 1809 or later you don’t need to hunt the executable and Windows does offer it for whitelisting.
Ok I mis spoke I will still need to hunt up the executable location rather that windows just offering to white list it
again [painful]
We have Windows 10 Enterprise ver.1803 at work, and our PowerShell executables are in the \Windows\SysWOW64\WindowsPowerShell\v1.0 folder. There you should find the command line executable as well as the ISE executable. I highlighted the v1.0 to ensure you didn’t think I’d mistyped v10. The folder name is, indeed, “v1.0”.
That’s also the same place they hide on my machines at home that have Win 7 x64 SP1. So, I think it’s a fair bet to say that the location mentioned above is where you’ll find them.
I hope this helps, especially if you decide to get into writing scripts with PowerShell!
The following comments are based on my experiences with PowerShell v 5.x. I believe they’re valid for v 3.x, but I’m not certain of that.
PowerShell has what I consider to be a fabulous help system. If you want the latest versions of the help files on your local machine (may not want to do this on a slow and/or metered connection):
Update-Help -Force
The main help command is called Get-Help. To see its help article:
Get-Help Get-Help
Output from the Get-Help command continuously scrolls to the PowerShell window, so help articles that are larger than one screen always scroll to the end with Get-Help, which isn’t useful.
Get-Help has two aliases, help and man, that display the help article one page at a time:
help Get-Help
Get-Help and its aliases will show you all of the syntax for the command and provide a description. You don’t get any explanation of the parameters nor do you get any examples. To get these, add the “-Detailed” switch:
help Get-Help -Detailed
If you just want the examples:
help Get-Help -Examples
Looking at the help article in the PowerShell console, especially for really long help articles, can be tedious. The pager is like the *NIX more command: you can only scroll forward. Plus, as you enter other PowerShell commands, the help article gets farther and farther back in the scroll buffer. If there were only some way to pop the help article up in its own window…
help Get-Help -ShowWindow
This is generally my goto view for help. With the “-ShowWindow” switch, you get the full text of the help article as if you provided the “-Detailed” switch, too. Also, there’s an entry field to find text in the help article.
If you’re on a metered connection or just don’t want to use the bandwidth to get local copies of the help files, use the “-Online” switch.
help Get-Help -Online
This will open your default browser and take you to the Microsoft TechNet Library page for the help article. A nifty feature about this page is it will default to the help article for the PowerShell version you have installed and you can change to the help article for other versions of PowerShell, if they exist. Note: the “-Online” switch won’t be useful for PowerShell modules/commands you’ve installed from third parties.
You can use wild cards in the help topic to get back of list of help articles matching the pattern. Let’s say you know there’s some network command you’ve used before, but you can’t quite remember what it is:
help *network*
This will give you a listing of all the help articles that have “network” somewhere in the command name.
Finally, PowerShell has a large number of special “about” help articles. To see what those are:
help about*
Hope you find this useful.
I gotta say thanks to the power shell help I got. Very good info!
I am really yammering about the Controlled folder access blocked message
I should have started a separate topic mea culpa
Thanks again…
Show Master Browser:
net view | ? { $_ -match '^\\(S+)' } | % { $matches[1] } | ? { nbtstat -a $_ | sls '__MSBROWSE__' }
This queries devices on the network and returns the computername of the device elected as master browser:
I’ve only tested it with PowerShell v5.
Hope this helps…
Rick,
On further investigation it seems your code segment dropped some back slashes. They do show correctly in your screen capture though.
net view | ? { $_ -match '^\\\\(\S+)' } | % { $matches[1] } | ? { nbtstat -a $_ | sls '__MSBROWSE__' }
RG, Thanks for pointing that out. I just copy/pasted from the PS window where I had successfully run the one-liner. I wonder if it’s the site software doing the removing?
Test:
net view | ? { $_ -match '^\\\\(\S+)' } | % { $matches[1] } | ? { nbtstat -a $_ | sls '__MSBROWSE__' }
I’ve checked and double-checked that the code is correct (i.e. 4+1 backslashes) prior to hitting the Submit button.
EDIT: Checked again after Submit. Everything looks fine. I’ll have to watch out for this in future. Thanks again, RG.
Determine UEFI or (legacy) BIOS:
Note: You MUST run this query as elevated. Tested with PS 5.0 (running in Windows 7):
if (Test-Path $env:windir\Panther\setupact.log) {(Select-String 'Detected boot environment' -Path "$env:windir\Panther\setupact.log" -AllMatches).line -replace '.*:\s+'} else {if (Test-Path HKLM:\System\CurrentControlSet\control\SecureBoot\State) {"UEFI"} else {"BIOS"}}
Note that the above code is all one line…
(Many thanks to http://wintech.sgal.info where I found the code…)
Invoke-WebRequest "https://raw.githubusercontent.com/lptstr/winfetch/master/winfetch.ps1" -UseBasicParsing | Invoke-Expression
Open a PowerShell console (it doesn’t need to be elevated), copy/paste the command above into the console and press Return/Enter.
It will execute the PowerShell script from github and in the blink of an eye give an output similar to this:
(Tested in Windows 10 using PowerShell 5.)
Rick,
Interesting that I get errors using PS 5.1.19041.1237
PS>$PSVersiontable Name Value ---- ----- PSVersion 5.1.19041.1237 PSEdition Desktop PSCompatibleVersions {1.0, 2.0, 3.0, 4.0...} BuildVersion 10.0.19041.1237 CLRVersion 4.0.30319.42000 WSManStackVersion 3.0 PSRemotingProtocolVersion 2.3 SerializationVersion 1.1.0.1 PS>Invoke-WebRequest "https://raw.githubusercontent.com/lptstr/winfetch/master/winfetch.ps1" -UseBasicParsing | Invoke-Expression The variable '$IsWindows' cannot be retrieved because it has not been set. At line:81 char:11 + if (-not ($IsWindows -or $PSVersionTable.PSVersion.Major -eq 5)) { + ~~~~~~~~~~ + CategoryInfo : InvalidOperation: (IsWindows:String) [], RuntimeException + FullyQualifiedErrorId : VariableIsUndefined ....,,:;+ccllll Bruce@DELLXPS8920 ...,,+:; cllllllllllllllllll ----------------- ,cclllllllllll lllllllllllllllllll OS: Windows 10 Pro [64-bit] llllllllllllll lllllllllllllllllll Host: Dell Inc. XPS 8920 llllllllllllll lllllllllllllllllll Kernel: 10.0.19043.0 llllllllllllll lllllllllllllllllll Motherboard: Dell Inc. 0VHXCD llllllllllllll lllllllllllllllllll Uptime: 8 hours 7 minutes llllllllllllll lllllllllllllllllll Shell: PowerShell v5.1.19041.1237 Resolution: 1920x1080, 1920x1080 llllllllllllll lllllllllllllllllll Terminal: Windows Console llllllllllllll lllllllllllllllllll CPU: Intel(R) Core(TM) i7-7700 CPU @ 3.60GHz llllllllllllll lllllllllllllllllll GPU: NVIDIA GeForce GTX 1050 Ti Intel(R) HD Graphics 630 llllllllllllll lllllllllllllllllll Memory: 6.02 GiB / 15.9 GiB (37%) llllllllllllll lllllllllllllllllll Disk (C:): 90 GiB / 207 GiB (43%) `'ccllllllllll lllllllllllllllllll `' \\*:: :ccllllllllllllllll''*::cll
But runs w/o complaint in PS 7.1.5.
PSv7>$psversiontable Name Value ---- ----- PSVersion 7.1.5 PSEdition Core GitCommitId 7.1.5 OS Microsoft Windows 10.0.19043 Platform Win32NT PSCompatibleVersions {1.0, 2.0, 3.0, 4.0…} PSRemotingProtocolVersion 2.3 SerializationVersion 1.1.0.1 WSManStackVersion 3.0 PSv7>Invoke-WebRequest "https://raw.githubusercontent.com/lptstr/winfetch/master/winfetch.ps1" -UseBasicParsing | Invoke-Expression ....,,:;+ccllll Bruce@DELLXPS8920 ...,,+:; cllllllllllllllllll ----------------- ,cclllllllllll lllllllllllllllllll OS: Windows 10 Pro [64-bit] llllllllllllll lllllllllllllllllll Host: Dell Inc. XPS 8920 llllllllllllll lllllllllllllllllll Kernel: 10.0.19043.0 llllllllllllll lllllllllllllllllll Motherboard: Dell Inc. 0VHXCD llllllllllllll lllllllllllllllllll Uptime: 8 hours 12 minutes llllllllllllll lllllllllllllllllll Shell: PowerShell v7.1.5 Resolution: 1536x864, 1536x864 llllllllllllll lllllllllllllllllll Terminal: Windows Console llllllllllllll lllllllllllllllllll CPU: Intel(R) Core(TM) i7-7700 CPU @ 3.60GHz llllllllllllll lllllllllllllllllll GPU: NVIDIA GeForce GTX 1050 Ti Intel(R) HD Graphics 630 llllllllllllll lllllllllllllllllll Memory: 6.19 GiB / 15.9 GiB (38%) llllllllllllll lllllllllllllllllll Disk (C:): 90 GiB / 207 GiB (43%) `'ccllllllllll lllllllllllllllllll `' \\*:: :ccllllllllllllllll''*::cll
RG,
I don’t understand that. I’ve just run it using PowerShell 5.1.19041.906 in both elevated and ordinary consoles without any errors.
That’s the same version and build you used except yours has a very small increase in the revision no. All the rest of the info provided by $PSVersiontable is identical. I assume by the difference in revision no. that you have installed one or more Windows Updates that I have blocked.
PS – I was intrigued that this worked running the script from a remote site. When I get a moment I’m going to try the same method to run scripts directly from the public folder of my Google drive.
Finding Your Windows 10 OEM Product Key Embedded In Firmware/WMI:
(Get-CimInstance -ClassName SoftwareLicensingService).OA3xOriginalProductKey
Tested with PowerShell 5.1 in Windows 10.
See this Finding Your Windows 10 OEM Product Key Embedded In Firmware/WMI article for more info.
Donations from Plus members keep this site going. You can identify the people who support AskWoody by the Plus badge on their avatars.
AskWoody Plus members not only get access to all of the contents of this site -- including Susan Bradley's frequently updated Patch Watch listing -- they also receive weekly AskWoody Plus Newsletters (formerly Windows Secrets Newsletter) and AskWoody Plus Alerts, emails when there are important breaking developments.
Welcome to our unique respite from the madness.
It's easy to post questions about Windows 11, Windows 10, Win8.1, Win7, Surface, Office, or browse through our Forums. Post anonymously or register for greater privileges. Keep it civil, please: Decorous Lounge rules strictly enforced. Questions? Contact Customer Support.
S | M | T | W | T | F | S |
---|---|---|---|---|---|---|
1 | 2 | 3 | ||||
4 | 5 | 6 | 7 | 8 | 9 | 10 |
11 | 12 | 13 | 14 | 15 | 16 | 17 |
18 | 19 | 20 | 21 | 22 | 23 | 24 |
25 | 26 | 27 | 28 | 29 | 30 | 31 |
Want to Advertise in the free newsletter? How about a gift subscription in honor of a birthday? Send an email to sb@askwoody.com to ask how.
Mastodon profile for DefConPatch
Mastodon profile for AskWoody
Home • About • FAQ • Posts & Privacy • Forums • My Account
Register • Free Newsletter • Plus Membership • Gift Certificates • MS-DEFCON Alerts
Copyright ©2004-2025 by AskWoody Tech LLC. All Rights Reserved.
Notifications