SCCM – PowerShell – SQL Query

email me

This is a SQL query written in PowerShell. It connects to the SCCM DB and returns Custom_Data for C and D drives.

#import-module sqlps
#Install-Module -Name SqlServer -AllowClobber
#Update-Module -Name SqlServer

Clear-Host

[string] $Server= "SCCM_Server\SQL_Instance"
[string] $Database = "CM_SITENAME"

# C Drive Query
[string] $SQLQuery1 = $("SELECT [Bitlocker_C_Drive00] FROM [dbo].[Custom_Custom_DATA] WHERE MachineID='$ResourceID'")

# D Drive Query
[string] $SQLQuery2 = $("SELECT [Bitlocker_D_Drive00] FROM [dbo].[Custom_Custom_DATA] WHERE MachineID='$ResourceID'")

# Not used at this time - no need to use this if connecting in authorized security context
#[string] $user = "username"
#[string] $pwd = "LetMeIn99$"

$Connection = New-Object System.Data.SQLClient.SQLConnection
$dt = new-object "System.Data.DataTable"

$Connection.ConnectionString = "server='$Server';database='$Database';trusted_connection=true;"
#$Connection.ConnectionString = "server='$Server';uid=$user;pwd=$pwd;database='$Database';trusted_connection=true;"
$Connection.Open()

# C Drive
$cmd1 = $Connection.CreateCommand()
$cmd1.CommandText = $SQLQuery1
$data1 = $cmd1.ExecuteReader()
$dt.Load($data1)
$CDrive = $dt | foreach { $_.Bitlocker_C_Drive00 }
$CDrive

# D Drive
$cmd2 = $Connection.CreateCommand()
$cmd2.CommandText = $SQLQuery2
$data2 = $cmd2.ExecuteReader()
$dt.Load($data2)
$DDrive = $dt | foreach { $_.Bitlocker_D_Drive00 }
$DDrive

# Close Connection
$Connection.Close()