Reputation: 3301
I'm new to this Powershell lark, and I understood that Stop-Process
should be sufficient to end a task. However, it didn't close the newly created window and it left me uncertain if the process had stopped or not.
But, after doing some ID checking, I discovered that the process ID had been removed from the list. Is it, therefore, best practice to call Stop-Process
and then CloseMainWindow()
... or is CloseMainWindow()
sufficient on its own?
Cls
$notepadId = Start-Process notepad -passthru
Echo "" "notepadId = "
Echo $notepadId.Id
Echo "" "Current Notepad tasks:"
Get-Process notepad
Start-Sleep -s 2
Echo "" "Stopping Task:"
Stop-Process $notepadId.Id -Force
Echo "" "Closing Window:"
(Get-Process -Id $notepadId.Id).CloseMainWindow()
Start-Sleep -s 2
Echo "" "Tasks remaining:"
Get-Process notepad
Pause
Upvotes: 1
Views: 833
Reputation: 6874
I don't know why it's not working for you, but here's how I'd write it:
Cls
$notepadProcess = Start-Process notepad -passthru
Start-Sleep -s 2
Stop-Process $notepadProcess
The return-value from Start-Process is actually a Process object, not just the ID. If you pass that process object to Stop-Process, it knows what to do. However, a few experiments suggest that Stop-Process is not synchronous, so if you do this:
Cls
$notepadProcess = Start-Process notepad -passthru
Start-Sleep -s 2
Stop-Process $notepadProcess
get-process Notepad -ErrorAction Ignore
You will probably still see the process listed, however a few hundred milliseconds sleep before the Get-Process command should be sufficent to eliminate it.
Upvotes: 1