设置变量并通过它

时间:2016-09-16 01:57:39

标签: powershell

以下作品但很难看。

> Get-CimInstance win32_process | `
    select -first 5
    foreach { $process = $_; $process; } |     # this is ugly
    foreach { write $process.ProcessName }

System Idle Process
System
smss.exe
csrss.exe
wininit.exe

我们已经尝试过了,但它并没有奏效。

> Get-CimInstance win32_process | 
    select -first 5
    foreach { Set-Variable $c -PassThru } |    # this is prettier
    foreach { write $c.ProcessName }

wininit.exe
wininit.exe
wininit.exe
wininit.exe
wininit.exe

我们如何让Set-Variable工作?

1 个答案:

答案 0 :(得分:1)

您没有在set-variable调用中为变量设置值,并且名称不应该有$符号

PS C:\> 1,2,3 | ForEach { Set-Variable -Name c -Value $_ -PassThru } | ForEach { "-$c-" }
-1-
-2-
-3-

虽然我不知道变量值是如何/与流水线同步的,或者它是否可能不同步。

怎么样?
$names = foreach ($c in Get-CimInstance win32_process | Select -First 5) {
    write $c.ProcessName
}

这里使用的是CimInstance

的示例
PS C:\> Get-CimInstance win32_process | `
    select -first 5 | ` 
    foreach { Set-Variable -name process -value $_ -PassThru } | ` 
    foreach { write $process.ProcessName }

System Idle Process
System
smss.exe
csrss.exe
wininit.exe
相关问题