【问题标题】:load output to variables directly powershell直接将输出加载到变量powershell
【发布时间】:2017-06-06 17:10:40
【问题描述】:

我有这个脚本可以杀死 VNC 进程并重新启动 VNC 服务:

$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

有什么方法可以将任务列表的输出直接传递给变量吗?

提前感谢您的任何提示! 约瑟夫

【问题讨论】:

    标签: powershell variables output


    【解决方案1】:

    使用 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
    }
    

    【讨论】:

    • 不幸的是它给了我这个错误Stop-Process : Feature is not supported for remote machines. At 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
    • 太棒了!您的解决方案就像一个魅力! SUCCESS: The process with PID 7564 has been terminated. SUCCESS: The process with PID 7708 has been terminated.非常感谢!
    猜你喜欢
    • 1970-01-01
    • 2014-01-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多