Page 1 of 1

Format Script hoses foreach loops in some cases.

Posted: Mon Jul 14, 2014 7:11 am
by Eurisko
In PowerShell Studio 4.1.62, when I hit Format Script, it hoses several foreach statements in my code. Is there something I'm doing wrong?

What should look like this:
$erc_xml.configuration.InstanceConfigurationData.InstanceConfiguration.add | foreach { If ($_.AdfsWhr -eq $Identifier)
...
Ends up like this:
$erc_xml.configuration.InstanceConfigurationData.InstanceConfiguration.add | foreach
{
If ($_.AdfsWhr -eq $Identifier)
{...
By putting the command for the foreach on the next line, foreach won't work correctly. I had to go through and fix a bunch of these after being bit by it today. Is there something I can do to avoid this?

Re: Format Script hoses foreach loops in some cases.

Posted: Mon Jul 14, 2014 8:12 am
by davidc
Leave it to PowerShell to use same word as keyword and cmdlet. Our parser is treating foreach as a keyword in this case instead of a cmdlet.

Until we resolve this, I recommend using the Foreach-Object (or any other alias) instead of foreach.


David

Re: Format Script hoses foreach loops in some cases.

Posted: Mon Jul 14, 2014 11:58 am
by Eurisko
Isn't there a difference in performance between Foreach vs Foreach-Object?

Several articles imply that they work a little differently and performance can be drastically different in some situations.

Re: Format Script hoses foreach loops in some cases.

Posted: Mon Jul 14, 2014 1:07 pm
by davidc
When you are using the pipeline, you are using the Foreach-Object cmdlet which is slower then the foreach construct:
PowerShell Code
Double-click the code block to select all.
foreach ($item in $items)
{
...
}
But it really depends on what you are doing. Sometimes the Foreach-Object cmdlet may be the easier way.

David