Innocent code snippet:
- $processes = Get-Process -Name powershell* -Verbose
- If ($processes.count -gt 1) {
- "There are several powershell consoles"
- } ElseIf ($processes.count -eq 1) {
- "There is one powershell console"
- } Else {
- "There are no powershell consoles at all"
- }
But PowerShell runtime does a following thing:
- If cmdlet returns several objects, it wraps them in object[]
- If only one object is returned to pipe, it returns the object itself (Process class instance in our case)
- If no results are returned, it returns $null
The preferred way to work with cmdlet output is pipeline, so most clean and robust solution will be:
- $powershellConsoles = 0
- Get-Process -Name powershell* | ForEach-Object { $powershellConsoles++ }
- # First way, generic
- If ($powershellConsoles -gt 1) {
- "There are several powershell consoles"
- } ElseIf ($powershellConsoles -eq 1) {
- "There is one powershell console"
- } Else {
- "There are no powershell consoles at all"
- }
Also, you can handle output like that:
- $processes = Get-Process -Name powershell*
- # First way, generic
- If ($processes -is [array]) {
- "There are several powershell consoles"
- } ElseIf ($processes -ne $null) {
- "There is one powershell console"
- } Else {
- "There are no powershell consoles at all"
- }
- # Second way, straight typed
- If ($processes -is [array]) {
- "There are several powershell consoles"
- } ElseIf ($processes -is [System.Diagnostics.Process]) {
- "There is one powershell console"
- } Else {
- "There are no powershell consoles at all"
- }
Also, notice, that default cmdlets behavior is to write error, if explicit conditions were determined:
- # Will silently return $null, if there are no jobs at all
- Get-Job
- # Will return null and error message, if there are no jobs reaching conditions
- Get-Job -Name NonexistableJob
No comments:
Post a Comment