2017-01-21 74 views
2

我有這樣的腳本來殺死VNC進動,並重新啓動VNC服務:負載輸出變量直接PowerShell的

$ip = Read-Host 'Enter hostname or IP' 

& tasklist /s $ip /FI "IMAGENAME eq winvnc*" 

$procid_1 = Read-Host 'pid 1' 
$procid_2 = Read-Host 'pid 2' 

& taskkill /s $ip /pid $procid_1 
& taskkill /s $ip /pid $procid_2 

Stop-Service -InputObject $(Get-Service -Computer $ip -Name "uvnc_service") 
Start-Service -InputObject $(Get-Service -Computer $ip -Name "uvnc_service") 

此命令

& tasklist /s $ip /FI "IMAGENAME eq winvnc*" 

給了我這樣的輸出:

Image Name      PID Session Name  Session# Mem Usage 
========================= ======== ================ =========== ============ 
winvnc.exe     3576       0  2,968 K 
winvnc.exe     4444       0  5,556 K 

我必須手動輸入PID(在本例中爲3576和4444)變量$ procid_1和$ procid_2

有沒有辦法如何將任務列表輸出直接傳遞給變量?

在此先感謝您的任何提示! 約瑟夫

回答

2

使用Get-Process cmdlet的替代tasklist - Get-Process將輸出活生生的.NET對象,這樣你就可以直接搶Id財產使用點符號:

$RemoteComputer = Read-Host 'Enter hostname or IP' 

Get-Process -Name winvnc -ComputerName $RemoteComputer |ForEach-Object { 
    & taskkill /s $ip /pid $_.Id 
} 
+0

遺憾的是它給了我這個錯誤 '停止進程:功能不支持遠程機器。在C:\ Users \ barcuchj1-a \ Downloads \ Scripty_testing \ VNC \ VNC_restart_v0.1.ps1:3 char:46 + Get-Process -Name winvnc -ComputerName $ ip | Stop-Process -Force + ~~~~~~~~~~~~~~~~~~~ + CategoryInfo:NotSpecified:(:) [Stop-Process],NotSupportedException + FullyQualifiedErrorId:System.NotSupportedException, Microsoft.PowerShell.Commands.StopProcessCommand' – InLoveWithTux

+0

@InLoveWithTux更新回答 –

+0

優秀!你的解決方案就像一個魅力! '成功:PID 7564過程已終止。 成功:PID 7708過程已終止。' 非常感謝! – InLoveWithTux