Reputation: 282
I've been trying to launch a simple powershell script from a batch file. After looking online the advice is to set the policy using Set-ExecutionPolicy.
I've done this and using Get-ExecutionPolicy the policy has been changed.
However running this batch file results in an 'Open With' dialog rather than the execution of the script.
Batch:
%SystemRoot%\system32\WindowsPowerShell\v1.0\powershell.exe ^&'./script.psl'
Powershell:
Write-Host "This is a message"
I have sampled on both Windows 7 and Server 2008 R2. Both have same result. What am I missing?
Upvotes: 3
Views: 14638
Reputation: 440
There is another way you can get this error, associated with spaces in file paths which is still common in windows even to this very day.
Let's say you had access to the common knowledge that in powershell, you need to escape spaces in filenames with a backtick, `, also known as a grave operator.
You could then use it like this in a batch script to run a powershell script, both of which are in the same sub-directory of a directory path that has spaces in it:
@REM get directory of the batch file script to use for powershell script
set cwd=%~dp0
@REM escape the spaces for powershell
set cwd=%cwd: =` %
echo %cwd%
@REM list the powershell script with a powershell command
powershell.exe -c Get-ChildItem "%cwd%install.ps1"
@REM run the powershell script
powershell.exe -File "%cwd%install.ps1"
Get-ChildItem will work, but powershell will not find the script as an argument of -File. In fact, as it turns out, escaping the spaces is NOT needed for the -File argument, even as it is needed for Get-ChildItem. So this will work:
set cwd=%~dp0
set cwd1=%cwd: =` %
echo %cwd%
echo %cwd1%
powershell.exe -c Get-ChildItem "%cwd1%install.ps1"
powershell.exe -File "%cwd%install.ps1"
And yes I found this out because I'm running powershell script in batch script for same reason as OP. 13 years later.
Upvotes: 0
Reputation: 2021
To run a script file from the *.cmd file , use the -file parameter of powershell.exe and double quotes:
%SystemRoot%\system32\WindowsPowerShell\v1.0\powershell.exe -file "./script.ps1"
When you will use only one quote in batch file you can expect powershell error like:
Processing -File ''./build.ps1'' failed because the file does not have a '.ps1' extension. Specify a valid Windows PowerShell script file name, and then try again.
Upvotes: 0
Reputation: 68341
To run a script file from the command line, use the -file parameter of powershell.exe.
%SystemRoot%\system32\WindowsPowerShell\v1.0\powershell.exe -file './script.psl'
Upvotes: 1