35
votes

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?

4

4 Answers

28
votes

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.

11
votes

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

9
votes

Go to C:\MyDirectory and try this:

.\MyCommand.cmd
0
votes

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!