sevi
sevi

Reputation: 480

Pass an array item to a function in PowerShell

I've already read many articles about PowerShell functions and passing parameters to them but I haven't found a solution on how to pass a specific array item to a function and not the full array.
This is how my code looks:

$log = "C:\Temp\test.txt"
$test = "asdf"
$arrtest = @("one", "two", "three")

Function Write-Log($message)
{
    Write-Host $message
    $message | Out-File $log -Append
}

Now I want to pass single items of the array to the Write-Log function like this:

Write-Log "first arr item: $arrtest[0]"
Write-Log "second arr item: $arrtest[1]"
Write-Log "third arr item: $arrtest[2]"

But in the commandline I'll always get the full array plus [number] as a string:

first arr item: one two three[0]
second arr item: one two three[1]
third arr item: one two three[2]

I think the problem is my syntax, can someone please point me in the right direction?

Thanks a lot!!

Upvotes: 2

Views: 873

Answers (1)

AdamL
AdamL

Reputation: 13141

This will do the trick:

Write-Log "first arr item: $($arrtest[0])"

In your attempt, your passing entire array, because PowerShell interprets $arrtest as variable, and [0] as string.

Upvotes: 3

Related Questions