Search code examples
powershellprocesscommandadminprivileges

Start-Process does not run as expected


I want to write a PowerShell script to auto-install tools and set up configs after reinstalling OS. Almost command only needs user privilege, but some commands require admin privilege. Therefore, I need create the new progress with admin right and run that command there. I searched Google for that and I found Start-Progress

After that, I searched how to get the output of progress started by Start-Progress, but I can't find anything. Therefore, I think I need to copy the output to clipboard by using command like this:

Start-Process -FilePath "powershell.exe" -ArgumentList '-NoLogo -NoProfile -Command "echo hello | clip"' -Verb RunAs -Wait

Or write the output to the file like this and read the file to get the output of process:

Start-Process -FilePath "powershell.exe" -ArgumentList '-NoLogo -NoProfile -Command "echo hello > a.log"' -Verb RunAs -Wait

The first way runs well. The output as same as this command:

powershell.exe -NoLogo -NoProfile -Command "echo hello | clip"

But the second way is too weird. It doesn't create file a.log. However, this command runs as I expected:

powershell.exe -NoLogo -NoProfile -Command "echo hello > a.log"

According to my understanding, the Start-Process -FilePath "ex.exe" -ArgumentList "some_argument" -Verb RunAs is the same as we run the command ex.exe some_argument but with admin privilege. However, I may be misunderstood Start-Process command.

Could you explain it for me? Thank you very much.

I need explanation what differences between Start-Process -FilePath "ex.exe" -ArgumentList "some_argument" -Verb RunAs and ex.exe some_argument with admin right


Solution

  • Run

    Start-Process -FilePath "powershell.exe" -ArgumentList '-NoLogo -NoProfile -Command "echo hello > a.log;(dir a.log).FullName;pause"' -Verb RunAs -Wait.
    

    (Command echo hello > a.log;(dir a.log).FullName;pause). Then you see where the a.log file is created (supposedly C:\WINDOWS\system32\a.log)…


    Note: echo h1 | clip; echo h2 | clip; echo h3 | clip utilises clip.exe (the clipboard is overwritten on each use.)

    Use Set-Clipboard as follows:

    echo h1 | Set-Clipboard; echo h2 | Set-Clipboard -append; echo h3 | Set-Clipboard -append
    

    Then:

    • Get-Clipboard returns an array, and
    • Get-Clipboard -Raw returns a string, with ␍␊ as a delimiter ([System.Environment]::NewLine, in fact).

    To view full Windows clipboard history, press Windows logo+V. Read Enumerating Windows clipboard history in PowerShell as well.