Home > Net >  PowerShell netsh inline command not working properly
PowerShell netsh inline command not working properly

Time:10-19

When I run

PS C:\WINDOWS\system32> wsl hostname -I
172.27.96.44
PS C:\WINDOWS\system32> netsh interface portproxy add v4tov4 listenport=3000 connectport=3000 connectaddress=172.27.96.44
PS C:\WINDOWS\system32> netsh interface portproxy show all

Listen on ipv4:             Connect to ipv4:

Address         Port        Address         Port
--------------- ----------  --------------- ----------
*               3000        172.17.218.173  3000

It works, the target address is accesible. But when I run

netsh interface portproxy add v4tov4 listenport=3000 connectport=3000 connectaddress=$(wsl hostname -I)

PS C:\WINDOWS\system32>  netsh interface portproxy show all

Listen on ipv4:             Connect to ipv4:

Address         Port        Address         Port
--------------- ----------  --------------- ----------
*               3000        172.27.96.44    3000

The target address is not accesible. It just doesn't respond. Even despite the fact that it is shown in the table. I tried string conversions e.g.

netsh interface portproxy add v4tov4 listenport=3000 connectport=3000 connectaddress=([string] (wsl hostname -I));

But it didn't help. Why it doesn't work even when the ip address is in the table?

CodePudding user response:

If you take the output of your WSL command and a verbatim string of what you believe is the same value and compare the actual bytes with Format-Hex, you will see there is a difference.

$output = WSL hostname -I

$output | Format-Hex


           00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F

00000000   31 39 32 2E 31 36 38 2E 31 2E 36 38 20           192.168.1.68

VS

'192.168.1.68' | Format-Hex


           00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F

00000000   31 39 32 2E 31 36 38 2E 31 2E 36 38              192.168.1.68

So it's adding a value, a 20. I took a guess and it is indeed a space.

$output -replace '\s' | Format-Hex

           00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F

00000000   31 39 32 2E 31 36 38 2E 31 2E 36 38              192.168.1.68

So you can solve this various ways but as shown it can be as simple as.

$output = (WSL hostname -I) -replace '\s'

You can always test the contents of your variable. I regularly do something like this just for a sanity check. It would've definitely saved you here.

$output = WSL hostname -I

Write-Host "A$($output)A"

A192.168.1.68 A
  • Related