I have these 2 arrays and I need to get the differences between them
$traceIhave = "3226,3042"
$traceIneed = "3042, 3226, 4199, 7745,8121"
Compare-Object $traceflagsIhave $traceineed
I want that show what is missing from traceIneed to traceihave which is 4199, 7745,8121
Even if I use as integer
$traceIhave = 3226,3042
$traceIneed = 3042, 3226, 4199, 7745,8121
Compare-Object $traceIhave $traceineed
returns
InputObject SideIndicator
----------- -------------
3042 =>
3226 =>
4199 =>
7745 =>
8121 =>
3226 3042 <=
Can Compare-object do this ?
>Solution :
You can use Compare-Object for this task but you would need to split by comma , those strings so the cmdlet can compare both arrays. Trim() is also used to remove any extra whitespace from each item in the arrays:
$traceIhave = '3226,3042'
$traceIneed = '3042, 3226, 4199, 7745,8121'
Compare-Object $traceIhave.Split(',').Trim() $traceineed.Split(',').Trim()
# InputObject SideIndicator
# ----------- -------------
# 4199 =>
# 7745 =>
# 8121 =>
If you’re interested only in the numbers you could use -PassThru here.
Looking at the edit, it seems what you actually have in $traceIhave is actually an array within an array or an unenumerated array. This could happen if the cmdlet you’re using outputs this array without enumerating it.
Example:
$traceIhave = , (3226, 3042)
$traceIneed = 3042, 3226, 4199, 7745, 8121
Compare-Object $traceIhave $traceineed
# InputObject SideIndicator
# ----------- -------------
# 3042 =>
# 3226 =>
# 4199 =>
# 7745 =>
# 8121 =>
# {3226, 3042} <=
The way you could deal with this is to pipe to Write-Output to unroll the array. If $traceIhave is the result of a command, you can directly pipe it after your command, example:
$traceIhave = (Invoke-Sqlcmd2 -ServerInstance . -Database master -Query "DBCC TRACESTATUS").traceflag | Write-Output
Using the example from before:
$traceIhave = , (3226, 3042) | Write-Output
$traceIneed = 3042, 3226, 4199, 7745, 8121
Compare-Object $traceIhave $traceineed
# InputObject SideIndicator
# ----------- -------------
# 4199 =>
# 7745 =>
# 8121 =>
Looking at the newly added screenshot to the question, the only possible explanation for that behavior is that some point your variable $traceIhave was constrained to a [string], i.e. [string] $traceIhave = ..... in which case the solution would have been to constrain it back to an [int[]]: [int[]] $traceIhave = .....