2016-09-16 4 views
0

Das folgende funktioniert, ist aber hässlich.Setzen Sie eine Variable und übergeben Sie sie durch

> 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 

Wir haben das versucht, aber es funktioniert nicht.

> 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 

Wie können wir machen Set-Variable arbeiten?

Antwort

1

Sie keinen Wert für die Variable in Ihrer Set-Variable Anrufeinstellung, und der Name soll nicht ein $ Symbol

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

hat Obwohl ich weiß nicht, wie/ob der Variablenwert trägt synchron mit der Pipeline oder wenn es nicht mehr synchron ist. Was ist mit

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

Hier ist Ihr Beispiel 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 
Verwandte Themen