Skip to content

Instantly share code, notes, and snippets.

@jdhitsolutions
Last active November 10, 2023 15:40
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save jdhitsolutions/9439c6b49d9019b950156b45fe8a4d0b to your computer and use it in GitHub Desktop.
Save jdhitsolutions/9439c6b49d9019b950156b45fe8a4d0b to your computer and use it in GitHub Desktop.
Get all PowerShell or pwsh processes running on your computer.
#requires -version 5.1
#requires -module CIMCmdlets
Function Get-PSPowerShell {
<#
.Synopsis
Get all PowerShell processes.
.Description
Get all PowerShell or pwsh processes on your computer. The command will default
to the same PowerShell process as your console, but you can specify either one.
The command writes a custom object to the pipeline with custom formatting. If
you are running in a console host, the default formatting will use ANSI escape
sequences to highlight details.
.Parameter Name
Specify either powershell.exe or pwsh.exe. The default is your current process.
.Parameter Exclude
Exclude the current PowerShell or pwsh process.
.Example
PS C:\> Get-PSPowerShell -exclude
Get all processes that are the same as the current host, but exclude the current
process.
.Example
PS C:\> Get-PSPowerShell powershell.exe | Format-Table
Use the default table view. The process ID of the current process will be shown
in Green. If the Owner is other than the current user, it will be shown in Red.
.Example
PS C:\> Get-PSPowerShell pwsh.exe | Format-Table -view cmd
Use an alternate table view.
.Notes
The command has an alias of gpsp.
Learn more about PowerShell: http://jdhitsolutions.com/blog/essential-powershell-resources/.
.Link
Get-Process
.Link
Get-CimInstance
#>
[cmdletbinding()]
[alias("gpsp")]
[Outputtype("PowerShellProcess")]
Param(
[Parameter(Position = 0, HelpMessage = "Specify PowerShell or Pwsh. The default is your current engine.")]
[ValidateSet("powershell.exe", "pwsh.exe")]
[string]$Name = $(Split-Path (Get-Process -Id $pid).path -Leaf),
[Parameter(HelpMessage = "Exclude the current PowerShell or pwsh process.")]
[switch]$Exclude
)
Write-Verbose "Starting $($MyInvocation.MyCommand)"
Write-Verbose "Getting all $name processes."
#define a CIM Filter
$filter = "Name='$Name'"
if ($Exclude) {
#expand the filter
Write-Verbose "Excluding current $name process $pid."
$filter += " AND ProcessID != $pid"
}
<#
a hashtable of parameter values that will be splatted to Get-CimInstance
limiting CIM properties to squeeze out a bit more performance. If I am
not going to use a property, why get it?
#>
$splat = @{
Classname = "Win32_Process"
Filter = $filter
Property = "ProcessID", "HandleCount", "CommandLine", "ParentProcessID", "CreationDate","WorkingSetSize","Name"
}
Write-Verbose "Getting process data"
$items = Get-CimInstance @splat
if ($items) {
Write-Verbose "Found $($items.count) matching processes"
#create a list object to temporarily store the results
$results = [System.Collections.Generic.list[object]]::New()
foreach ($item in $items) {
Write-Verbose "Processing id $($item.processId)"
#get owner
$owner = Invoke-CimMethod -InputObject $item -MethodName GetOwner
$parent = Get-Process -Id $item.ParentprocessID
$r = [PSCustomObject]@{
PSTypename = "PowerShellProcess"
ProcessID = $item.ProcessID
Name = $item.Name
Handles = $item.HandleCount
WorkingSet = $item.WorkingSetSize
ParentProcessID = $item.ParentProcessID
ParentProcess = $parent.Name
ParentPath = $parent.Path
Started = $item.CreationDate
Owner = "$($owner.Domain)\$($owner.user)"
CommandLine = $item.Commandline
}
#add each custom object to the list
$results.Add($r)
}
#sort results and write to the pipeline
#I'm sorting so that my custom formats work as designed
$results | Sort-Object -Property Commandline, Started
}
Else {
Write-Warning "No $name processes found."
}
Write-Verbose "Ending $($MyInvocation.MyCommand)"
}
#add some type extensions to the custom object output
Update-TypeData -TypeName PowerShellProcess -MemberType ScriptProperty -MemberName Runtime -Value { (Get-Date) - $this.Started } -Force
Update-TypeData -TypeName PowerShellProcess -MemberType AliasProperty -MemberName ID -Value ProcessID -Force
Update-TypeData -TypeName PowerShellProcess -MemberType AliasProperty -MemberName WS -Value WorkingSet -Force
Update-TypeData -TypeName PowerShellProcess -MemberType AliasProperty -MemberName cli -Value Commandline -Force
#load the custom format file which should be in the same folder as this file
Update-FormatData $PSScriptRoot\powershellprocess.format.ps1xml
<#
MIT License
Copyright (c) 2021 JDH Information Technology Solutions, Inc.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
#>
<?xml version="1.0" encoding="UTF-8"?>
<!--
Format type data generated 04/12/2021 13:56:07 by PROSPERO\Jeff
This file was created using the New-PSFormatXML command that is part
of the PSScriptTools module.
https://github.com/jdhitsolutions/PSScriptTools
Load this file with Update-FormatData
-->
<Configuration>
<ViewDefinitions>
<View>
<!--Created 04/12/2021 13:56:07 by PROSPERO\Jeff-->
<Name>default</Name>
<ViewSelectedBy>
<TypeName>PowerShellProcess</TypeName>
</ViewSelectedBy>
<ListControl>
<ListEntries>
<ListEntry>
<ListItems>
<ListItem>
<Label>ProcessID</Label>
<ScriptBlock>
<!-- highlight the current process ID using ANSI-->
if ($host.name -match "console|code" -AND $_.processID -eq $pid) {
"$([char]27)[92m$($_.ProcessID)$([char]27)[0m"
}
else {
$_.ProcessID
}
</ScriptBlock>
</ListItem>
<ListItem>
<Label>Name</Label>
<PropertyName>Name</PropertyName>
</ListItem>
<ListItem>
<Label>Handles</Label>
<PropertyName>Handles</PropertyName>
</ListItem>
<ListItem>
<Label>WorkingSetMB</Label>
<ScriptBlock>($_.WorkingSet/1MB) -as [int32]</ScriptBlock>
</ListItem>
<ListItem>
<Label>ParentProcessID</Label>
<PropertyName>ParentProcessID</PropertyName>
</ListItem>
<ListItem>
<Label>ParentProcess</Label>
<PropertyName>ParentProcess</PropertyName>
</ListItem>
<ListItem>
<Label>Started</Label>
<PropertyName>Started</PropertyName>
</ListItem>
<ListItem>
<Label>Owner</Label>
<!-- Highlight owner if it isn't the current user-->
<ScriptBlock>
if ($host.name -match "console|code" -AND ($_.owner -ne "$env:USERDOMAIN\$env:username" )) {
"$([char]27)[91m$($_.Owner)$([char]27)[0m"
}
else {
$_.Owner
}
</ScriptBlock>
</ListItem>
<ListItem>
<Label>CommandLine</Label>
<PropertyName>CommandLine</PropertyName>
</ListItem>
<ListItem>
<Label>Runtime</Label>
<ScriptBlock>
$r = $_.Runtime.toString()
$r.Substring(0,$r.lastindexof("."))
</ScriptBlock>
</ListItem>
</ListItems>
</ListEntry>
</ListEntries>
</ListControl>
</View>
<View>
<!--Created 04/12/2021 14:38:01 by PROSPERO\Jeff-->
<Name>parent</Name>
<ViewSelectedBy>
<TypeName>PowerShellProcess</TypeName>
</ViewSelectedBy>
<GroupBy>
<ScriptBlock>
@"
$($_.ParentProcess) [$($_.ParentProcessID)]
Path : $($_.ParentPath)
"@
</ScriptBlock>
<Label>Parent</Label>
</GroupBy>
<TableControl>
<!--Delete the AutoSize node if you want to use the defined widths.
<AutoSize />-->
<TableHeaders>
<TableColumnHeader>
<Label>ID</Label>
<Width>8</Width>
<Alignment>left</Alignment>
</TableColumnHeader>
<TableColumnHeader>
<Label>Owner</Label>
<Width>25</Width>
<Alignment>left</Alignment>
</TableColumnHeader>
<TableColumnHeader>
<Label>Started</Label>
<Width>23</Width>
<Alignment>left</Alignment>
</TableColumnHeader>
<TableColumnHeader>
<Label>Runtime</Label>
<Width>12</Width>
<Alignment>left</Alignment>
</TableColumnHeader>
<TableColumnHeader>
<Label>Commandline</Label>
<Alignment>left</Alignment>
</TableColumnHeader>
</TableHeaders>
<TableRowEntries>
<TableRowEntry>
<Wrap />
<TableColumnItems>
<TableColumnItem>
<ScriptBlock>
<!-- highlight the current process ID using ANSI-->
if ($host.name -match "console|code" -AND $_.processID -eq $pid) {
"$([char]27)[92m$($_.ProcessID)$([char]27)[0m"
}
else {
$_.ProcessID
}
</ScriptBlock>
</TableColumnItem>
<TableColumnItem>
<!-- Highlight owner if it isn't the current user-->
<ScriptBlock>
if ($host.name -match "console|code" -AND ($_.owner -ne "$env:USERDOMAIN\$env:username" )) {
"$([char]27)[91m$($_.Owner)$([char]27)[0m"
}
else {
$_.Owner
}
</ScriptBlock>
</TableColumnItem>
<TableColumnItem>
<PropertyName>Started</PropertyName>
</TableColumnItem>
<TableColumnItem>
<ScriptBlock>
$r = $_.Runtime.toString()
$r.Substring(0,$r.lastindexof("."))
</ScriptBlock>
</TableColumnItem>
<TableColumnItem>
<PropertyName>Commandline</PropertyName>
</TableColumnItem>
</TableColumnItems>
</TableRowEntry>
</TableRowEntries>
</TableControl>
</View>
<View>
<!--Created 04/12/2021 14:15:24 by PROSPERO\Jeff-->
<Name>cmd</Name>
<ViewSelectedBy>
<TypeName>PowerShellProcess</TypeName>
</ViewSelectedBy>
<GroupBy>
<PropertyName>Commandline</PropertyName>
<Label>Commandline</Label>
</GroupBy>
<TableControl>
<!--Delete the AutoSize node if you want to use the defined widths
<AutoSize />.-->
<TableHeaders>
<TableColumnHeader>
<Label>ID</Label>
<Width>10</Width>
<Alignment>left</Alignment>
</TableColumnHeader>
<TableColumnHeader>
<Label>ParentID</Label>
<Width>10</Width>
<Alignment>left</Alignment>
</TableColumnHeader>
<TableColumnHeader>
<Label>Owner</Label>
<Width>25</Width>
<Alignment>left</Alignment>
</TableColumnHeader>
<TableColumnHeader>
<Label>Started</Label>
<Width>23</Width>
<Alignment>left</Alignment>
</TableColumnHeader>
<TableColumnHeader>
<Label>Runtime</Label>
<Width>12</Width>
<Alignment>right</Alignment>
</TableColumnHeader>
</TableHeaders>
<TableRowEntries>
<TableRowEntry>
<TableColumnItems>
<TableColumnItem>
<ScriptBlock>
<!-- highlight the current process ID using ANSI-->
if ($host.name -match "console|code" -AND $_.processID -eq $pid) {
"$([char]27)[92m$($_.ProcessID)$([char]27)[0m"
}
else {
$_.ProcessID
}
</ScriptBlock>
</TableColumnItem>
<TableColumnItem>
<PropertyName>ParentProcessID</PropertyName>
</TableColumnItem>
<TableColumnItem>
<!-- Highlight owner if it isn't the current user-->
<ScriptBlock>
if ($host.name -match "console|code" -AND ($_.owner -ne "$env:USERDOMAIN\$env:username" )) {
"$([char]27)[91m$($_.Owner)$([char]27)[0m"
}
else {
$_.Owner
}
</ScriptBlock>
</TableColumnItem>
<TableColumnItem>
<PropertyName>Started</PropertyName>
</TableColumnItem>
<TableColumnItem>
<ScriptBlock>
$r = $_.Runtime.toString()
$r.Substring(0,$r.lastindexof("."))
</ScriptBlock>
</TableColumnItem>
</TableColumnItems>
</TableRowEntry>
</TableRowEntries>
</TableControl>
</View>
</ViewDefinitions>
</Configuration>
@jdhitsolutions
Copy link
Author

Put both files in the same directory. Dot source the ps1 file which will also load the custom format file.

@jdhitsolutions
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment