我试图比较两个变量的值,但这两个字符串的内容是不同的顺序
示例:
$Var1 = "item1"
$Var1 += "item2"
$Var2 = "item2"
$Var2 = "item1"
如何比较这两个变量以确定它们是否相等?
=====更新示例===== 示例:获取对象并对其进行排序。
$Computers = (Get-Content "$PWD\Computers.txt").GetEnumerator() | Sort-Object {"$_"}
示例:添加结果并对其进行排序。
$Successful += $Computer
$Successful = $Successful.GetEnumerator() | Sort-Object {"$_"}
示例脚本:使用上面的示例创建以下脚本。该示例允许我检查结果,而不是计数,但通过内容允许我进行更准确的比较。在我使用“Successful.count -eq Computers.count”之前,它不会检查计算机是否被输入两次。
$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
答案 0 :(得分:4)
如果要查找内容是否相等,无论字符位置如何,都可以将字符串分解为字符,对结果进行排序,然后使用Compare-Object cmdlet。没有结果意味着变量是相等的:
$v1 = $Var1.GetEnumerator() | Sort-Object {"$_"}
$v2 = $Var2.GetEnumerator() | Sort-Object {"$_"}
compare $v1 $v2