Run Powershell with parameters from batch file
Matthew Barrera
I have this PowerShell command that I run from directly from the PowerShell terminal on my Windows 10 system and it works great.
PowerShell
Get-AppxPackage | % { Add-AppxPackage -DisableDevelopmentMode -Register "$($_.InstallLocation)\AppxManifest.xml" -verbose }I'm trying to create a batch file to automate this PowerShell and I'm having trouble. I tried a bunch of different things but I'm way off in my testing.
I'm wondering if someone has some advice or examples of running PowerShell commands with batch files and using parameters.
43 Answers
Batch script that accepts arguments
Here's a batch script with arguments that are set as variables, and those variables passed to a PowerShell script and executed. You can execute a PowerShell script with batch this way.
Batch Script Example
Scale the batch arguments up with subsequent SET arg#=%~#
@ECHO ON
SET arg1=%~1
SET arg2=%~2
SET arg3=%~3
SET arg4=%~4
SET PSScript=C:\Users\User\Desktop\Test.ps1
SET PowerShellDir=C:\Windows\System32\WindowsPowerShell\v1.0
CD /D "%PowerShellDir%"
Powershell -ExecutionPolicy Bypass -Command "& '%PSScript%' '%arg1%' '%arg2%' '%arg3%' '%arg4%'"
EXIT /BPowershell script that accepts arguments
Scale the PowerShell arguments up with subsequent $arg#=$args[#]
Example PowerShell Script
$arg1=$args[0]
$arg2=$args[1]
$arg3=$args[2]
$arg4=$args[3]
Write-Host "$arg1 is a beauty!!"
Write-Host "$arg2 is cool!!"
Write-Host "$arg3 has body odor!!"
Write-Host "$arg4 is a beast!!"Tying it together
Pass arguments to the batch script:
c:\users\user\desktop\test.cmd "Princess" "Joe" "Akbar" "WeiWei"Pass arguments to the PowerShell script:
Powershell -ExecutionPolicy Bypass -Command "& 'C:\Script\Path\psscript.ps1' 'Princess' 'Joe' 'Akbar' 'WeiWei'
Supporting Resources
Command Line arguments (Parameters)
%* in a batch script refers to all the arguments (e.g. %1 %2 %3 %4 %5 ...%255) only arguments %1 to %9 can be referenced by number.
The call operator (&) allows you to execute a command, script or function.
I solved creating a script , .ps1 file , in Powershell ISE and after this I went to Powershell window and type this command to allow script to run : Set-ExecutionPolicy RemoteSigned and create a .bat file with this line : Powershell.exe -executionpolicy remotesigned -File "ps1_file_path\ps1_file_name.ps1" and all works fine.
You can run PowerShell commands from cmd/bat files by passing the commands as an argument to the powershell command. Make you batch file look like this. Note, I have not checked this in relation to the quotations—specifically how the single quote plays with the internal variables and double quotes.
powershell -command “Get-AppxPackage | ForEach-Object { Add-AppxPackage -DisableDevelopmentMode -Register “”$($_.InstallLocation)\AppxManifest.xml”” -verbose }” 5