简体   繁体   中英

Powershell not handling string parameters properly

I'm writing a simple powershell script, and I don't understand its behavior. Here is the code.

Function print($first,$second){
Write-Host "$first"
}

$one="Dog"
$two="Cat"

print($one,$two)

And here is the output.

Dog Cat

I don't know why its printing both parameters instead of just the one that I asked for. I found a similar question posted that says the answer to the solution is to write

print $one $two

But I don't know why. The other question is at How do I pass multiple string parameters to a PowerShell script?

Can anyone illuminate on this subject?

Like you mentioned, you have to call it as:

print $one $two

In Powershell, arguments to functions are delimited with space and not comma and are not enclosed in parentheses ( method arguments are, though)

The way you were calling, print($one,$two) , it is like calling print with one argument which is an array - ($one,$two) . So when you write-host $first , you are echoing the array and hence you see them both.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM