Author Posts

May 21, 2015 at 1:54 pm

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

May 21, 2015 at 1:56 pm

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]

May 21, 2015 at 1:58 pm

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

May 21, 2015 at 2:15 pm

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!

May 22, 2015 at 5:05 am

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