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)
}
просто к вашему сведению ... переменная $Input
является зарезервированной переменной. PoSh будет делать это, когда захочет. так что вы ДЕЙСТВИТЕЛЬНО не должны использовать это для переменной. [ухмылка]
Спасибо, Ли. Я изучаю сценарии в классе и все еще учусь... Я изменю это на $value. Авраам, я не могу понять, как напечатать определенную строку из файла dat. Сценарий должен искать имя, введенное пользователем, и печатать имя, возраст и зарплату из файла dat. Любая обратная связь очень ценится.
Вот один из способов сделать это, надеюсь, встроенные комментарии помогут вам понять логику. Поскольку файл 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()
}
Итак, какой у вас здесь вопрос?