I am trying to work with DataTables in powershell, more specifically I am trying to check to see if a row with a certain value exists in the datatable.
Here is the method I am using to create the dataTable.
function GetPropertyIDs()
{
write-host "Retrieving all Property ID's from $DatabaseInstance.$DatabaseName..." -NoNewline
$cn = new-object system.data.SqlClient.SqlConnection("Data Source=$DatabaseInstance;Integrated Security=SSPI;Initial Catalog=$DatabaseName");
$cn.Open()
$cmd = new-Object System.Data.SqlClient.SqlCommand("Select Distinct CAST(ID as varchar(5)) as ID, Name, Code from TableName Order by ID", $cn)
$cmd.CommandType = [System.Data.CommandType]'Text'
$adapter = New-Object System.Data.SqlClient.SqlDataAdapter $cmd
$dataTable = New-Object System.Data.DataTable
$adapter.Fill($dataTable) | out-null
$cn.Close() | out-Null
$cn.Dispose()
$count = $dataTable.rows.count;
write-host "$count records retrieved."
#Set Primary Key
$pk = $dataTable.Columns["ID"]
$dataTable.PrimaryKey = $pk
return $dataTable
}
Here is the code where I am trying to check if a specific value exists in the datatable...
$PropertyIDs = GetPropertyIDs
foreach($PropertySite in $PropertySites)
{
$id = ([System.String] $PropertySite).Replace("$SiteCollectionURL/property/", "")
$found = $PropertyIDs.DefaultView.Find($id)
}
Currently I am getting an error:
"You cannot call a method on a null-valued expression."
I have also tried this with no luck either:
$found = $PropertyIDs.Rows.Contains($id)
$PropertyIDs = GetPropertyIDs; $PropertyIDs -eq $null. Is the result true or false? If false, run this:$PropertySites | % { $_ -eq $null }. Does it return True? The error is saying that you calling the method on a null-object.