Running a shell command to run a separate program as admin space character issue!

Normally via cmd this is the way to run a command and to run the thing as admin!

powershell -command "&{Start-Process -filepath 'cmd' -argumentlist '/c cmd.exe' -verb

Now when I try to runt he same thing with Rust,

// Running shell scripts
use std::process::Command;

fn main()
{
    let output = Command::new("powershell.exe")
    .arg("powershell")
    .arg(format!("-command \"&{{Start-Process -filepath 'cmd' -argumentlist '/c \"{}\"' -verb runas}}\"", "C:\\Users\\Joe\\Desktop\\testing 1\\testing.bat"))
    .output()
    .unwrap();

    println!("{:?}", output);
}

It only works if there is no space character, but because there is a space character C:\\Users\\Joe\\Desktop\\testing 1\\testing.bat how would I fix this?

This looks like it would be solved by

https://github.com/rust-lang/rust/pull/85832

I would have expected -command and the PowerShell code to go as separate .arg() calls. There are some other things you could try:

  • Use -EncodedCommand to pass Base-64 encoded PowerShell code as a separate argument.
  • Use -Command - to pass the PowerShell code via the program’s stdin.
  • Most reliably, but with a more complicated build process, use ShellExecuteW with its runas verb to skip using PowerShell at all.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.