Declan McNulty
Declan McNulty

Reputation: 3374

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?

Upvotes: 39

Views: 157008

Answers (6)

sergtk
sergtk

Reputation: 10974

You many need to prepend the command with &:

& C:\MyDirectory\MyCommand.cmd

If path contains spaces, you need to use double quotes:

& "C:\MyDirectory\MyCommand.cmd"

Refer to Call operator & (invocation operator)

Upvotes: 0

SunilVeer
SunilVeer

Reputation: 1

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

Upvotes: 0

Gustavo A Sanchez
Gustavo A Sanchez

Reputation: 169

Go to C:\MyDirectory and try this:

.\MyCommand.cmd

Upvotes: 16

alroc
alroc

Reputation: 28154

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.

Upvotes: 34

Armand G.
Armand G.

Reputation: 1915

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!

Upvotes: 0

mirabilos
mirabilos

Reputation: 5317

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

Upvotes: 14

Related Questions