假設我有四個不同部門的串列
- 音樂
- 科學
- 聚乙烯
- 數學
我可以設定它,以便當您選擇數字時,它將部門存盤為 $department
我想做一個Write-Host所有四個部門的串列,然后$department = Read-Host讓他們從 1-4 中選擇一個數字,它將變數設定為數學等。
任何幫助表示贊賞!
親切的問候
uj5u.com熱心網友回復:
使用列舉 - 讓你開始,沒有像上面那樣的錯誤處理
enum Department
{
Music = 1
Science = 2
PE = 3
Maths = 4
}
$Departments = [Department]
Write-Host "Please Select"
Write-Host "-------------"
forEach ($departmentName in $Departments.GetEnumNames())
{
Write-Host "$departmentName = $(($Departments::$departmentName).value__)"
}
$DepartmentNumber = Read-Host "Please Select a Department number"
$Department = [Department]$DepartmentNumber
Write-Host $Department
輸出:
Please Select
-------------
Music = 1
Science = 2
PE = 3
Maths = 4
Please Select a Department: 3
PE
關于列舉的進一步閱讀:https : //docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_enum? view = powershell- 7.1
uj5u.com熱心網友回復:
思考程序
這是一個非常教科書的問題。你想要有一個部門陣列,然后用一個與元素索引 1 對應的整數向用戶顯示該陣列。
然后,您從與部門對應的用戶接收整數輸入(進行一些錯誤檢查以確保他們輸入的整數實際上與部門對應),然后使用該整數從部門陣列中獲取適當的陣列元素。由于Read-Host默認情況下input from是一個字串,因此您需要在使用它之前將其轉換$UserInput為 an[int]來獲取陣列的索引。
同樣,由于我們使用陣列索引 1 向用戶列出值,因此在從陣列中檢索陣列元素時必須考慮到這一點,因此我們從用戶獲得的值中減去 1。
代碼
# Our array of departments
$Departments = @(
"Music",
"Science",
"PE",
"Maths"
)
# List each department for the user to pick from, being sure to off-set it's array index by 1
foreach($Department in $Departments){
Write-Host "$([array]::IndexOf($Departments, $Department) 1). $Department"
}
# Get the appropriate value that corresponds to a department from the user, retry if user entered invalid value
do {
$UserInput = Read-Host -Prompt "Enter the number corresponding to the desired department"
} while ($UserInput -le 0 -or $UserInput -gt $Departments.Length)
# Once we have a value from the user, use it to assign get the appropriate department, make sure to offset it by 1
$SelectedDepartment = $Departments[[int]$UserInput - 1]
Write-Host "User selected department: $SelectedDepartment"
示例執行和輸出
1. Music
2. Science
3. PE
4. Maths
Enter the number corresponding to the desired department: 0
Enter the number corresponding to the desired department: 5
Enter the number corresponding to the desired department: 4
User selected department: Maths
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/316428.html
標籤:电源外壳
上一篇:用于從CSV檔案修改XML的Powershell腳本
下一篇:更改多個目錄中.ini檔案的值
