0

I have the following PowerShell code:

Add-Type -AssemblyName System.Data

function SQLBuild       
    {

        [DataTable] $dt = (New-Object -TypeName System.Data.DataTable)
        $dt = fillDataTable
        $dt.rows.count
        foreach ($dr in $dt.rows)
                    {
                     Write-Host "$($dr[0])"
                    }
}

I am getting the following errors:

Cannot index into a null array.
Untitled2.ps1:19 char:43
+                             Write-Host "$($dr[0])"
+                                           ~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : NullArray


Cannot index into a null array.
At Untitled2.ps1:19 char:43
+                             Write-Host "$($dr[0])"
+                                           ~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : NullArray

Can you please help me to understand why.

1
  • 1
    try to be more specific on what you want to achieve. Commented Sep 8, 2017 at 13:22

1 Answer 1

1

The error likely occurs because $dr is sometimes empty (or $null to be more specific).

You are asking PowerShell to return the 0th element of $DR, and in doing so you are assuming that it is always an array (or some other data type that can be accessed via an Array index). The error tells you that on two of the iterations it does not have a 0th array element because it is null.

One way to work around this would be to check if it's an array first. You can do this with -is:

foreach ($dr in $dt.rows)
{
    if ($dr -is [array]){ Write-Host $dr[0] }
}
Sign up to request clarification or add additional context in comments.

2 Comments

Error is resolved, but no values for column index 0 is not displaying which is needed here. Data exists in the column
Verify that $dt contains content before your loop. I can't help you further as I don't have your data or the fillDataTable function you're seemingly using.

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.