Skip to content

Instantly share code, notes, and snippets.

@inammathe
Last active June 30, 2018 02:22
Show Gist options
  • Save inammathe/2f0fa91ad82bc469ba7a208ff78bd2d8 to your computer and use it in GitHub Desktop.
Save inammathe/2f0fa91ad82bc469ba7a208ff78bd2d8 to your computer and use it in GitHub Desktop.
Sets the process class of one or more processes
function Set-ProcessPriorityClass
{
[CmdletBinding(SupportsShouldProcess, ConfirmImpact='Low')]
param(
# Names of the processes to change
[Parameter(Mandatory, ValueFromPipeline)]
[Alias("Name")]
[String[]]
$ProcessName,
# Desired Priority of the process
[Parameter(Mandatory)]
[ValidateSet('Low', 'Below Normal', 'Normal', 'Above Normal', 'High', 'Realtime')]
[Alias("PriorityClass","Class")]
[String]
$Priority,
# Max attempts to retrieve process state
[Parameter(Mandatory=$false)]
[int]
$MaxAttempts = 20
)
Process
{
foreach ($name in $ProcessName) {
if ($PSCmdlet.ShouldProcess($name, "Sets the process priority to '$Priority'"))
{
$oldValue = $null
$newValue = $null
$process = $null
$attempts = 1
do {
Write-Host "Attempting to get process $name. Attempt $attempts of $MaxAttempts"
$process = Get-Process -Name $name -ErrorAction SilentlyContinue
$attempts++
Start-Sleep -Seconds 1
} while (!$process -and $attempts -le $MaxAttempts)
if ($process) {
$oldValue = $process.PriorityClass
if($oldValue -ne $Priority) {
$process.PriorityClass = $Priority
}
$newValue = $process.PriorityClass
}
[PSCustomObject]@{
ProcessName = $name
OldValue = $oldValue
NewValue = $newValue
IsChanged = $newValue -ne $oldValue
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment