0

I am calling a PS function while passing it a string and a datatable variable. I want to extract all items in the datatable and store them in an object.

Here is my code from my script:

Function myFunc
{
    param ($id, $dt)
    $data = $dt | where-object ($_.ID -eq $ID)
}

$myVar = myFunc -id "stringID" -dt myDataTable

When this runs my data variable stays empty.

I have a breakpoint placed at the end of my project so I can try and play with the values. When I try and re-create the issue it works:

[DBG]: PS C:\WINDOWS\system32>> $abc = $myDataTable | where-object {$_.ID -eq $ID}

[DBG]: PS C:\WINDOWS\system32>> $abc


ID          : //info here
Location    : //info here
Managedr    : //info here

It just will not work in my actual script.

2
  • 2
    For one thing your function doesn't return anything, because you capture all output in the variable $data. Also, is the lack of $ in -dt myDataTable a typo in your question or in your actual script? And why do you have that parameter in the first place, if you're not using it? Commented Jan 16, 2015 at 23:52
  • Sorry for the late response. Yes there was a typo in my original question. My function should read $data = $dt | where-object ($_.ID -eq $ID) Commented Jan 19, 2015 at 12:07

1 Answer 1

4

The function runs in it's own scope, and the scope and all variables created in the scope are disposed when the function exits. Functions should return data, which you assign to variables in the local scope, like this:

Function myFunc
{
    param ($id, $dt)
    $myDataTable | where-object ($_.ID -eq $ID)
}

$myVar = myFunc -id "stringID" -dt myDataTable
Sign up to request clarification or add additional context in comments.

1 Comment

Johnrad just be aware that I think you need to change the line to $dt | where-object ($_.ID -eq $ID) since there is no variable called $myDataTable in the scope of the function

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.