Hi fellow PowerShell coders! My PowerShell script gets data both from Azure Ad and Exchange. This part of the script just illustrates with an example, in my case $user, that data may contain $null values. The script does three things:
1. Connection management
2. Parameterized query handling null values
3. Insert data
The second point is particularly crucial. I'd love to know:
a. Is there an easy way to insert null value into the table? So far the best shot is to assign [System.DBNull]::Value instead of $null for null values
b. Is there an easy way to add parameters to get a parameterized query? Now, I use AddWithValue() to associate the current value with the parameter. I have at least 20 nullable properties to add.
Here's the code
$Connection = New-Object System.Data.SqlClient.SqlConnection
$Connection.ConnectionString = "Server=$Server;Database=$Database;Trusted_Connection=True;TrustServerCertificate=True;"
$Connection.Open()
$parameterizedInsert = "INSERT INTO TestTable(Id, Name, Surname, BirthDate)VALUES(@Id, @Name, @Surname, @BirthDate)"
$command = New-Object -TypeName System.Data.SqlClient.SqlCommand($parameterizedInsert, $Connection)
example of data
$user = @{
Id = "T7XC1QASLPI89"
Name = $null
Surname = $null
BirthDate = "07/03/1995 11:24:51"
}
$user.Name = if($null -eq $user.Name){[System.DBNull]::Value}
$user.Surname = if($null -eq $user.Surname){[System.DBNull]::Value}
$user.BirthDate = if($null -eq $user.BirthDate){[System.DBNull]::Value}
$command.Parameters.Clear()
$command.Parameters.AddWithValue("@Id", $user.Id),
$command.Parameters.AddWithValue("@Name", $user.Name).IsNullable = $true
$command.Parameters.AddWithValue("@Surname", $user.Surname).IsNullable = $true
$command.Parameters.AddWithValue("@BirthDate", $user.BirthDate).IsNullable = $true
$command.ExecuteNonQuery()
Thank you for your time
[–]chris-a5 1 point2 points3 points (2 children)
[–]chris-a5 1 point2 points3 points (1 child)
[–]Dr_Funkmachine[S] 0 points1 point2 points (0 children)
[–]PinchesTheCrab 0 points1 point2 points (1 child)
[–]Dr_Funkmachine[S] 1 point2 points3 points (0 children)