I can manually open up PowerShell and run
wsl
ip addr show eth0 | grep 'inetb' | awk '{print $2}' | cut -d/ -f1
To get the IP address of the Ubuntu instance. But when I try to write a script for this (100 different ways) I always get some kind of error. This is an example
$command = "ip addr show eth0 | grep 'inetb' | awk '{print $2}' | cut -d/ -f1"
$ip = Invoke-Expression "wsl $command"
Which gives an error about grep
.
2
Answers
Call
wsl.exe
via the-e
option and specifybash
as the executable, which allows you to use the latter’s-c
option with a command line specified as a single string:A note re the choice of string literals on the PowerShell side:
Using
"..."
quoting rather than'...'
quoting is convenient if the text contains'
characters, because it obviates the need for escaping – ditto for the inverse scenario: using'...'
quoting for text that contains"
chars.However, as in POSIX-compatible shells such as Bash, the choice of the enclosing quoting characters matters in PowerShell, because the resulting behavior differs:
'...'
is a verbatim (single-quoted) string.'
chars. must be emulated with'''
, PowerShell does support direct escaping, namely with''
"..."
is an expandable (double-quoted) string, i.e. subject to string interpolation for substrings that start with$
$
chars. to be used verbatim (literally) require escaping as$
, in PowerShell you must use`$
, using`
, the so-called backtick, PowerShell’s escape character.Or let’s assume you have powershell installed in linux (there’s no Get-NetIPConfiguration?).
Or even without it, piping to windows powershell cmdlets.
$command has to be an array of words: