Pages

Tuesday, November 9, 2010

Powershell.exe - Passing Command Arguments with Spaces

This isn't the first time I've run into this problem but the first good solution I've found. When wanting to execute a PowerShell.exe a file the spaces in the file path it can be problematic. However the normal methods of passing arguments fail. I've tried ticks, double quotes, single quotes, backslashes however nothing work.

An example of what fails.
powershell.exe -Command "c:\path with space\script1.ps1 arg1"

However by using the "& - call operator" you can successfully.

This example works.
powershell.exe -Command "& 'c:\path with space\script1.ps1' arg1"

Note: When passing the command line argument "-WindowsStyle" to powershell.exe you have to place it before the "-Command" argument. If "-Command" comes first "-WindowStyle" doesn't work.

Here's an example
powershell.exe -WindowsStyle Hidden -Command "& 'c:\path with space\script1.ps1' arg1"

Side Note: After posting this my brother was like "Of course thats the way around it" and I've swear i asked him the last time it came up.

Links
http://www.leeholmes.com/blog/2006/05/05/running-powershell-scripts-from-cmd-exe/

6 comments:

  1. Thanks. This is the one I was looking for

    ReplyDelete
  2. Thanks for writing..I had got the same issue, and your fix resolved it. Thanks again!!

    ReplyDelete
  3. Finally...and now I can move on with my life... On a side note http://technet.microsoft.com/en-us/library/dd315276.aspx is also pretty useful.

    ReplyDelete
  4. Dude, you rock. I was not able to find this information anywhere else. Thanks a bunch!

    ReplyDelete
  5. I have got space characters not in file path but in Azure Subscription name (Windows Azure MSDN Subscription), my command is like this:

    C:\file.ps1 -subscriptionName "Windows Azure MSDN Subscription"
    This does not fail but does not shows the correct subscriptioname when I do an Write-Output

    Using your method:

    C:\file.ps1 -subscriptionName "& 'Windows Azure MSDN Subscription'"

    This fails with message - 'Ampersand not allowed. The & operator is reserved for future use; use "&" to pass ampersand as a string.'

    Can you please help me find a solution to this.

    ReplyDelete
    Replies
    1. Try...
      C:\file.ps1 -subscriptionName 'Windows Azure MSDN Subscription'

      Worked for me.

      Also,
      powershell.exe -Command "& 'c:\path with space\script1.ps1' arg1"
      didn't work for me but
      powershell.exe -Command 'c:\path with space\script1.ps1 arg1 '
      did

      Delete

Please leave a comment; someone, anyone!