Import Powershell object data into SQL

Along the journey with Powershell, you've undoubtedly had a few issues manipulating data, all of which was loaded in memory and in the current session.  But, how can we store the output so we can visualize it?  Easy, stuff it into SQL.

#SQL Server Information 
$SQL_Server = Read-Host "SQL Server?"
$SQL_Database = Read-Host "SQL Database?"
$SQL_Table = Read-Host "SQL Table?"

#Get Count of All Sessions
Connect-AzAccount
$total = 0
$allPools = get-azwvdhostpool -resourcegroupname cloud-azure-na-avd-shared-rg | select Name
foreach ($aPool in $allPools) {
try {
$count = (Get-AzWvdSessionHost -ResourceGroupName cloud-azure-na-avd-shared-rg -HostPoolName $aPool.Name).count
write-host $aPool.Name, $count
$total += $count

#Insert data
$insert_data = "INSERT INTO AVD_Session_Counts ([ColumnName1], [ColumnName2], [ColumnName3]) VALUES ('$(Get-Date -Format 'yyyy/MM/dd HH:mm')','$($aPool.Name)','$([int]$count)');"
Invoke-Sqlcmd -ServerInstance $SQL_Server -Database $SQL_Database -Query $insert_data
}
catch {
Write-host "Whoops"

throw
}
}
#$list > $null
Write-host "Total Count: $total"

Leave a comment