Executing a PowerShell script from outside PowerShell (for example via a Windows shortcut) can be a little complicated, especially if the path to the script contains spaces and it has parameters, so here’s how to do it:
powershell.exe -command "& 'C:\A path with spaces\login.ps1' -password XXX"
Note that I’m using the PowerShell & operator to execute the script. This is because I have to surround the path with quotes so that it’s interpreted by PowerShell as a single literal even though it contains spaces. If I would leave out the “&” then the quoted string would simply be interpreted as a string literal to output, so the script would not be executed.
The parameters to the script should not be included within the single quotes since they are not part of the first literal, which should only contain the path to the script to execute.
/Emil
i have tried this
powershell.exe -command “& ‘C:\test\script.ps1′”
and it doesn’t worked do you have any idea
i am using win 7 with powershell
Major Minor Build Revision
—– —– —– ——–
2 0 -1 -1
thank you
@ygarti
Hi!
It looks like your last single quote is ′, and not ‘, which would have been correct. It could be that WordPress mangled your quotes when you posted your comment so if that’s not the error we have too look further…
Your script path does not contain any white space so you can remove the single quotes completely, maybe that helps?
If it doesn’t I don’t know what the error may be (your example works for me). What error do you get?
/Emil
I’d like to offer my thanks. I had been naming my powershell scripts without spaces, so my script filenames tended_to_look_like_this. It worked, but readability suffered.
Thanks to this tip, I’ve been able to start giving my scripts names with spaces.
One note: The shortcut path now looks like this:
C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -command “& ‘C:\Users\sjk-admin\Desktop\SJK_PS_Scripts\scripts\script with spaces.ps1′”
Thanks for the info. I was having a terrible time getting a shortcut to work.
I got it working just like you said. The quote replacement comment is valid for cases such as copying and pasting from a web page. It happened to me once; got two different kinds of double-quotes and that caused an error.