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.
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
?
CodePudding user response:
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 })