- 要求用戶輸入名稱,在名稱陣列 person.dat 檔案中搜索名稱。如果找到該名稱,則列印一個表,如果未找到該名稱,則列印一條錯誤訊息并詢問用戶另一個名稱。
persons.dat.
George Nelson,56,78000.00
Mary Nathaniel,65,66300.00
Rosy Ferreira,32,39000.00
猜測這部分。
While ($true){
Write-Host $("1. Search by user name")
Write-Host $("2. List all:)
$input = (Read-Host("Enter an option (0 to quit)"))##user will input value
#if 1 is entered (Read-Host("Enter user name"))
#if 2 is entered Print all#
#if 0 is entered quit.#
try{ ? }
catch {
## If input is invalid, restart loop
Write-host " User does not exist"
continue
}
0{
Write-Host $("Thank you. Bye!")
此底部將在表格中列印所有 3 個。
$data = Get-Content "persons.dat"
$line = $null;
[String[]] $name = @();
[int16[]] $age = @();
[float[]] $salary = @();
foreach ($line in $data)
{ #Split fields into values
$line = $line -split (",")
$name = $line[0];
$age = $line[1];
$salary = $line[2];
}
Write-Host $("{0,-20} {1,7} {2,11}" -f "Name", "Age", "Salary")
Write-Host $("{0,-20} {1,7} {2,11}" -f "-----------", "---", "-----------")
for
($nextItem=0 ; $nextItem -lt $name.length; $nextItem )
{
$val1n = $name[$nextItem];
$val2n = $age[$nextItem]
$val3n = $salary[$nextItem]
Write-Host $("{0,-20} {1,7} {2,11:n2}" -f $val1n,
$val2n, $val3n)
}
uj5u.com熱心網友回復:
這是您可以做到的一種方法,希望行內注釋可以幫助您理解邏輯。由于persons.dat您向我們展示的檔案是逗號分隔的,因此我們可以使用 將其轉換為物件ConvertFrom-Csv,通過這樣做,您無需像使用這些Write-Host陳述句那樣構建輸出到螢屏。
# Convert the file into an object
$persons = Get-Content persons.dat -Raw | ConvertFrom-Csv -Header "Name", "Age", "Salary"
function ShowMenu {
# simple function to clear screen and show menu when called
Clear-Host
'1. Search by user name'
'2. List all'
}
:outer while($true) {
# clear screen and show menu
ShowMenu
while($true) {
# ask user input
$choice = Read-Host 'Enter an option (0 to quit)'
# if input is 0, break the outer loop
if(0 -eq $choice) {
'Goodbye'
break outer
}
# if input is not 1 or 2
if($choice -notmatch '^(1|2)$') {
'Invalid input!'
$null = $host.UI.RawUI.ReadKey()
# restart the inner loop
continue
}
# if we are here user input was correct
break
}
$show = switch($choice) {
1 {
# if choice was 1, ask user for a user name
$user = Read-Host "Enter user name"
# if user name exists in the `$persons` object
if($match = $persons.where{ $_.Name -eq $user }) {
# output this to `$show`
$match
# and exit this switch
continue
}
# if user name was not found
"$user was not found in list."
}
2 {
# if input was 2, output `$persons` to `$show`
$persons
}
}
# show the object to the host
$show | Out-Host
# and wait for the user to press any key
$null = $host.UI.RawUI.ReadKey()
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/446337.html
上一篇:如果值在物件陣列中包含字串 數字
