PowerShell Cookbook

Twitter Updates

    follow me on Twitter

    Search

    Categories

     

    On this page

    Running PowerShell Scripts from Cmd.exe

    Archive

    Blogroll

    Disclaimer
    I work for Microsoft.

    The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.

    RSS 2.0 | Atom 1.0 | CDF

    Send mail to the author(s) E-mail

    Total Posts: 252
    This Year: 3
    This Month: 0
    This Week: 0
    Comments: 736

    Sign In

     Friday, May 05, 2006
    Friday, May 05, 2006 6:34:01 PM (Pacific Daylight Time, UTC-07:00) ( )

    One of the things that people often struggle with when they try to use PowerShell scripts as targets of Scheduled Tasks, or launch PowerShell scripts from cmd.exe is the following error message:

    C:\Program Files\Windows PowerShell\v1.0>powershell.exe "c:\temp\has space\test.ps1"
    'c:\temp\has' is not recognized as a cmdlet, function, operable program, or script file.
    At line:1 char:12
    + c:\temp\has  <<<< space\test.ps1

    (By the way, you can speed this up by using the -noprofile parameter to powershell.exe)

    This is because Powershell doesn’t natively support a parameter for a script to run.  The default command-line argument is “-command,” which defines the command as though you had typed it at the prompt.

    For example:

    C:\temp\monad>powershell "2+2"
    4

    This happens to work on script names with no spaces or quotes, as our interpreter interprets that as a command execution.  For scripts with spaces and quotes, you are doing the equivalent of:

    [C:\temp]
    PS:13 > c:\temp\has space\test.ps1
    'c:\temp\has' is not recognized as a cmdlet, function, operable program, or script file.
    At line:1 char:12
    + c:\temp\has  <<<< space\test.ps1
     

    [C:\temp]
    PS:14 > "c:\temp\has space\test.ps1"
    c:\temp\has space\test.ps1

    Suggestion: Did you mean to run the command in quotes?  If so, try using & "<command>"

    So, the solution is:

    [C:\temp]
    PS:15 > & 'C:\temp\has space\test.ps1'
    Hello World

    Or,

    C:\temp\monad>powershell "& 'c:\temp\has space\test.ps1'"
    Hello World

    This is something that we know to be a usability issue.  We’re tracking it internally, but a bug (and votes) on Ms Connect would help us prioritize this properly.