views:

8382

answers:

4

Is there documentation or an article on the rules for passing strings into PowerShell functions? I just trying to do some string concatenation/formatting, but it's putting all the parameters into the first placeholder.

Code

function CreateAppPoolScript([string]$AppPoolName, [string]$AppPoolUser, [string]$AppPoolPass)
{
    # Command to create an IIS application pool
    $AppPoolScript = "cscript adsutil.vbs CREATE ""w3svc/AppPools/$AppPoolName"" IIsApplicationPool`n"
    $AppPoolScript += "cscript adsutil.vbs SET ""w3svc/AppPools/$AppPoolName/WamUserName"" ""$AppPoolUser""`n"
    $AppPoolScript += "cscript adsutil.vbs SET ""w3svc/AppPools/$AppPoolName/WamUserPass"" ""$AppPoolPass""`n"
    $AppPoolScript += "cscript adsutil.vbs SET ""w3svc/AppPools/$AppPoolName/AppPoolIdentityType"" 3"

    return $AppPoolScript
}
$s = CreateAppPoolScript("name", "user", "pass")
write-host $s

Output

cscript adsutil.vbs CREATE "w3svc/AppPools/name user pass" IIsApplicationPool
cscript adsutil.vbs SET "w3svc/AppPools/name user pass/WamUserName" ""
cscript adsutil.vbs SET "w3svc/AppPools/name user pass/WamUserPass" ""
cscript adsutil.vbs SET "w3svc/AppPools/name user pass/AppPoolIdentityType" 3
+10  A: 

Lose the parentheses and commas.

Calling your function as:

$s = CreateAppPoolScript "name" "user" "pass"

gives:

cscript adsutil.vbs CREATE "w3svc/AppPools/name" IIsApplicationPool
cscript adsutil.vbs SET "w3svc/AppPools/name/WamUserName" "user"
cscript adsutil.vbs SET "w3svc/AppPools/name/WamUserPass" "pass"
cscript adsutil.vbs SET "w3svc/AppPools/name/AppPoolIdentityType" 3
Paul Roub
This is, coincidentally, how a fair number of programming languages work (O'Caml, Haskell).
Justice
+2  A: 

Paul's right.
In PowerShell, function parameters are not enclosed in parenthesis. (Method parameters still are.)
Your initial call was just passing one big array to the function, rather than the three separate parameters you wanted.

Steven Murawski
+3  A: 

By the way, using a PowerShell here-string might make your function a little easier to read as well, since you won't need to double up all the "-marks:

function CreateAppPoolScript([string]$AppPoolName, [string]$AppPoolUser, [string]$AppPoolPass)
{
  # Command to create an IIS application pool
  return @"
cscript adsutil.vbs CREATE "w3svc/AppPools/$AppPoolName" IIsApplicationPool
cscript adsutil.vbs SET "w3svc/AppPools/$AppPoolName/WamUserName" "$AppPoolUser"
cscript adsutil.vbs SET "w3svc/AppPools/$AppPoolName/WamUserPass" "$AppPoolPass"
cscript adsutil.vbs SET "w3svc/AppPools/$AppPoolName/AppPoolIdentityType" 3
"@
}
Emperor XLII
A: 

Nice .. thanks

good feedback; use comments rather than answers :)
John Weldon