There are a ton of PowerShell tips online, here I’ve collected the ones where I will probably forget about and need to reference. Please add some more in the comments section if you have a good tip.
Here, we are only selecting the Id.
PS C:\Users\amb12> Get-Process | where { $_.ProcessName -eq 'cmd' } | select Id
Id
--
24552
30828
Search online for “Powershell comparison operators” to see how to use the other ones like -like -match -contains -is
. Official docs
If you want to write your own cmdlets that accept piped input works, see the section called “accepting piped input”.
Let’s say you don’t want the heading ‘Id’, you can use a foreach loop:
PS C:\Users\amb12> Get-Process | where { $_.ProcessName -eq 'cmd' } | %{$_.Id}
24552
30828
Everything being returned is a “PSObject” in C# (think of it as a dictionary). If you want to see the actual type, call GetType()
on the object.
PS C:\Users\amb12> (new-object System.Net.WebClient).GetType()
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True False WebClient System.ComponentModel.Component
If you want to see the full properties, add a | fl *
(format list) at the end of the object.
PS C:\Users\amb12> (new-object System.Net.WebClient).GetType() | fl *
Module : System.dll
Assembly : System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
TypeHandle : System.RuntimeTypeHandle
DeclaringMethod :
BaseType : System.ComponentModel.Component
UnderlyingSystemType : System.Net.WebClient
FullName : System.Net.WebClient
...
You use the Get-Command
cmdlet, with the full name of the cmdlet you wish to get the source for (not the alias). Then get the .DLL
property:
PS C:\Users\ambrose> (Get-Command get-content).DLL
C:\WINDOWS\Microsoft.Net\assembly\GAC_MSIL\
Microsoft.PowerShell.Commands.Management\
...\Microsoft.PowerShell.Commands.Management.dll
This will work for cmdlets implemented in C#. You have to open the dll in ILSpy and find the implementation manually (by convention, the name is part of the method e.g. GetContentCommand
)
If the cmdlet is implemented in PowerShell (e.g. Add-PrinterDriver
), use .Scriptblock
.
PS C:\Users\ambrose> (Get-Command Add-PrinterDriver).ScriptBlock
[CmdletBinding(SupportsShouldProcess=$true, ConfirmImpact='Medium', PositionalBinding=$false)]
param(
By looking at the name of a command, there is no way to know whether the cmdlet is implemented in C# or in PowerShell. You can use the .CommandType
property to tell.
PS C:\Users\ambrose> (get-command get-content).CommandType
Cmdlet <--this means implemented in C# (dll)
PS C:\Users\ambrose> (get-command Add-PrinterDriver).CommandType
Function <--this means Powershell
Do not use these as variable names - PowerShell will not complain if you do, however you’ll just see weird results (variable names are case insensitive)
$input
$home
get yourself on the email list
comments powered by Disqus