I am trying to convert the below code to a PowerShell function as I will be using it multiple times in other scripts. I am trying to figure out how I can allow the user to simply pass a SQL Query (a String) to this script that I will turn into a function and have my hash table $row define the keys dynamically based on the column headers and then assign the values when multiple rows are returned by my SQL Query variable $QueryResults. Also, I will have two common variables in each hash table, which are "DateTime" and "ServerName" so those will have to be added as well.
$endpoint = "myPowerBIEndpoint"
$Query = "
myQueryThatReturnsMultipleRecords
"
$GetDate = (Get-Date).AddMinutes(-1)
while($true)
{
if((Get-Date) -gt $GetDate)
{
#Only run the below every 5 minutes
$GetDate = (Get-Date).AddMinutes(5)
#Get list of server to iterate through
$ServerList = Invoke-DbaQuery -SqlInstance "" -Database "" -Query "
EXEC [dbo].[myProc] @MonitorType" -SqlParameters @{MonitorType = "AGHealth"}
}
$ServerResults = @() # Results from each of the servers will be stored here
foreach ($Server in $ServerList)
{
$QueryResults = Invoke-DbaQuery -SqlInstance $ServerList.Cname -Database "" -Query $Query
$DateTime = Get-Date -DisplayHint Datetime -Format "MM/dd/yyyy HH:mm:ss"
foreach ($object in $QueryResults)
{
Write-Host 'Building Payload for' $object.replica_server_name
$row = @{
"DateTime" = $DateTime
"Replica_Server" = $object.replica_server_name
"Log_Send_Queue_Size_mb" = $object.total_log_send_queue_size_mb
"Redo_Queue_Size_mb" = $object.total_redo_queue_size_mb
"Sync_Health" = $object.synchronization_health
"Is_Primary_Replica" = $object.is_primary_replica
"AG_Name" = $object.ag_name
"ServerName" = $Server.Cname
}
$ServerResults += $row
}
}
$payload = @{ "rows" = $ServerResults }
Write-Host 'Invoking Rest Method'
Invoke-RestMethod -Method Post -Uri "$endpoint" -Body (ConvertTo-Json $payload)
(ConvertTo-Json $payload)
sleep 60
}
Invoke-DbaQueryalready solve this problem?