J,
Welcome to the forum.
There are a few issues with your code. First of all - when you post code, sample data, console output or error messages please format it as code using the preformatted text button ( </> ). Simply place your cursor on an empty line, click the button and paste your code.
Thanks in advance
In PowerShell (and in most other scripting or programming languages) the index of an array starts with 0
. So With the following line of code you explicitly select the first element of the array with the name $age
. And that’s always 45
$val = $age[0] ## This part I know is wrong…not sure how to make it work.
The next line of code is useless because you never use the variable you define.
$ndx = [array]::IndexOf($name, $age);
Regardless of that are your arrays actually completely unrelated to each other.
If I had to assume what you wanted to achieve I’d correct your code to this:
[String[]] $name = 'John Morales', 'Joe Root', 'Peter Barkley'
[int16[]] $age = 45, 67, 31
$user = Read-Host -Prompt 'Please enter your name'
$ndx = $name.IndexOf($user)
$val = $age[$ndx]
if ($user -in $name) {
'{0,-15} {1,0}' -f 'Name', 'Age'
'{0,-15} {1,0}' -f '------', '---'
'{0,-15} {1,0}' -f $user, $val
}
else {
'User not found'
}
But that’s actually not how we write PowerShell code. To provide your input where the names are actually related to their ages you use in the simplest case CSV data.
Something like this would work:
$CSVInput =
@'
Name,Age
"John Morales",45
"Joe Root",67
"Peter Barkley",31
'@ |
ConvertFrom-Csv
$UserName = Read-Host -Prompt 'Please enter your name'
$Result=
$CSVInput |
Where-Object -Property Name -EQ -Value $UserName
if ($Result) {
$Result
}
else{
'User not found'
}
Instead of providing the input data along with your code you would normaly use a CSV file and the cmdlet Import-Csv
to get the data.