2016-09-16 5 views
0

以下は動作しますが醜いです。変数を設定してそれを渡します

> 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

あなたは、セット変数の呼び出しで変数の値を設定していない、と私はどのように/もし変数の値を知りませんが、名前が$記号

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 
関連する問題