I've seen the following a lot in PowerShell, but what does it do exactly?
$_
I've seen the following a lot in PowerShell, but what does it do exactly?
$_
The $_ is a $PSItem, which is essentially an object piped from another command. For example, running Get-Volume on my workstations returns Rows of PSItems, or objects
get-volume | select driveLetter,DriveType
driveLetter DriveType
----------- ---------
D Fixed
Fixed
C Fixed
A Removable
Driveletter and DriveType are properties Now, you can use these item properties when piping the output with $_.(propertyName). (Also remember % is alias for Foreach-Object) For example
$vol = get-volume | select driveLetter,DriveType
$vol | Foreach-Object {
if($_.DriveType -eq "Fixed") {
"$($_.driveLetter) is $($_.driveType)"}
else{
"$($_.driveLetter) is $($_.driveType)"
}
}
Using Terinary in Powershell 7, I am able to shorten the logic while using properties from the Piped PSItem