A PowerShell tip

| 1 Comment
Recently I had the pleasure of attempting to use 'netsh' output in PowerShell. The output was fine, the hard part was getting the output. The netsh command behaved differently than other cli utilities I've used, notably dsget. With dsget, this works:

$List = dsget user -name "$FName"
But with netsh, this very much didn't:

$List = netsh dhcp server \\dhcpsrv scope $ScopeID show clients 1
The failure was pretty clear in that "$ScopeID" was not actually being correctly interpreted before execution. It was actually passing "$ScopeID". In order to make that work, I had to call out by way of the Invoke-Expression cmdlet.

$List=invoke-expression "netsh dhcp server \\dhcpsrv scope $ScopeID show clients 1"

Invoke-Expression is pretty robust in that it'll do variable substitution before execution, very handy in scripts!

1 Comment

Another option would be to just put $ScopeID into a doubled quoted string and PowerShell will do the variable expansion before the command is evaluated - like:

netsh dhcp server \\dhcpsrv scope "$ScopeID" show clients 1

The reason the invoke-expression is expanding the variable is because you are passing it a string and string evaluation (including variable expansion in double quoted strings) happens first. You can get the same effect, without the Invoke-Expression command by wrapping the parameter in double quotes. Most native cmdlets (native powershell commands) will expand variables as part of their command line evaluation, but for native Win32 commands and batch files, double quoting the variable should work.