How do I pass an instruction to cmd.exe from a PowerShell command?

23,702

The Start-Process cmdlet assumes that the first parameter (-FilePath, specifically) is only the filename of the program to run. That's why you were getting "cannot find the file specified" errors. The -ArgumentList option is designed to pass parameters. Therefore, this should do what you want:

powershell -Command "Start-Process 'cmd' -Verb RunAs -ArgumentList '/c calc && exit'"

Note that you might not even need the && exit part in some circumstances.

Share:
23,702

Related videos on Youtube

benscabbia
Author by

benscabbia

Updated on September 18, 2022

Comments

  • benscabbia
    benscabbia over 1 year

    I have a batch file which runs a command (that is in another batch file) in administrative mode via:

    //instructions above
    
    powershell.exe -Command "Start-Process file.bat -Verb RunAs" 
    
    //instructions below
    

    file.bat simply contains:

    iisreset
    exit
    

    I want to be able to run this directly in a single batch file. Can this be done? I was hoping for somthing like:

     powershell.exe -Command "Start-Process 'iisReset && exit' -Verb RunAs" 
    

    But this does not work.

  • benscabbia
    benscabbia almost 8 years
    looks promising, I will test it on my main machine tomorrow morning! Is it possible using the method above to pass in multi-line instructions? Or would I need to call the command above for each instruction requiring admin privileges?
  • Ben N
    Ben N almost 8 years
    Unfortunately, the command processor seems to cut off everything after the first line. You might be able to string more commands together with &&. If you have more complicated logic to run, you might have to have an external batch file (though you could assemble it on the fly with echo ... >> ...).
  • benscabbia
    benscabbia almost 8 years
    +1 works great, thank you! Do you have links with some documentation on this, particularly to do with assembling batch files on the fly (I will do some research anyway so not to worry if not :)
  • Ben N
    Ben N almost 8 years
    @gudthing This Stack Overflow answer shows how to create a multi-line text file using echo commands. It works for batch files too, you just have to be careful to escape %variables%.
  • benscabbia
    benscabbia almost 8 years
    brilliant! You've been incredibly helpful, thank you so much :)!