문제

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
도움이 되었습니까?

해결책

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
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top