blog.icewolf.ch

Let's talk about IT!
posts - 590, comments - 86, trackbacks - 0

Powershell - SQL DB

Hallo zusammen,

Ich habe kürzlich die Benachrichtigung über Geburtstage auf meiner Website auf Powershell umgestellt. Dabei musste ich mit Powershell auf die MS SQL 2005 Datenbank zugreifen. Hier ein kleines Script welches genau das demonstriert.

#############################################################################################
# GetMovies
#############################################################################################
Function GetMovies {

 # Setup SQL Connection
 $SqlConnection = New-Object System.Data.SqlClient.SqlConnection
 $SqlConnection.ConnectionString = "Data Source=ICESRV02;database=db_home_icewolf;Uid=myusername;Pwd=mypassword"
 
 #SQL String
 $qSQL = "SELECT TOP 10 [fID], [fTitle], [fKategorie],[fBewertung],[fDatum],[fURL] FROM tMovies ORDER BY [fDatum] DESC"
 
 $SqlCmd = New-Object System.Data.SqlClient.SqlCommand
 $SqlCmd.CommandText = $qSQL
 $SqlCmd.Connection = $SqlConnection
 
 # Setup .NET SQLAdapter to execute and fill .NET Dataset
 $SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
 $SqlAdapter.SelectCommand = $SqlCmd
 $DataSet = New-Object System.Data.DataSet
 
 #Execute and Get Row Count
 $nRecs = $SqlAdapter.Fill($DataSet)
 
 $Anzahl = $nRecs.ToString()
 
 Write-Host ($anzahl + " Records retrieved.") -foregroundcolor Cyan
 $SqlConnection.Close();
 
 if ($nRecs -gt 0)
 {
   #$DataSet.Tables[0].Rows[0][3]  #Print first data element
   #$DataSet.Tables[0].columns | Format-Table -autosize -property ColumnName, DataType
 
   $ResultTable = $DataSet.Tables[0]
   $DataSet.Tables[0] | Format-Table
 
 
  foreach ($row in $ResultTable.Rows)
  {
    $Titel = [string] $row[1]
    $Kategorie = [string] $row[2]
    $Bewertung = [string] $row[3]
   $Datum  = [string] "{0:MM-dd-yy}" -f $row[4]
   
   Write-Host("Datum: " + $Datum + " Titel: " + $Titel + " Kat: " + $Kategorie + " Bewertung: " + $Bewertung) -foregroundcolor Green
  }
 }
}
#############################################################################################
# Programm
#############################################################################################
Write-Host ("Starting the owershell script....")
GetMovies
Write-Host ("Finished the owershell script....")

Und so sieht das ganze dann im Powershell Fenster aus...

Print | posted on Saturday, March 01, 2008 1:10 PM | Filed Under [ Powershell ]

Feedback

No comments posted yet.

Post Comment

Title  
Name  
Email
Url
Comment   
Please add 2 and 7 and type the answer here:

Powered by:
Powered By Subtext Powered By ASP.NET