I recently encountered a puzzling issue while using PowerShell's switch statement. I expected that when utilizing $PSItem within a switch block inside a ForEach-Object loop, it would still refer to the original object from the pipeline. Instead, I found that $PSItem gets altered to reference the switch expression, leading to no output. In my initial code, I had:
```powershell
$proc = Get-Process
$proc | foreach-object {
switch ($PSitem.Name) {
Default {$PSitem.Name}
}
}
```
I was hoping to see the output of $PSItem.Name, but there was none, as the variable didn't seem to exist in that scope anymore. After some digging, I realize that changing the Default case to just $PSItem made it functional, but then I lost track of the original value. Can someone elaborate on how $PSItem behaves within the switch statement?
3 Answers
You don’t actually need a loop with switch statements if you’re just doing a direct match:
```powershell
$proc = Get-Process
switch ($proc.ProcessName) {
Default { $_ }
}
```
Personally, I find foreach statements cleaner than using Foreach-Object with the $_ syntax. Here’s how I usually write it:
```powershell
$ProcessList = Get-Process
foreach ($process in $ProcessList) {
switch ($process.Name) {
Default { $process.Name }
}
}
```
Or even simpler:
```powershell
foreach ($process in Get-Process) {
switch ($process.Name) {
Default { $process.Name }
}
}
```
In the switch block, $PSItem doesn't refer to the outer pipeline item anymore. Instead, you can store the original item in a separate variable. Here's a clearer approach:
```powershell
$proc = Get-Process
$proc | ForEach-Object {
$innerProc = $_
switch ($innerProc.Name) {
Default { $innerProc.Name }
}
}
```

I always forget that this works - thanks for reminding me!