I am using a batch file runpowershellscript.bat to invoke a powershell script sample.ps1. When I pass an argument to the batch file, the batch sends that argument to the powershell script. When I print the argument in sample.ps1, the argument has a space each around them. Why is that space getting added?
runpowershellscript.bat
@echo off
setlocal
SET SCRIPT=%1
SET PATH=%PATH%;C:\Windows\System32\WindowsPowershell\v1.0\
if "%2"=="" (
REM no arguments
powershell -executionpolicy bypass -File %1
goto :END
)
if not "%3"=="" (
REM 2 arguments
powershell -executionpolicy bypass -File %1 %2 %3
goto :END
)
if not "%2"=="" (
REM 1 argument
powershell -executionpolicy bypass -File %1 %2
goto :END
)
:END
endlocal
sample.ps1
Write-Host "number of arguments=" $args.Count
for($i = 0; $i -lt $args.Count; $i++) {
Write-Host "[",$args[$i],"]"
}
Write-Host ""
if ($args[0]) {
Write-Host "Hello,",$args[0]
}
else {
Write-Host "Hello,World"
}
version of powershell
PS C:\eclipse\batch> Get-Host
Name : ConsoleHost
Version : 2.0
InstanceId : 7b72da6c-5e6c-4c68-9280-39ae8320f57e
UI : System.Management.Automation.Internal.Host.InternalHostUserI
nterface
CurrentCulture : en-GB
CurrentUICulture : en-US
PrivateData : Microsoft.PowerShell.ConsoleHost+ConsoleColorProxy
IsRunspacePushed : False
Runspace : System.Management.Automation.Runspaces.LocalRunspace
Command line content below, when I run the batch
C:\batch>.\runpowershellscript.bat sample.ps1 firstarg
number of arguments= 1
[ firstarg ]
Hello, firstarg
Please note that there is no space between Hello, and $args[0] in the ps1 script. I was not expecting a space between Hello, and firstarg.
Thanks.