powershell - 直接将输出加载到变量 powershell

标签 powershell variables output

我有这个脚本来终止 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

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

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

最佳答案

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

关于powershell - 直接将输出加载到变量 powershell,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41785222/

相关文章:

python打印输出不在同一行

powershell - 替换所有txt文件中的一个字符

powershell - 获取 NetFirewallRule 用户{GUIDE}

c++ - 如果不在结构中初始化 vector ,它会自动为空还是会具有随机内存位置的值?

c - C中字符的转置

Hadoop 1 个输入文件 = 1 个输出文件,仅映射

powershell - Azure PowerShell 剪贴板的使用

powershell - 如何使用 PowerShell 取得文件所有权?

javascript - 将 PHP 数组转换为 JS 变量

java - 单击适配器 View