Home > Mobile >  Write-Host prints entire object instead of one property of it when surrounded by quotes
Write-Host prints entire object instead of one property of it when surrounded by quotes

Time:12-10

$AllDrivesExceptBootDrive = Get-Volume | Where-Object {$_.DriveLetter -ne 'C'} | Select-Object DriveLetter, AllocationUnitSize

foreach ($d in $AllDrivesExceptBootDrive)
{
    Write-Host "Checking Drive $d.DriveLetter"
}

Prints:

Checking Drive @{DriveLetter=F; AllocationUnitSize=4096}.DriveLetter
Checking Drive @{DriveLetter=G; AllocationUnitSize=4096}.DriveLetter
Checking Drive @{DriveLetter=E; AllocationUnitSize=4096}.DriveLetter
Checking Drive @{DriveLetter=H; AllocationUnitSize=4096}.DriveLetter
Checking Drive @{DriveLetter=I; AllocationUnitSize=4096}.DriveLetter

How do I keep quotes around Write-Host and still print it as below?

Checking Drive F
Checking Drive G
Checking Drive E
Checking Drive H
Checking Drive I

CodePudding user response:

From the about_Quoting_Rules help topic:

Only simple variable references can be directly embedded in an expandable string. Variables references using array indexing or member access must be enclosed in a subexpression.

Change the string literal to surround the expression with the subexpression operator $(), like this:

Write-Host "Checking Drive $($d.DriveLetter)"
  • Related