I can't figure out how to get the results of the query (qty_records) which is 5 so I can use it in a PowerShell If statement.
====
$my_query = "select count(CustomerNumber) as qty_records from customers"
$qty_records = Invoke-Sqlcmd -Query $my_query -ServerInstance "2008c" -Username sa -Password abc.1234 -Database MikeDB
if ($qty_records -gt 4) {
write-host "do something"
} else {
Write-Host "do something else"
}
====== thanks
The Invoke-Sqlcmd cmdlet runs a script containing the languages and commands supported by the SQL Server SQLCMD utility. The commands supported are Transact-SQL statements and the subset of the XQuery syntax that is supported by the database engine.
The official SqlServer module now includes a version of the Invoke-Sqlcmd cmdlet that runs in PSCore 6.2 and above. The version of the SqlServer module which contains this cmdlet is 21.1. 18095-preview and is available in the PowerShell Gallery.
I think the problem here is that Invoke-SqlCmd returns a datarow even if it's only returning a single value, so you need to expose the actual content. It's been a while since I worked in SQL so I'm a bit fuzzy on how the return values get named but I am reasonably sure based on your SELECT
that it will return with a .qty_records
property, so you would need to modify your if statement like so
if ($qty_records.qty_records -gt 4) {
write-host "do something"
} else {
Write-Host "do something else"
}
Note that it could return as .CustomerNumber
if I recall the mechanics incorrectly. If your interested in other methods of working with datarows I' recommend checking out This Post
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With