我正在為用戶創建一個選單驅動的腳本,以根據他們選擇的選項執行某些操作。萬一他們選擇了錯誤的選項,我會在顯示適當的訊息后再次顯示選擇。但是,只要選擇了任何錯誤的選擇,并且從內部呼叫該函式,我就會得到一個 ParseException 。你能看看這里有什么問題嗎?
Class O_Manager {
[int]$val
ShowMenu() {
Write-Host " Please choose from below Options : "
Write-Host " "
Write-Host " 1. Option1 "
Write-Host " 2. Option2 "
Write-Host " 3. Option3 "
$this.val = Read-Host " Enter your Choice here "
switch($this.val)
{
1 {"ONE"}
2 {"TWO"}
3 {"THREE"}
default {"Incorrect choice selected"
ShowMenu()}
}
}
}
$obj = New-Object O_Manager
$obj.ShowMenu()
uj5u.com熱心網友回復:
PowerShell 將裸詞標記解釋ShowMenu為命令名稱(例如,cmdlet、函式、腳本或可執行檔案的名稱),但ShowMenu不是命令 - 它是附加到類實體的方法[O_Manager]。
要ShowMenu遞回呼叫,請通過$this變數參考當前實體:
default {
"Incorrect choice selected"
$this.ShowMenu()
}
ShowMenu我建議不要從自身內部遞回呼叫,而是重構你的類,使其具有一個公共入口點,該入口點ShowMenu連續重復呼叫而不是遞回呼叫——根據我的經驗,這通常會使代碼更容易推理和排除故障。
在下面的示例中,入口點被呼叫REPL(因為它實作了 Read-Eval-Print-loop),它只呼叫ShowMenu,Eval和Print函式,直到選單或 eval 函式告訴它停止:
enum Outcome
{
Continue
Quit
}
Class O_Manager {
[int]$val
[string]$result
REPL() {
while($this.ShowMenu() -eq 'Continue' -and $this.Eval() -eq 'Continue'){
$this.Print()
}
}
Print() {
Write-Host $this.result -ForegroundColor Cyan
}
[Outcome]
Eval() {
# do something with $this.result here
return [Outcome]::Continue
}
[Outcome]
ShowMenu() {
Write-Host " Please choose from below Options : "
Write-Host " "
Write-Host " 1. Option1 "
Write-Host " 2. Option2 "
Write-Host " 3. Option3 "
try {
$this.val = Read-Host " Enter your Choice here "
}
catch {
Write-Host "Error encountered: $_" -ForegroundColor Yellow
return [Outcome]::Quit
}
$this.result = switch ($this.val) {
1 { "ONE" }
2 { "TWO" }
3 { "THREE" }
default {
$this.result = "Incorrect choice selected"
return [Outcome]::Quit
}
}
return [Outcome]::Continue
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/414547.html
標籤:
上一篇:為什么“$(where.exegit|select-object-first1)”設定了$LastExitCode?
下一篇:清除函式中的文本框
