[英]Functions in Powershell - can they be called within a string?
我很喜歡函數如何能夠大大減少Powershell腳本中的繁忙工作,並且它們為我節省了大量的冗余編碼。 但我現在遇到在Powershell字符串中調用聲明函數的問題(作為使用'+'符號的連接字符串的一部分)並且想知道是否有這樣做的技巧。 一些示例代碼:
#this function takes input and either returns the input as the value, or returns
placeholder text as the value
function val ($valinput)
{ if ($valinput)
{return $valinput}
else
{$valinput = "No Results!"; return $valinput}
}
如果我在行的開頭或單獨調用該函數:
val("yo!")
它運行正常。 但是,如果我嘗試將其連接為字符串的一部分,例如:
"The results of the tests are: " + val($results)
Powershell似乎在執行函數時遇到問題,我得到'你必須在'+'運算符的右側提供一個值表達式。 和表達式或語句中的'意外的標記'val'。 錯誤。
有沒有辦法在連接字符串中正確調用函數? 我知道我可以將函數的結果推送到另一個變量並將結果變量連接為字符串的一部分,但每次調用此函數時都會很麻煩。 提前致謝...!
將命令/函數調用包裝在可擴展字符串內的子表達式中:
"The results of the test are: $(val "yo!")"
另外值得指出的是,PowerShell中的命令調用語法不需要括號。 我會勸阻使用括號,就像你在示例中一樣,因為你最終會將連續的參數視為一個:
function val ($inputOne,$inputTwo)
{
"One: $inputOne"
"Two: $inputTwo"
}
現在,使用類似C#的語法,您可以:
val("first","second")
但發現輸出變為:
One: first second
Two:
因為PowerShell解析器會看到嵌套表達式("first","second")
並將其視為單個參數。
位置參數參數的正確語法是:
val "first" "second"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.