Array pipeline issue

This topic contains 4 replies, has 3 voices, and was last updated by  Matthew Tisdel 2 years, 5 months ago.

  • Author
    Posts
  • #25553

    Matthew Tisdel
    Participant

    Something about arrays is killing me, and this example would have saved me hours of work today. However, I could not make it work.
    This script was "supposed to run" on a Server 2012 R2 IIS server. I attempted a foreach statement, and it would resolve the variable with extra characters. (I wanted "website.com" but what I got was @{name.website.com} ) If this is the total wrong approach, then I am good with that. If you can point me to resources that educate me on this, then that would be the best result.

    $SiteArray = (get-website | select name)

    $SiteArray | foreach-object {New-WebVirtualDirectory -Site $_ -name "WebSiteLinks" -PhysicalPath 'E:\Websites\Links' -force}

    Thanks,
    Matt

  • #25554

    Dave Wyatt
    Moderator

    There are a couple of ways you could address that. One is to use [b]Select-Object -ExpandProperty[/b] (instead of -Property, which is the default position parameter when you just do "select name"). Or, you could put [b]-Site $_.Name[/b] in your ForEach-Object block, instead of just [b]-Site $_[/b]

  • #25555

    Dave Wyatt
    Moderator

    Incidentally, this is one of the items mentioned in the "Big Book of PowerShell Gotchas", which is free and available from this site. 🙂 https://www.penflip.com/powershellorg/the-big-book-of-powershell-gotchas/blob/master/properties-vs-values.txt

  • #25557

    Don Jones
    Keymaster

    The underlying problem here isn't arrays.

    Your original Select-Object was producing an object, which had a single property Name, which contained a String. Those vexing curly braces are PowerShell's way of representing an object; the shell is hardcoded to look for a Name property simply because most objects have one. Dave's -ExpandProperty is different, in that it *extracts* the value from the property and leaves just the simple string value, which is probably what you wanted.

    And +1 to the Gotchas book!

  • #25577

    Matthew Tisdel
    Participant

    That worked great, and I have learned something very useful. I am going to put the Gotcha book on my study list.

You must be logged in to reply to this topic.