Exporting Importing and Formatting
Like export-csv out-file out-html and the like
Comparing processes with a reference xml output of current processes
First exporting the Get-Process to xml
Get-Process | Export-Clixml -Path C:\temp\Processes.xml
Mode LastWriteTime Length Name
---- ------------- ------ ----
-a---- 28/05/2020 9:20 AM 28110462 Processes.xml
Just so I have some process to compare I am opening the calculator, notepad, ISE and word and I have closed PowerShell . And now I will compare them.
Compare-Object -ReferenceObject (Import-Clixml C:\temp\Processes.xml) -DifferenceObject (Get-Process) -Property name
name SideIndicator
---- -------------
FileCoAuth =>
notepad =>
powershell_ise =>
RuntimeBroker =>
WINWORD =>
conhost <=
powershell <=
svchost <=
A left pointing arrow means that something was on in the reference object but not present in the difference object and visa versa right arrows right arrows mean new objects
Sorting
Get-Process -Name a* | Sort-Object -Property ws -Descending
You can sort on multiple properties by seperating them with a comma
Get-Process -Name a* | Sort-Object -Property name,ws -Descending
Handles NPM(K) PM(K) WS(K) CPU(s) Id SI ProcessName
------- ------ ----- ----- ------ -- -- -----------
566 15 16892 21588 33.27 17344 0 audiodg
771 49 22544 392 1.34 8380 1 AudibleRT.WindowsPhone
627 34 24220 30096 47.31 10572 1 ApplicationFrameHost
297 17 4232 4996 14.42 3924 1 Amazon Music Helper
606 51 108172 151080 235.31 11844 1 Amazon Music
1256 66 86372 132100 212.63 16900 1 Amazon Music
630 37 50884 71792 134.30 9204 1 Amazon Music
261 20 18032 30268 0.72 9692 1 Amazon Music
195 15 2760 5144 8312 0 aesm_service
Select
Select can be used to pull out only the data you are interested in.
Get-Process -Name a* | select name
Name
----
aesm_service
Amazon Music
Amazon Music
Amazon Music
Amazon Music
Amazon Music Helper
ApplicationFrameHost
AudibleRT.WindowsPhone
audiodg
Measure Object
Measure-object can be used to find max min average and sum of and object.
ps | Measure-Object -Property ws -Maximum -Minimum -Average -Sum
Count : 229
Average : 21158236.7860262
Sum : 4845236224
Maximum : 278446080
Minimum : 0
Property : WS
Select-Object with Expression
The basic format here is @{name='';expression={}}
ps | Select-Object name,id,@{name="VM(MB)";expression={$_.vm / 1MB -as[int]}}
Name Id VM(MB)
---- -- ------
aesm_service 8312 4203
Amazon Music 9204 638
Amazon Music 9692 242
Amazon Music 11844 500
Amazon Music 16900 497
Amazon Music Helper 3924 100
Get-Member
Most of the time when you run a command in PowerShell the output is filtered. to find all the properties of an object you can pipe the command to Get-Member or its alias gm
Get-Service | Get-Member
TypeName: System.ServiceProcess.ServiceController
Name MemberType Definition
---- ---------- ----------
Name AliasProperty Name = ServiceName
RequiredServices AliasProperty RequiredServices = ServicesDependedOn
Disposed Event System.EventHandler Disposed(System.Object, System.EventArgs)
Close Method void Close()
Continue Method void Continue()
CreateObjRef Method System.Runtime.Remoting.ObjRef CreateObjRef(type requestedType)
Dispose Method void Dispose(), void IDisposable.Dispose()
Equals Method bool Equals(System.Object obj)
ExecuteCommand Method void ExecuteCommand(int command)
GetHashCode Method int GetHashCode()
GetLifetimeService Method System.Object GetLifetimeService()
GetType Method type GetType()
InitializeLifetimeService Method System.Object InitializeLifetimeService()
Pause Method void Pause()
Refresh Method void Refresh()
Start Method void Start(), void Start(string[] args)
Stop Method void Stop()
WaitForStatus Method void WaitForStatus(System.ServiceProcess.ServiceControllerStatus desiredStatus), void Wa...
CanPauseAndContinue Property bool CanPauseAndContinue {get;}
CanShutdown Property bool CanShutdown {get;}
CanStop Property bool CanStop {get;}
Container Property System.ComponentModel.IContainer Container {get;}
DependentServices Property System.ServiceProcess.ServiceController[] DependentServices {get;}
DisplayName Property string DisplayName {get;set;}
MachineName Property string MachineName {get;set;}
ServiceHandle Property System.Runtime.InteropServices.SafeHandle ServiceHandle {get;}
ServiceName Property string ServiceName {get;set;}
ServicesDependedOn Property System.ServiceProcess.ServiceController[] ServicesDependedOn {get;}
ServiceType Property System.ServiceProcess.ServiceType ServiceType {get;}
Site Property System.ComponentModel.ISite Site {get;set;}
StartType Property System.ServiceProcess.ServiceStartMode StartType {get;}
Status Property System.ServiceProcess.ServiceControllerStatus Status {get;}
ToString ScriptMethod System.Object ToString();
You can use Format-List * if you want to see the actual values of the properties and alias properties
Get-Service -Name BITS | Format-List *
Name : BITS
RequiredServices : {RpcSs}
CanPauseAndContinue : False
CanShutdown : False
CanStop : True
DisplayName : Background Intelligent Transfer Service
DependentServices : {}
MachineName : .
ServiceName : BITS
ServicesDependedOn : {RpcSs}
ServiceHandle : SafeServiceHandle
Status : Running
ServiceType : Win32OwnProcess, Win32ShareProcess
StartType : Automatic
Site :
Container :
Format-Wide
Format-Wide only displays one thing and by default it displays it in two columns
Get-Process | Format-Wide
aesm_service Amazon Music
Amazon Music Amazon Music
Amazon Music Amazon Music Helper
ApplicationFrameHost AudibleRT.WindowsPhone
audiodg Calculator
chrome chrome
You can however increase the amount of columns
Get-Process | Format-Wide -Column 6
aesm_service Amazon Music Amazon Music Amazon Music Amazon Music Amazon Music Helper
ApplicationFrameHost AudibleRT.WindowsP... audiodg Calculator chrome chrome
chrome chrome chrome chrome chrome chrome
Format Table
Format table is the default display if there are less than 3 columns
The alias is FT. With FT you can use auto size and groupby and -wrap
Get-Service |sort status | ft -GroupBy status -AutoSize
Status: Stopped
Status Name DisplayName
------ ---- -----------
Stopped AarSvc_547a8 Agent Activation Runtime_547a8
Stopped PNRPsvc Peer Name Resolution Protocol
Stopped PolicyAgent IPsec Policy Agent
Stopped PrintNotify Printer Extensions and Notifications
--------------------------------------------------------------------
Status: Running
Status Name DisplayName
------ ---- -----------
Running BthAvctpSvc AVCTP service
Running BTAGService Bluetooth Audio Gateway Service
Running BrokerInfrastructure Background Tasks Infrastructure Service
Running bthserv Bluetooth Support Service
You can also include expressions in FT
ps |ft name,id,@{n='VM(MB)';e={$_.vm / 1mb};formatstring='n2';align='right';width=12},@{n='PM(MB)';e={$_.pm / 1mb};formatstring='n2';align='right';width=10} -AutoSize
Name Id VM(MB) PM(MB)
---- -- ------ ------
aesm_service 8312 4,203.22 2.70
Amazon Music 9204 637.50 49.75
Amazon Music 9692 241.57 17.62
Amazon Music 11844 500.35 111.02
Amazon Music 16900 502.04 88.32
Amazon Music Helper 3924 100.26 4.07
ApplicationFrameHost 10572 2,101,514.50 23.14
The Format Operator
The first number is the index and after the colon the n value is the amount of decimals
"{0} {1:n2} {3} {2:n4}" -f "hello",4.5756345634,6.475333,"there"
hello 4.58 there 6.4753
Write Host
Write-Host only displays text to the screen it does not allow you to send output to the pipeling
It does however have the advantage of being able to colour text and change the background colour.
This makes it useful for the kind of commands that are interactive like show commands
PS C:\>Write-Host "Hello World" -ForegroundColor magenta -BackgroundColor white
Hello World
Read Host
You can get users to interactively enter data with Read-Host
PS C:\> Read-Host -Prompt "Please enter your age?"
Please enter your age?: 42
42
This can be used to set variables before running some kind of script. It can be used with menus.
Write Verbose
This is kind of like write host except it only appear when you either set the $VerbosePreference variable from SilentlyContinue to Continue
$VerbosePreference = 'continue' or you run an advanced function with the verbose flag
Write-Verbose "Task A has completed"
This is good for troubleshooting and showing progress in a script that does multiple tasks
Formatting Get-Date
PS C:\> $D = Get-Date
PS C:\> get-date $D -Format MMMM
June
PS C:\> get-date $D -Format MM
06
PS C:\> get-date $D -Format d
15/06/2020
PS C:\> get-date $D -Format dd
15
PS C:\> get-date $D -Format dddd
Monday
PS C:\> get-date $D -Format "MMMM dd, yyyy"
June 15, 2020
