77

I'm trying to run a PowerShell script inside cmd command line. Someone gave me an example and it worked:

powershell.exe -noexit "& 'c:\Data\ScheduledScripts\ShutdownVM.ps1'"

But the problem is my PowerShell script has input parameters, so I tried, but it doesn't work:

powershell.exe -noexit "& 'D:\Work\SQLExecutor.ps1 -gettedServerName "MY-PC" ' "

The error is:

The term 'D:\Work\SQLExecutor.ps1 -gettedServerName "MY-PC" ' is not recognized as the name of a cmdlet, function,

How can I fix this problem?

Matt
  • 25,467
  • 18
  • 120
  • 187
XiaoYao
  • 3,177
  • 4
  • 22
  • 19
  • 4
    Are you sure you want to use -noexit ? This means when your script completes the shell will hang around, possibly blocking the execution of the batch file in CMD. – x0n May 08 '13 at 15:56

3 Answers3

110

You need to separate the arguments from the file path:

powershell.exe -noexit "& 'D:\Work\SQLExecutor.ps1 ' -gettedServerName 'MY-PC'"

Another option that may ease the syntax using the File parameter and positional parameters:

powershell.exe -noexit -file "D:\Work\SQLExecutor.ps1" "MY-PC"
Shay Levy
  • 121,444
  • 32
  • 184
  • 206
12

I'd like to add the following to Shay Levy's correct answer: You can make your life easier if you create a little batch script run.cmd to launch your powershell script:

run.cmd

@echo off & setlocal
set batchPath=%~dp0
powershell.exe -noexit -file "%batchPath%SQLExecutor.ps1" "MY-PC"

Put it in the same path as SQLExecutor.ps1 and from now on you can run it by simply double-clicking on run.cmd.


Note:

  • If you require command line arguments inside the run.cmd batch, simply pass them as %1 ... %9 (or use %* to pass all parameters) to the powershell script, i.e.
    powershell.exe -noexit -file "%batchPath%SQLExecutor.ps1" %*

  • The variable batchPath contains the executing path of the batch file itself (this is what the expression %~dp0 is used for). So you just put the powershell script in the same path as the calling batch file.

Matt
  • 25,467
  • 18
  • 120
  • 187
  • You can do the same with `@powershell.exe -noexit -file "%~dp0SQLExecutor.ps1" "MY-PC"`. – Nuno André Jul 10 '19 at 18:03
  • If you want to get rid of the varialble `batchPath`, yes of course you can do so. But due to `setlocal` the variable does not harm, since the variable's lifetime ends when the script exits. @NunoAndré – Matt Jul 11 '19 at 11:57
6

Try just:

powershell.exe -noexit D:\Work\SQLExecutor.ps1 -gettedServerName "MY-PC"
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
CB.
  • 58,865
  • 9
  • 159
  • 159