Home > Back-end >  In Powershell how to start a process, store the ID in a file, and later stop the process by this ID
In Powershell how to start a process, store the ID in a file, and later stop the process by this ID

Time:08-25

We want to run a process with Start-Process -PassThru store the ID in a file and later on Stop-Process with this stored ID. Or rather when starting a new batch

  1. Read the stored ID
  2. stop any running process by this ID
  3. start a new one and
  4. store the new ID
# Change this to the proper path
$Root = \\Server\Share$\
# Change this to the proper exe or command
$Command = "something"

# Get current ID, and stop the corresponding process
$ID = Get-Content $Root"\process_id.txt"
Stop-Process -ID $ID

# Start a new process and store the ID
$ID = (Start-Process -FilePath $Command -PassThru).Id
Set-Content -Path $Root"\process_id.txt"

But the $ID stays empty.

CodePudding user response:

The file is empty because you didn't supply Set-Content with any input:

$ID |Set-Content -Path $Root"\process_id.txt"
# or
Set-Content -Path $Root"\process_id.txt" -Value $ID
  • Related