Powershell: Retrieve Data from SQL database (placing data in a local CSV file)

Concern: I have a database that has near real-time data and I would like to use this data within PowerShell. How do I retreive this data and consume this within Powershell?

Example: You have a domain environment with ever changing server counts. You also use a network polling solution (example: LanSweeper) to audit your environment.

Note: To use the below, replace >>values<< with real world values.
#-------------------------Variables----------------------------
$SqlConnString = "Data Source=>>server<<;Database=>>database<<;User Id=>>username<<;Password=>>user password<<;" $CsvFile = ("file.csv") #-------------------------Functions---------------------------- Function RunServerQuery() { $SqlConnection = New-Object System.Data.SqlClient.SqlConnection $SqlConnection.ConnectionString = $SqlConnString $SqlConnection.Open() $SqlCmd = New-Object System.Data.SqlClient.SqlCommand $SqlCmd.CommandType = [System.Data.CommandType]'Text' $SqlCmd.CommandText = 'SELECT * FROM >>tablename<<' $SqlCmd.Connection = $SqlConnection $SqlCmd.CommandTimeout = 0 $da = New-Object System.Data.SqlClient.SqlDataAdapter($SqlCmd) $dt = New-Object System.Data.Datatable [void]$da.fill($dt) $SqlConnection.Close() #wrap the function result in an array because PowerShell automatically #unravels any enumerable object sent through the pipeline into an array return @(,$dt) } Clear-Host $dt = RunServerQuery #$dt | Format-Table -autosize $dt | Export-CSV $CsvFile -NoType -ErrorAction SilentlyContinue

No comments:

Post a Comment