我们希望用Start-Process -PassThru
运行一个进程,将ID存储在文件中,然后用这个存储的ID停止进程。或者更确切地说,在启动新的批时
- 读取存储的ID
- 使用此ID停止任何正在运行的进程
- 开始一个新的
- 存储新ID
# Change this to the proper path
$Root = \ServerShare$SomeFolder
# 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"
但$ID保持为空。
文件为空,因为您没有向Set-Content
提供任何输入:
$ID |Set-Content -Path $Root"process_id.txt"
# or
Set-Content -Path $Root"process_id.txt" -Value $ID
对于那些想要一份&粘贴:
# Change this to the proper path
$Root = \ServerShare$SomeFolder
# 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" -Value $ID