1

I have a PowerShell script that starts a process:

$pythodDir, $argsOriginalList = $args

$pythonExePath = Join-Path $pythodDir "python.exe"
$argsList = @("--no-render") + $argsOriginalList
Start-Process -FilePath $pythonExePath -ArgumentList $argsList

I wish to see the full command line of the Start-Process for example:

C:\python\python.exe --no-render --arg1 value

I didn't find a flag to render the full command that Start-Process creates. Is there any way to verbose it?

nrofis
  • 8,975
  • 14
  • 58
  • 113
  • Use `Start-Process -PassThru` to make `Start-Process` return the associated `Process` object – Mathias R. Jessen Mar 15 '22 at 15:57
  • Yeah, I know. But can it help to print out the full command? – nrofis Mar 15 '22 at 15:59
  • @nrofis You might have the mental model backwards. Both `Start-Process` and the command line `python --foo bar` are two different ways of telling the operating system to start a process. `Start-Process` is *not* just something that simply automates the CLI (it works directly with .net objects which in turn interact with the os kernel). You can take a process object and reverse engineer the command that *could* have been used to start it from the cli, but its not *the* command that was used – George Mauer Mar 15 '22 at 16:48
  • @GeorgeMauer, thank you. I'm aware of that. I just wanted to show the command line to that caller in the log/output to see how the process started: what are the file path and the arguments. It is just for debugging and validation proposes – nrofis Mar 15 '22 at 21:52
  • To complement Cpt.Whale's helpful answer: In order to invoke _console_ applications, only ever use `Start-Process` _if you want them to open in a new window_ or run with _different credentials_; otherwise, invoke them _directly_ - see [this answer](https://stackoverflow.com/a/51334633/45375). [GitHub docs issue #6239](https://github.com/MicrosoftDocs/PowerShell-Docs/issues/6239) provides guidance on when use of `Start-Process` is and isn't appropriate. Also, providing pass-through arguments as an _array_ to `-ArgumentList` is, sadly, [problematic](https://stackoverflow.com/a/71271756/45375). – mklement0 Mar 15 '22 at 23:32
  • 1
    Thank you @mklement0. I do use different credentials but didn't mention it in the question for simplicity. Thank you for all the sources, it is important to summarize that knowledge. – nrofis Mar 16 '22 at 11:44

1 Answers1

2

You can get the command line by grabbing two properties from the ProcessInfo of the process you started:

# Capture the process object using -PassThru
$p = Start-Process -FilePath $pythonExePath -ArgumentList $argsList -PassThru

# Output the command line
($p.StartInfo.FileName,$p.StartInfo.Arguments) -join ' '

For example:

$p = Start-Process -FilePath 'Notepad.exe' -ArgumentList 'c:\folder\file.txt' -PassThru
($p.StartInfo.FileName,$p.StartInfo.Arguments) -join ' '

C:\WINDOWS\system32\notepad.exe C:\folder\file.txt
Cpt.Whale
  • 4,784
  • 1
  • 10
  • 16