Run a .cmd file through PowerShell

I am trying to run a .cmd file on a remote server with PowerShell.

In my .ps1 script I have tried this:

C:\MyDirectory\MyCommand.cmd

It results in this error:

C:\MyDirectory\MyCommand.cmd is not recognized as the name of a cmdlet,
function, script file, or operable program.

And this

Invoke-Command C:\MyDirectory\MyCommand.cmd

results in this error:

Invoke-Command : Parameter set cannot be resolved using the specified named
parameters.

I do not need to pass any parameters to the PowerShell script. What is the correct syntax that I am looking for?

5 Answers

Invoke-Item will look up the default handler for the file type and tell it to run it.

It's basically the same as double-clicking the file in Explorer, or using start.exe.

4

Go to C:\MyDirectory and try this:

.\MyCommand.cmd

Try invoking cmd /c C:\MyDirectory\MyCommand.cmd – that should work.

2

To run or convert batch files to PowerShell (particularly if you wish to sign all your scheduled task scripts with a certificate) I simply create a PowerShell script, for example, deletefolders.ps1.

Input the following into the script:

cmd.exe /c "rd /s /q C:\#TEMP\test1"
cmd.exe /c "rd /s /q C:\#TEMP\test2"
cmd.exe /c "rd /s /q C:\#TEMP\test3"

*Each command needs to be put on a new line, calling cmd.exe again.

This script can now be signed and run from PowerShell outputting the commands to command prompt / cmd directly.

It is a much safer way than running batch files!

First you can reach till that folder: cd 'C:\MyDirectory' and then use: ./MyCommand.cmd

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

You Might Also Like