tirsdag den 4. oktober 2011

Get-SQLData


I like working with FIM (Microsoft ForeFront Identity Management). I'm currently working with Søren Granfeldt on a Homedir MA, and i find myself needing som extra entries from the metaverse in my Powershell script. I designed this cmdlet to get me, what i needed:

Function Get-SQLData {
<#
.SYNOPSIS
   Gets data from MSSQL tables

.DESCRIPTION
   Gets data from MSSQL tables
 
.EXAMPLE
    Get-SQLData -SQLServer FLHSRV144 -SQLDBName FIMSynchronizationService -Schema dbo -Select * -Field Uid -Value ITSABA
 Returns the entire record containing ITSABA on the field Uid in the FIMSynchronizationService database on FLHSRV144
.EXAMPLE
 Get-SQLData -SQLServer FLHSRV144 -SQLDBName FIMSynchronizationService -Schema dbo -Select isMailUser -Field Uid -Value ITSABA
 Returns the value for isMailUser for the record where Uid equals ITSABA in the FIMSynchronizationService database on FLHSRV144
#>
Param ($SQLServer = "FLHSRV144",
 $SQLDBName = "FIMSynchronizationService",
 $Schema = "dbo",
 $Table = "mms_metaverse",
 $Select = "*",
 $Field = "Uid",
 $Value
 )
 $SqlQuery = "SELECT $Select FROM [$SQLDBName].[$Schema].[$Table] Where $Field = '" + $Value + "'"
 $SqlConnection = New-Object System.Data.SqlClient.SqlConnection
 $SqlConnection.ConnectionString = "Server = $SQLServer; Database = $SQLDBName; Integrated Security = True"
 $SqlConnection.open()
 $SqlCmd = New-Object System.Data.SqlClient.SqlCommand
 $SqlCmd.CommandText = $SqlQuery
 $SqlCmd.Connection = $SqlConnection

 $Reader =  $SqlCmd.ExecuteReader()
 $Counter = $Reader.FieldCount
 $info = @{}
 while ($Reader.Read()) {
 for ($i = 0; $i -lt $Counter; $i++) {
 $info.add($Reader.GetName($i),$Reader.GetValue($i))
 }
 }
 $Reader.Close()
 $SqlConnection.Close()
 New-Object PSObject -Property $info
    }

Now all MV-entries are accessible from my script.
Feel free to reuse and modify.

Ingen kommentarer:

Send en kommentar