Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Parentheses around foreach in Powershell

For context, I’m trying to run multiple powershell commands in a single line of code so that I can use it in a Dockerfile.

($SubInterfaceInfo = netsh interface ipv4 show subinterface) -and ($vEthernetInterfaces = (($SubInterfaceInfo | Where-Object { $_ -match 'vEthernet' }) -split '\s\s')[-1]) -and (foreach($vEthernetInterface in $vEthernetInterfaces){ netsh interface ipv4 set subinterface $vEthernetInterface mtu=1460 })

When run, I get the error:

Unexpected token 'in' in expression or statement.

Individually all of these commands work, however, the parentheses around the foreach seems to be the cause of the problem.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

This command works:

foreach($vEthernetInterface in $vEthernetInterfaces){ netsh interface ipv4 set subinterface $vEthernetInterface mtu=1460 }

But this causes the error:

(foreach($vEthernetInterface in $vEthernetInterfaces){ netsh interface ipv4 set subinterface $vEthernetInterface mtu=1460 })

Is a way I can make the foreach command work inside the parentheses, or another way of using the foreach loop with -and?

>Solution :

The grouping operator, (...), is primarily meant for constructing nested pipelines, and you must therefore provide a valid pipeline expression (eg. call a cmdlet, evaluate a variable expression, etc.) as the first statement.

To nest control flow expressions like the foreach loop, use the subexpression operator $(...):

$(foreach($vEthernetInterface in $vEthernetInterfaces){ netsh interface ipv4 set subinterface $vEthernetInterface mtu=1460 })
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading