0

I've found out the format operator is working differently inside a function compared to a plain script. Here's a simple example of what is working as expected:

[string]$name = 'Scripting Guy'
[string]$statement = 'PowerShell rocks'
$s = "The {0} thinks that {1}!" -f $name, $statement
write-host $s

producing:

The Scripting Guy thinks that PowerShell rocks!

While inside a function it does something different:

function myFunc( [string] $iname, [string] $istatement) { 
    $s = "The {0} thinks that {1}!" -f $iname, $istatement
    write-host $s
}

[string]$name = 'Scripting Guy'
[string]$statement = 'PowerShell rocks'
myFunc($name, $statement)

produces:

The Scripting Guy PowerShell rocks thinks that !

I tried to play with it to find out what it's doing:

function myFunc( [string] $iname, [string] $istatement) { 
    $s = "The {0} thinks that {1}! {2} {3}" -f $iname, $istatement, "=====", $iname
    write-host $s
}

[string]$name = 'Scripting Guy'
[string]$statement = 'PowerShell rocks'
myFunc($name, $statement)

This produces:

The Scripting Guy PowerShell rocks thinks that ! ===== Scripting Guy PowerShell rocks

So now I don't know what to think about this.

0

1 Answer 1

3

You should call the function as follows:

myFunc -iname "Scripting Guy" -istatement "Powershell Rocks!!"

or

myFunc $name $statement

The current method you're using passes a single array object that's why the elements get printed in succession

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

Comments

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.