Reputation: 91600
I have the following function (I just paste it into the command line):
function Test ($url, $interface, $method)
{
Write-Host "http://$url/$interface/$method"
}
I then call it:
Test("localhost:90", "IService", "TestMethod")
I get:
http://localhost:90 IService TestMethod//
I expect to get:
http://localhost:90/IService/TestMethod
The same thing happens if I first set the result to a variable:
$res = "http://$url/$interface/$method"
Write-Host $res
I also don't think it's due to Write-Host
, since I get the same error if I pass this string into .NET objects.
It completely confuses me that this works if I just define each variable. So, it's something to do with the fact that these are function parameters. I can do this from the command line:
PS C:\> $url = "localhost:90"
PS C:\> $interface = "IService"
PS C:\> $method = "TestMethod"
PS C:\> Write-Host "http://$url/$interface/$method"
http://localhost:90/IService/TestMethod
PS C:\>
Am I doing something silly, or is there another way to do string interpolation in PowerShell?
Upvotes: 3
Views: 3226
Reputation: 1095
You aren't doing anything silly, but you are conflating PowerShell with something like Python.
When I do:
Function Count-Args
{
$args.count
}
Count-args($var1, $var2, $var3)
I get a count of 1, and all three variables you put into ()
are cast as a single array to $args
.
Just change the way you call the function to the test mysite myinterface mymethod
. Note the ss64 site advice.
Don't add brackets around the function parameters:
$result = Add-Numbers (5, 10) --Wrong!
$result = Add-Numbers 5 10 --Right
Upvotes: 4