1

I wrote a PowerShell script which accepts a string array parameter. It is defined in the param section of the script like this:

param
(
    [Parameter(Position=0)]
    [string[]]$TemplateNames,
    ...
)

When calling the script via a PowerShell command-line, I can easily pass multiple strings to this parameter by using the following syntax:

.\Script.ps1 -TemplateNames @("Name1","Name2")

However, I need to call this script in a scheduled task and no matter what syntax I use, I can't get PowerShell to interpret the array correctly. The @(...) syntax doesn't work, passing the strings separated with a comma also doesn't work, putting the array in brackets also doesn't work and no matter how I escape the parameter or even the entire script call in single quotes, double quotes or even multiple single or double quotes, it just won't work. The same problem occurs also when calling the script manually via the Windows command line like this:

Powershell.exe -NoProfile -NoLogo -NonInteractive -ExecutionPolicy Bypass -File "C:\Script\Script.ps1" -TemplateNames ...

How can I pass an array to a PowerShell script in a scheduled task or when calling it via the Windows command line?

0

1 Answer 1

1

When using -command the problem of the misinterpretation can be circumvented:

powershell -command "& .\script.ps1 'Name1','Name2'"

This works because the string beetween the quotes is not (mis)interpreted. When using double quotes you have to use three of them:

powershell -command "& .\script.ps1 """Name1""","""Name2""""

The logic of removed quotes is strange. A test with a program that simply echos the parameters shows that a variant with two quotes yields the same result as the one with three.

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

3 Comments

Thanks a lot, this actually works just fine! Just one problem: Whenever I run the script like this (with single quotes) twice in cmd, the cmd window just closes when running it for the second time. Do you know why that is or how I can prevent that from happening?
Hm, I am not able to reproduce this behavior. I tried it with a script consisting of "write-output @args". You may try to reduce your script to only those lines producing the behavior and post it.
I found out that this behavior was actually caused by my antivirus software.

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.