Access variable attributes using Write-Output in PowerShell

Access variable attributes using Write-Output in PowerShell

Q. How do I access an attribute of a variable in PowerShell using Write-Output?

A. If you have an object that you want to output a parameter from it using Write-Output it does not behave as you would expect. For example:

Write-Output "Name of VM is $VM.VMName"

This would actually output the VM object then .VMName as text. What is actually required is a subexpression and this is used as follows:

Write-Output "Name of VM is $($VM.VMName)"

Note the subexpression is performed using $(<to be evaluated>).

Hide comments

Comments

  • Allowed HTML tags: <em> <strong> <blockquote> <br> <p>

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
Publish