Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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)"
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading