1

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.

1 Answer 1

1

You're using the wrong concatenation operator. By using a comma, you're passing an array rather than a string to Write-Host and therefore it adds the space between the elements.

Try instead:

if ($args[0]) {
  Write-Host "Hello,$($args[0])"
}

That should solve it.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks ! The first one works. The second one does not though. It prints Hello, + firstArgVal . the plus sign is also printed. I tried plus earlier. That did not work. I added commas instead (got idea from a sample online). That was wrong too.
Write-Host ("Hello, [{0}]" -f $args[0])
Write-Host ("Hello, [{0}]" -f $args[0]) looks cleaner. Thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.