Reputation: 141424
The following works but is ugly.
> 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
We've tried this, but it doesn't work.
> 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
How can we make Set-Variable
work?
Upvotes: 0
Views: 177
Reputation: 28963
You aren't setting a value for the variable in your set-variable call, and the name shouldn't have a $ symbol
PS C:\> 1,2,3 | ForEach { Set-Variable -Name c -Value $_ -PassThru } | ForEach { "-$c-" }
-1-
-2-
-3-
Although I don't know how/if the variable value carries in sync with the pipeline or if it can get out of sync. What about
$names = foreach ($c in Get-CimInstance win32_process | Select -First 5) {
write $c.ProcessName
}
Here it is using your example of 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
Upvotes: 1