3

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?

1 Answer 1

4

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
Sign up to request clarification or add additional context in comments.

3 Comments

You don't even need to make a param block, if you keep your original function and just space the arguments like in the bottom of my example it'll work.
Confirmed. It's always the basic things like this that get me in PowerShell.
You'd probably get a lot of benefit out of an intro to Powershell book, all you have here is a common practices issue. PowerShell.org has a lot of nice free ebooks for learning PS.

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.