John
John

Reputation: 971

How to Launch batch file remotely in a command prompt using powershell

I'm trying to launch a batch file in a cmd window on a remote machine using powershell.

This is my ps1 script.

function Run-BatchFile
{
     param($computer = "mycomputer")
     $batfilename = "mybatch.bat"
     Invoke-Command -ComputerName $computer -ScriptBlock {param($batfilename) "cmd.exe /c C:\Batchfiles\$batfilename" } -ArgumentList $batfilename -AsJob
}

Run-BatchFile

When I run it from myhost machine I get this output..

Id     Name            PSJobTypeName   State         HasMoreData     Location             Command
--     ----            -------------   -----         -----------     --------             -------
5      Job5            RemoteJob       Running       True            mycomputer           param($batfilename) "c...

But no command prompt and batch file are launched on the remote machine.

Any clues as to what I am doing wrong or how to debug this as it looks like it works ok.

Thanks,

John.

Upvotes: 0

Views: 6717

Answers (2)

Titus1024
Titus1024

Reputation: 63

You can use PowerShell to launch batch files as well.

function Run-BatchFile
{
 param($computer = "mycomputer")
 $batfilename = "mybatch.bat"
 Invoke-Command -ComputerName $computer -ScriptBlock {param($batfilename) "powershell.exe -NoLogo -NoProfile -WindowStyle Hidden -ExecutionPolicy Bypass -File C:\Batchfiles\$batfilename" } -ArgumentList $batfilename -AsJob
}

Run-BatchFile

Keep in mind I haven't tested this exact code but the general idea should work.

Upvotes: 1

Sean
Sean

Reputation: 62472

Try using the ampersand operator to launch your script:

& "cmd.exe /c C:\Batchfiles\$batfilename"

Basically, because you've got the command in quotes Powershell will treat it as a string, not a command to execute. The ampersand forces Powershell to treat it as a command. See here for more information.

Upvotes: 0

Related Questions