In a previous post, we saw how to check the Confirmation Preference, and how it works compare to a cmdlet's built-in confirmation level. But if we want to force a cmdlet to run with confirmation, we can use the '-Confirm' switch.
Here's how that works:
Like last time, we launched an instance of calculator.exe, found the process ID using Get-Process, then killed it with Stop-Process. PowerShell didn't hesitate to do as we commanded. But for safety's sake, let's add the '-Confirm' switch:
This time we had to take an extra step before the process was stopped. This feature would be useful in, for example, an interactive script designed for newer users, who might not be as comfortable taking permanent or destructive actions.
We've been crafting a complicated but powerful command to get the top ten CPU-eating processes on a computer, presented in a nice readable format:
Get-Process | Sort-Object CPU -Descending | Select-Object `
-First 10 | Format-Table Name,@{Name="CPU(Min)";Expression` ={"{0:F2}" -f($_.CPU/60)}} -Autosize
But who wants to type that ugly command repeatedly, or can even remember it from one day to the next?
Fortunately, PowerShell makes it easy to execute it using two methods. The first is to wrap the long command inside a function:
Function Get-TopCPU {
Get-Process | Sort-Object CPU -Descending | Select-Object `
-First 10 | Format-Table Name,@{Name="CPU(Min)";Expression` ={"{0:F2}" -f($_.CPU/60)}} -Autosize
}
Run all that in your PowerShell window, and thereafter we can get the information by simply typing:
Get-TopCPU
There. That was easy.
Unfortunately, the function will be lost as soon as we close the PowerShell window. If we want to keep a custom function permanently, we can add it to our PowerShell profile. (Enter 'notepad $profile' for a quick edit.)
Another way to keep the long ugly command is to enclose the command in quotes and redirect it to a script:
' Get-Process | Sort-Object CPU -Descending | Select-Object `
-First 10 | Format-Table Name,@{Name="CPU(Min)";Expression` ={"{0:F2}" -f($_.CPU/60)}} -Autosize ' > Get-TopCPU.ps1
Then, for as long as we have the script saved somewhere convenient, we can always launch it: