Home > Back-end >  Why does this Powershell subexpression operator command not work?
Why does this Powershell subexpression operator command not work?

Time:03-22

I am trying to understand why a Powershell one liner I want to use to setup a port proxy to a WSL instance seemingly does not work, but running it without the grouping/substitution does work. Steps:

Get the IP address of WSL instance:

wsl hostname -I

> 172.18.108.185

Try one liner with the previous command as subexpression:

netsh interface portproxy add v4tov4 listenport=3443 `
listenaddress=0.0.0.0 connectport=3443 `
connectaddress=$(wsl hostname -I)

That seems to work because listing port proxies shows it:

netsh interface portproxy show v4tov4

> Listen on ipv4:             Connect to ipv4:
> 
> Address         Port        Address         Port
> --------------- ----------  --------------- ----------
> 0.0.0.0         3443        172.18.108.185  3443

(I have also tried it without the $.)

However, the proxy forwarding does not actually work.

If I then do the same command without the substitution:

netsh interface portproxy add v4tov4 listenport=3443 `
listenaddress=0.0.0.0 connectport=3443 `
connectaddress=172.18.108.185

The output looks exactly the same:

netsh interface portproxy show v4tov4

> Listen on ipv4:             Connect to ipv4:
> 
> Address         Port        Address         Port
> --------------- ----------  --------------- ----------
> 0.0.0.0         3443        172.18.108.185  3443

However, this time it works.

What is different between these two executions such that one works, one doesn't, and yet the results look exactly the same?

CodePudding user response:

Abraham Zinala provided the crucial pointer:

The output from wsl hostname -I - surprisingly - has a trailing space, which must be trimmed in order for the IP address represented by the output to be used as an argument passed to netsh:

netsh interface portproxy add v4tov4 listenport=3443 `
  listenaddress=0.0.0.0 connectport=3443 `
  connectaddress=$((wsl hostname -I).Trim())
  • Related