Powershell - 如果继续,请检查远程进程

时间:2013-08-20 17:49:27

标签: powershell

作为备份操作的一部分,我正在运行7zip命令将文件夹压缩为单个.7z文件。我使用InVoke-WMIMethod时没有任何问题。

示例:

$zip = "cmd /c $irFolder\7za.exe a $somedirectory.7z $somedirectory"
"InVoke-WmiMethod -class Win32_process -name Create -ArgumentList $zip -ComputerName $remotehost"

我的问题出现了,因为我的脚本继续,7za.exe进程尚未完成。然后我尝试从远程系统复制项目,它不完整或失败。

有人能指出我的方向,弄清楚如何识别7za.exe进程是否仍在运行,等到它死了,然后继续我的其余脚本?

我可以通过......来掌握从远程系统中拉出过程。

get-wmiobject -class Win32_Process -ComputerName $remotehost | Where-Object $_.ProcessName -eq "7za.exe"}

不确定如何将其转换为我的问题的可用信息。

回复更新:(由@dugas轻推)

这将为需要它的人提供一些反馈......

do {(Write-Host "Waiting..."),(Start-Sleep -Seconds 5)}
until ((Get-WMIobject -Class Win32_process -Filter "Name='7za.exe'" -ComputerName $target | where {$_.Name -eq "7za.exe"}).ProcessID -eq $null)

2 个答案:

答案 0 :(得分:4)

您可以使用Invoke-Command cmdlet在远程计算机上调用Wait-Process cmdlet。例如:

$process = Invoke-WmiMethod -Class Win32_Process -Name create -ArgumentList notepad -ComputerName RemoteComputer

Invoke-Command -ComputerName RemoteComputer -ScriptBlock { param($processId) Wait-Process -ProcessId $processId } -ArgumentList $process.ProcessId

由于您提到使用Invoke-Command不是一个选项,另一个选项是轮询。 例如:

$process = Invoke-WmiMethod -Class Win32_Process -Name create -ArgumentList notepad -ComputerName hgodasvccr01
$processId = $process.ProcessId

$runningCheck = { Get-WmiObject -Class Win32_Process -Filter "ProcessId='$processId'" -ComputerName hgodasvccr01 -ErrorAction SilentlyContinue | ? { ($_.ProcessName -eq 'notepad.exe') } }

while ($null -ne (& $runningCheck))
{
 Start-Sleep -m 250
}

Write-Host "Process: $processId is not longer running"

答案 1 :(得分:0)

你应该可以使用do ... while循环来完成它,直到进程完成为止。

 do { 
    "waiting"
    start-sleep 10 
    } while (gwmi -class win32_process -ComputerName $remotehost | Where ProcessName -eq "7za.exe")