1

I have a value that I want to find and pull out of a database. I have everything I need in order to run this script except how to store the result in a variable and then write those results to a txt file

$CNumber = Invoke-Sqlcmd -query ("Select Cust From SY.CompanyCode") -ServerInstance $SQLInstance -Database $Database

Add-Content $Mobile $CNumber

When it writes the results in the text file it looks like this:

System.Data.DataRow

When I just run the Invoke-Sqlcmd and don't try to store it in a variable I can see the correct value. So I'm assuming once this query runs, I need to convert the results somehow?

Please and thank you.

1
  • Please and thank you. ... Yes.
    – Clijsters
    Commented Oct 27, 2017 at 7:50

1 Answer 1

2

Because the result of the query is a System.Data.DataRow, PowerShell first needs to convert the DataRow to a String before it can be used with Add-Content and the easiest way to convert any object into a String is to use the ToString() method.

You can check this yourself by calling

$CNumber.ToString()

and it should show up in the console as:

System.Data.DataRow # OR System.Object[] if there are multiple DataRows

As you're only selecting one column you can simply access the property on the DataRow but keeping in mind that the query may return multiple DataRows we should loop through them, something like this:

foreach($row in $CNumber.Cust)
{
    # row will be equal to each cust from the query
    # add row to your file here
}
2
  • And see that's the weird part, I tested this exact method before I posted my question, and for some reason I still end up with System.Data.Datarow.
    – Ochuse
    Commented Oct 27, 2017 at 13:58
  • Found why this wasn't working, per .NET specifications .tostring will output the object type. In order to convert it I need to run the following: Add-Content $Mobile $CNumber.itemarray Thank you so much for your time. Cheers!
    – Ochuse
    Commented Oct 27, 2017 at 14:06

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.