Avatar of johnj_01201
johnj_01201
 asked on

PowerShell Set-StrictMode -Version Latest

I've just discovered "Set-StrictMode -Version Latest" in Powershell and am wondering how to handle this issue, or is it an issue at all?

$MainQuery= Invoke-Sqlcmd -Query $Query

If the SQL returns more than 1 record then $MainQuery.Count is valid, but if there is only 1 result returned the "Count" property is not valid.

I want to show the number of records:
$TotalRecords = $MainQuery.Count
write-host $TotalRecords

*Also note, that in PS3 Microsoft changed something (forget what it is called) where 0 and 1 are different (no longer numbers unless specified with "@()" ) than numbers 2 and higher. As an example "@(1)" has to be used sometimes or it is seen as not a one, but an object or something. Thought I would mention this because it seems like it might be the same issue here?

Anyway, I guess $MainQuery might be  called a dynamic object because the properties change? Hmmm, maybe it is just the change Microsoft made, but I would still like to know if the code is "OK" or if I should handle it differently?

Does PS 4 have a way to test if a property exist for an object and then if it does I could code it so that if .Count was not available then to set the $TotalRecords = 1 else $TotalRecords = $MainQuery.Count

What are your thoughts?
thanks!
Powershell

Avatar of undefined
Last Comment
johnj_01201

8/22/2022 - Mon
ASKER CERTIFIED SOLUTION
footech

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
Qlemo

I'm not aware of a change of handling of 0 and 1 differently in PS3. Probably you mean the handling of (no element), (one element) and (many elements). No element is always something tricky, because it can mean many things, and sometimes needs to be ignored, in other cases not, and such.

As footech elaborated, enclosing results in @(...) will make sure you can treat them as "array" all the time.
johnj_01201

ASKER
Thanks. I'm new to PS and get confused. Your answer is the same (I think) to what I've found a while ago when trying to get IF statements to work when 1 result was returned from invoke-sql.  Based on your explanation, your fix is exactly what I need to do whenever I use invoke-sqlcmd and expect the .count property.

http://connect.microsoft.com/SQLServer/feedback/details/796367/count-property-of-invoke-sqlcmd-result-is-null-when-record-set-contains-exactly-one-record
All of life is about relationships, and EE has made a viirtual community a real community. It lifts everyone's boat
William Peck