Pergunta

I am trying to compare the values of two variables but the contents of those two strings are in different orders

Example:

$Var1 = "item1"
$Var1 += "item2"
$Var2 = "item2"
$Var2 = "item1"

How can I compare those two variables to see if they both are equal?

===== UPDATED WITH EXAMPLE ===== EXAMPLE: Get objects and sort them.

$Computers = (Get-Content "$PWD\Computers.txt").GetEnumerator() | Sort-Object {"$_"}

EXAMPLE: Add the results and sort them.

$Successful += $Computer
$Successful = $Successful.GetEnumerator() | Sort-Object {"$_"}

EXAMPLE SCRIPT: Used the examples above to create the following script. The example allowed me to check the results, instead of count, but by content allowing me to get more accurate comparison. Before I was using "Successful.count -eq Computers.count" which wouldn't check if a computer was inputted twice.

$Computers = (Get-Content "$PWD\Computers.txt").GetEnumerator() | Sort-Object {"$_"}
$HotFixes = Get-Content "$PWD\HotFixes.csv"
CLS
While (!$Successful -OR $Successful -ne $Computers) {
    foreach  ($Computer in $Computers) {
        $MissingCount = 0
        IF (!$Successful -NotLike "*$Computer*") {
            Write-Host "$Computer`: Connecting"
            If (Test-Connection -ComputerName $Computer -Count 1 -quiet) {
                Write-Host "$Computer`: Connected"
                [string]$Comparison = get-hotfix -ComputerName $Computer | Select -expand HotFixID
                ForEach ($HotFix in $HotFixes) {
                    IF ($Comparison -NotLike "*$HotFix*") {
                        $Results += "$Computer,$HotFix"
                        $MissingCount++
                    }
                }
                Write-Host "$Computer`: $MissingCount Patches Needed"
                $Successful += $Computer
                $Successful = $Successful.GetEnumerator() | Sort-Object {"$_"}
            } ELSE {
                Write-Host "$Computer`: Unable to connect"
            }
        } ELSE {
            Write-Host "$Computer already completed"
        }
    Write-Host "$Computer`: Complete"
    Write-Host
    }

}

$Results
Foi útil?

Solução

If you want to find if the content is equal, regardless of characters position, you could break the string to its characters, sort the result and then use the Compare-Object cmdlet. No result means the variables are equal:

$v1 = $Var1.GetEnumerator() | Sort-Object {"$_"}
$v2 = $Var2.GetEnumerator() | Sort-Object {"$_"}
compare $v1 $v2
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top