Monday, 30 September 2013

Powershell format operator inside function

Powershell format operator inside function

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.

No comments:

Post a Comment