I'd like to learn to execute a PowerShell command from another shell or language, e.g. Python os.system()
. What I want to achieve is the following:
- Execute the PowerShell command
- Tee the output to both the console and a file
- Return the command exit code
I think this gives an idea of what I would like to achieve, assuming to use cmd.exe as the caller environmnet:
powershell -NoProfile -command "& { cat foo.txt | Tee-Object ps-log.txt; exit $LASTEXITCODE }"
echo %errorlevel%
There are some problems here. First, I cannot use quotations in the command, e.g. :
powershell -NoProfile -command "& { cat `"foo bar.txt`" | Tee-Object ps-log.txt; exit $LASTEXITCODE }"
The cat
argument seems to be passed unquoted and so cat
looks for a 'bar.txt' parameter.
I think $LASTEXITCODE
is expanded soon, that is before cat
is executed.
&
is inconvenient to use, because it does not accept a single command line string including arguments. An alternative to &
is iex
, however I cannot use it from cmd.exe. In fact:
powershell -NoProfile -command {iex cat foo.txt}
returns:
iex cat foo.txt