Asdfg
Asdfg

Reputation: 12213

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

$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

Upvotes: 2

Views: 2230

Answers (1)

Mathias R. Jessen
Mathias R. Jessen

Reputation: 174505

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)"

Upvotes: 5

Related Questions