# Retrieve items from an Array

**URL:** <https://forums.powershell.org/t/retrieve-items-from-an-array/18857>\
**Category:** PowerShell Help\
**Created:** [March 19, 2022, 3:50am UTC](https://forums.powershell.org/t/retrieve-items-from-an-array/18857 "2022-03-19T03:50:33Z")\
**Posts on this page:** 1\
**Showing post:** 2

<div class="post-metadata">

**Author:** ![Olaf](https://sea1.discourse-cdn.com/flex019/user_avatar/forums.powershell.org/olaf/32/992_2.png) [@Olaf](https://forums.powershell.org/u/Olaf)\
**Post date:** [March 19, 2022, 6:07am UTC](https://forums.powershell.org/t/retrieve-items-from-an-array/18857/2 "2022-03-19T06:07:50Z")

</div>

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

> [@Welcome to the new PowerShell Forums](https://forums.powershell.org/t/welcome-to-the-new-powershell-forums/7/6):
>
> How to format code in [PowerShell.org](http://PowerShell.org) forums. [Codeformatting\_1]

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`

```auto
$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.

```auto
$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:

```auto
[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:

```auto
$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.

---

_[View the full topic](https://forums.powershell.org/t/retrieve-items-from-an-array/18857)._
