A process in windows can be in any of the six states i.e, running, ready, blocked, suspend, new and exit. How to know the state a given process (name, ID) using powershell in windows.
In UNIX this information is stored in /proc/$processid/status file. Where is it found in windows or how to get this information in powershell.
"exit" status is signified by the presense of "exit code" property (natively returned by GetExitCodeProcess()). In PS, it is reflected by HasExited and ExitCode fields in Get-Process (alias ps).
ps | where {$_.Id -eq <PID>} | select HasExited,ExitCode
"running/wait/suspended" in Windows is a status of a thread rather than process ("suspend" being one of several Wait substates). I didn't find any info on getting thread information by PS's built-in means but we can call the corresponding .NET functionality:
$process=[System.Diagnostics.Process]::GetProcessById(<PID>)
$threads=$process.Threads
$threads | select Id,ThreadState,WaitReason
You are right, that's an interesting point. A way to find out about the state the process is the following way :
$ProcessActive = Get-Process outlook -ErrorAction SilentlyContinue
if($ProcessActive -eq $null)
{
Write-host "I am not running"
}
else
{
Write-host "I am running"
}
If outlook would not be a running process, it would not be listed but -ErrorAction SilentlyContinue will simply continue and return an I am not running
If it's running it will send you an I am running
I am not aware of other states of a process... at least not how to dertermine
Related
I'm trying to launch Windows applications using their AppID such as Microsoft.WindowsCalculator_8wekyb3d8bbwe!App which I get by calling Get-StartApps
Currently I can launch the applications but can't get the correct PID
cmd = exec.Command("powershell", "start", `shell:AppsFolder\Microsoft.WindowsCalculator_8wekyb3d8bbwe!App`)
err := cmd.Start()
fmt.Println(cmd.Process.Pid)
This returns the PID of powershell
C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe start shell:AppsFolder\Microsoft.WindowsCalculator_8wekyb3d8bbwe!App
Is there a way to launch the application by the AppID and still get the correct PID?
tl;dr
// Make PowerShell not only launch Calculator, but also
// determine and output its PID, as described in the next section.
out, _ :=
exec.Command(
`powershell.exe`,
`-NoProfile`,
`-Command`,
`Start-Process -ErrorAction Stop calculator: ; (Get-Process Calculator | Where-Object SessionId -eq (Get-Process -ID $PID).SessionId).ID`,
).Output()
// Parse stdout output, which contains the PID, into an int
var pid int
fmt.Sscanf(string(out), "%d\n", &pid)
In principle, you can pass -PassThru to PowerShell's Start-Process (start) cmd, which returns a process-info object that has an .Id property containing the launched process' PID, and output the latter.
Unfortunately, with UWP / AppX applications specifically, such as Calculator, this does not work, which is a problem that exists in the underlying .NET APIs, up to at least .NET 6.0 - see GitHub issue #10996.
You can try the following workaround:
Launch the AppX application with Start-Process, which indirectly creates a process whose name is Calculator (Windows 10) / CalculatorApp (Windows 11).
You can identify this name yourself if you run (Get-Process *calc*).Name after launching Calculator. Get-Process *calc* | Select-Object Name, Path would show the executable path too, but note that this executable should be considered an implementation detail and can not be invoked directly.
Return the ID of that Calculator / CalculatorApp process. The fact that Calculator only ever creates one such process in a given user session actually makes identifying that process easy.
Note that this means that the PID of a preexisting Calculator process may be returned, which, however, is the correct one, because the transient process launched by Start-Process simply delegates creation of a new Calculator window to an existing process.
If you wanted to identify the newly created window, more work would be required: You'd have to enumerate the process' windows and identify the one with the highest z-order.
PowerShell code (note: in Windows 11, replace Calculator with CalculatorApp):
# Launch Calculator - which may reuse an existing instance and
# merely create a new *window* - and report the PID.
Start-Process -ErrorAction Stop calculator:
(Get-Process Calculator | Where-Object SessionId -eq (Get-Process -ID $PID).SessionId).ID
Note that I've used the URL scheme calculator: as a simpler way to launch Calculator.
Note:
The Where-Object SessionId -eq (Get-Process -ID $PID).SessionId guards against mistakenly considering potential Calculator processes created by other users in their own sessions (Get-Process returns all processes running on the local machine, across all user sessions). Filtering by .SessionID, i.e. by the active user session (window station), prevents this problem.
As a PowerShell CLI call:
powershell.exe -NoProfile -Command "Start-Process -ErrorAction Stop calculator: ; (Get-Process Calculator | Where-Object SessionId -eq (Get-Process -ID $PID).SessionId).ID"
I have a powershell script that needs to run 24 * 7.
To make sure it does this, I have created two (almost) identical tasks listed in task scheduler. One starts the task every day at midnight, the other is set to run with the trigger 'At System startup'. The script is set to exit at a minute to midnight.
So far so good, everything works fine. All my bases are covered. The scheduled task takes care of the script 99% of the time, and the 'on startup' task covers the occasional power-failure
However, I've noticed a subtle difference when I look at the process details.
If I open a powershell session and check the pid for the task that started at midnight using this -
PS C:\Users\Elvis> get-wmiobject win32_process | where{$_.ProcessId -eq nnnn}
(where nnnn is the PID) I see lots of details listed, including this....
CommandLine : "C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" -NoExit -command "&c:\myDir\myScript.ps1"
This makes sense, it's exactly what I put into the task definition.
If do a similar thing with the task that starts on boot-up, then instead of seeing the full command line I just get
CommandLine :
This may not seem important, but I want to check that no other versions of the script are running when I start a new copy. I do this by including this line in the script. (basically it checks for other powershell process running the same script name but with a different PID)
get-wmiobject win32_process | where{$_.processname -eq 'powershell.exe' -and $_.ProcessId -ne $pid -and $_.commandline -match 'myScript'}
I need to be able to either persuade the task scheduler to include the script name in the process details, or find another way to check if there's another copy of the script already running
Use what I call a "PID lockfile". Write the PID to a known file path, if the file already exists, check for the PID. If it's already running, throw an error or otherwise exit. When the script exits have it delete that file.
$lockfilePath = "\path\to\script.pid"
try {
if( Test-Path -PathType Leaf $lockFilePath ) {
$oldPid = ( Get-Content -Raw $lockfilePath ).Trim()
if( Get-Process -Id $oldPid -EA SilentlyContinue ) {
throw "Only one instance of this script can run at a time"
}
}
$PID > $lockfilePath
# Rest of your script goes within this try block
} finally {
# Add a catch block if you like but this finally code
# guarantees a deletion attempt will be made on the
# PID file whether the try block succeeds or errors
if( Test-Path -PathType Leaf $lockfilePath ) {
Remove-Item $lockfilePath -Force -EA Continue
}
}
I have a powershell script that launches an exe process. I have a task scheduled to run this powershell script on computer idle, and I have it set to stop it when it's not idle.
The problem is task schedule doesn't kill the launched exe process, I'm assuming it's just trying to kill the powershell process.
I can't seem to find a way to make the launched exe as a subprocess of a powershell.exe when it's launched from task scheduler
I've tried launching the process with invoke-expression, start-proces, I've also tried to pipe to out-null, wait-process, etc.. nothing seems to work when ps1 is launched from task scheduler.
Is there a way to accomplish this?
Thanks
I don't think there is an easy solution for your problem since when a process is terminated it doesn't receive any notifications and you don't get the chance to do any cleanup.
But you can spawn another watchdog process that watches your first process and does the cleanup for you:
The launch script waits after it has nothing else to do:
#store pid of current PoSh
$pid | out-file -filepath C:\Users\you\Desktop\test\currentposh.txt
$child = Start-Process notepad -Passthru
#store handle to child process
$child | Export-Clixml -Path (Join-Path $ENV:temp 'processhandle.xml')
$break = 1
do
{
Sleep 5 # run forever if not terminated
}
while ($break -eq 1)
The watchdog script kills the child if the launch script got terminated:
$break = 1
do
{
$parentPid = Get-Content C:\Users\you\Desktop\test\currentposh.txt
#get parent PoSh1
$Running = Get-Process -id $parentPid -ErrorAction SilentlyContinue
if($Running -ne $null) {
$Running.waitforexit()
#kill child process of parent posh on exit of PoSh1
$child = Import-Clixml -Path (Join-Path $ENV:temp 'processhandle.xml')
$child | Stop-Process
}
Sleep 5
}
while ($break -eq 1)
This is maybe a bit complicated and depending on your situation can be simplified. Anyways, I think you get the idea.
I have 4-5 process (like java.exe, javaw.exe etc) having username "OWNER"(suppose). Below is the script that filters the java.exe process and kills it if it belongs to "OWNER". I need your help to modify this so that any process related to "OWNER" would be killed if found.
Just do it with Get-Process:
get-process -IncludeUserName | where username -like $username | stop-process
Basically your whole script can be replaced with this line
Get-Process with -IncludeUsername switch is only available in WMF 5.0.
WMI is the option here.
You could probably terminate the process just by checking the owner equals to the corresponding user.
Get-WmiObject -Class Win32_Process | Where-Object -FilterScript {
$_.GetOwner.User -eq "$Owner" } | Invoke-WmiMethod -Name Terminate
Edit: The above code is a one liner, you could save the out put of Get-WmiObject in a variable and for foreach through the collection to print the process id and call the terminate() method instead of using Invoke-WmiMethod.
Note:This code is not tested
I am writing a batch script in PowerShell v1 that will get scheduled to run let's say once every minute. Inevitably, there will come a time when the job needs more than 1 minute to complete and now we have two instances of the script running, and then possibly 3, etc...
I want to avoid this by having the script itself check if there is an instance of itself already running and if so, the script exits.
I've done this in other languages on Linux but never done this on Windows with PowerShell.
For example in PHP I can do something like:
exec("ps auxwww|grep mybatchscript.php|grep -v grep", $output);
if($output){exit;}
Is there anything like this in PowerShell v1? I haven't come across anything like this yet.
Out of these common patterns, which one makes the most sense with a PowerShell script running frequently?
Lock File
OS Task Scheduler
Infinite loop with a sleep interval
Here's my solution. It uses the commandline and process ID so there's nothing to create and track. and it doesn't care how you launched either instance of your script.
The following should just run as-is:
Function Test-IfAlreadyRunning {
<#
.SYNOPSIS
Kills CURRENT instance if this script already running.
.DESCRIPTION
Kills CURRENT instance if this script already running.
Call this function VERY early in your script.
If it sees itself already running, it exits.
Uses WMI because any other methods because we need the commandline
.PARAMETER ScriptName
Name of this script
Use the following line *OUTSIDE* of this function to get it automatically
$ScriptName = $MyInvocation.MyCommand.Name
.EXAMPLE
$ScriptName = $MyInvocation.MyCommand.Name
Test-IfAlreadyRunning -ScriptName $ScriptName
.NOTES
$PID is a Built-in Variable for the current script''s Process ID number
.LINK
#>
[CmdletBinding()]
Param (
[Parameter(Mandatory=$true)]
[ValidateNotNullorEmpty()]
[String]$ScriptName
)
#Get array of all powershell scripts currently running
$PsScriptsRunning = get-wmiobject win32_process | where{$_.processname -eq 'powershell.exe'} | select-object commandline,ProcessId
#Get name of current script
#$ScriptName = $MyInvocation.MyCommand.Name #NO! This gets name of *THIS FUNCTION*
#enumerate each element of array and compare
ForEach ($PsCmdLine in $PsScriptsRunning){
[Int32]$OtherPID = $PsCmdLine.ProcessId
[String]$OtherCmdLine = $PsCmdLine.commandline
#Are other instances of this script already running?
If (($OtherCmdLine -match $ScriptName) -And ($OtherPID -ne $PID) ){
Write-host "PID [$OtherPID] is already running this script [$ScriptName]"
Write-host "Exiting this instance. (PID=[$PID])..."
Start-Sleep -Second 7
Exit
}
}
} #Function Test-IfAlreadyRunning
#Main
#Get name of current script
$ScriptName = $MyInvocation.MyCommand.Name
Test-IfAlreadyRunning -ScriptName $ScriptName
write-host "(PID=[$PID]) This is the 1st and only instance allowed to run" #this only shows in one instance
read-host 'Press ENTER to continue...' # aka Pause
#Put the rest of your script here
If the script was launched using the powershell.exe -File switch, you can detect all powershell instances that have the script name present in the process commandline property:
Get-WmiObject Win32_Process -Filter "Name='powershell.exe' AND CommandLine LIKE '%script.ps1%'"
Loading up an instance of Powershell is not trivial, and doing it every minute is going to impose a lot of overhead on the system. I'd just scedule one instance, and write the script to run in a process-sleep-process loop. Normally I'd uses a stopwatch timer, but I don't think they added those until V2.
$interval = 1
while ($true)
{
$now = get-date
$next = (get-date).AddMinutes($interval)
do-stuff
if ((get-date) -lt $next)
{
start-sleep -Seconds (($next - (get-date)).Seconds)
}
}
This is the classic method typically used by Win32 applications. It is done by trying to create a named event object. In .NET there exists a wrapper class EventWaitHandle, which makes this easy to use from PowerShell too.
$AppId = 'Put-Your-Own-GUID-Here!'
$CreatedNew = $false
$script:SingleInstanceEvent = New-Object Threading.EventWaitHandle $true, ([Threading.EventResetMode]::ManualReset), "Global\$AppID", ([ref] $CreatedNew)
if( -not $CreatedNew ) {
throw "An instance of this script is already running."
}
Notes:
Make sure $AppId is truly unique, which is fullfilled when you use a random GUID for it.
The variable $SingleInstanceEvent should exist as long as the script is running. Putting it in the script scope as I did above, should normally be sufficient.
The event object is created in the "Global" kernel namespace, meaning it blocks execution even if the script is already running in another client session (e. g. when multiple users are logged onto the same machine). Replace "Global\$AppID" by "Local\$AppID" if you want to prevent multiple instances from running within the current client session only.
This doesn't have a race condition like the WMI (commandline) solution, because the OS kernel makes sure that only one instance of an event object with the same name can be created across all processes.
I'm not aware of a way to do what you want directly. You could consider using an external lock instead. When the script starts it changes a registry key, creates a file, or changes a file contents, or something similar, when the script is done it reverses the lock. Also at the top of the script before the lock is set there needs to be a check to see the status of the lock. If it is locked, the script exits.
$otherScriptInstances=get-wmiobject win32_process | where{$_.processname -eq 'powershell.exe' -and $_.ProcessId -ne $pid -and $_.commandline -match $($MyInvocation.MyCommand.Path)}
if ($otherScriptInstances -ne $null)
{
"Already running"
cmd /c pause
}else
{
"Not yet running"
cmd /c pause
}
You may want to replace
$MyInvocation.MyCommand.Path (FullPathName)
with
$MyInvocation.MyCommand.Name (Scriptname)
It's "always" best to let the "highest process" handle such situations. The process should check this before it runs the second instance. So my advise is to use Task Scheduler to do the job for you. This will also eliminate possible problems with permissions(saving a file without having permissions), and it will keep your script clean.
When configuring the task in Task Scheduler, you have an option under Settings:
If the task is already running, then the following rule applies:
Do not start a new instace