Pipeline variable expansion within double quotes

Welcome Forums General PowerShell Q&A Pipeline variable expansion within double quotes

Viewing 3 reply threads
  • Author
    Posts
    • #245283
      Participant
      Topics: 12
      Replies: 38
      Points: 281
      Helping Hand
      Rank: Contributor

      I have a simple script backing up config files for a couple of programs and everything works pretty much as i want it to, but I’m a little surprised by one thing.
      I have PSCustomObjects for each config file and each object contains a Name, Path and Destination variable. The script uses a Foreach-Object to iterate over an array containing the objects and as part of the Foreach-Object loop it checks if the destination file already exists, and if so it writes a warning that I’ve already backed up the file once today.

      I had to write the warning in two lines like this:

      I thought I would be able to use simple variable expansion like this to

      But using that syntax Powershell expands the entire PSCustomObject into the text rather than just the Name variable. Am I missing something or is that expected behavior?

    • #245286
      Participant
      Topics: 11
      Replies: 127
      Points: 762
      Helping Hand
      Rank: Major Contributor

      When referencing an object’s member (property or method) in string such as you are, you need to use a subexpression to do so:

    • #245292
      Participant
      Topics: 12
      Replies: 38
      Points: 281
      Helping Hand
      Rank: Contributor

      Thank you!

      I’m pretty sure I’ve bumped into a version of this previously but managed to forget about it again.

      /KLaage

    • #245325
      Participant
      Topics: 13
      Replies: 1753
      Points: 3,136
      Helping Hand
      Rank: Community Hero

      I always use string format:

Viewing 3 reply threads
  • You must be logged in to reply to this topic.