5

I have a batch file test.bat to start a powershell script:

@pushd "C:\myscripts"
powershell .\test.ps1 arg1 "arg2 with space" arg3
@popd

The script test.ps1 (located at C:\myscripts) is a very simple one like:

# just print out the arguments
Write-Output ("args count: {0}" -f $args.length)
$args

Then I tried to start test.bat. I should get three arguments passed to ps1 but I got the following result:

args count: 5 arg1 arg2 with space arg3

What I expected in the script, args[0] should arg1 and args[1] should be "arg2 with space" and args3[2] be arg3. I cannot understand why the script actually gets 5 arguments.

How can I pass parameters from cmd or batch to powershell as what I expected? Like this:

args count: 3
arg1
arg2 with space
arg3

2 Answers 2

7
powershell .\test.ps1 arg1 'arg2 with space' arg3

or

powershell .\test.ps1 arg1 """arg2 with space""" arg3

I think you should try to avoid using double quotes as cmd already uses them too and therefore it's a little hard to predict what exactly PowerShell will get. Remember that this gets passed through two shells and therefore two layers of escaping/quoting.

PowerShell itself doesn't make much of a distinction between single and double quotes. At least in this context the difference is irrelevant.

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

Comments

0

OK. I think I got it:

@pushd "C:\myscripts"
powershell .\test.ps1 arg1 'arg2 with space' arg3
@popd

single quote char instead of double one. Maybe they mean different thing in PS.

1 Comment

They don't. But they do mean different things for cmd.

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.