2

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!!

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot for the fast solution!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.