2008-08-22 179 views
29

我想做一些字符串連接/格式化,但它將所有參數放入第一個佔位符。如何將多個字符串參數傳遞給PowerShell腳本?

代碼

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 

輸出

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 

回答

38

失去括號和逗號。

調用你的函數爲:

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

給出:

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 
+1

這是,巧合的是,相當數量的編程語言如何工作(O'Caml,Haskell)。 – yfeldblum 2009-06-05 00:36:06

3

保羅的權利。
在PowerShell中,函數參數不包含在括號中。 (方法參數仍然存在。)
您最初的調用只是將一個大數組傳遞給該函數,而不是您想要的三個單獨參數。

4

順便說一句,使用PowerShell的here-string可能使你的函數一點更易於閱讀爲好,因爲你不會需要加倍所有" -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 
"@ 
} 
相關問題