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