简体   繁体   中英

Comparing strings using powershell not working

I'm trying to compare strings using powershell but its not working as required.

$compare_test = @(Get-Content compare_test.txt)
$test = @(Get-Content test.txt)
for ($c1 = 0; $c1 -lt $test.Length; $c1++) {
    $space_position = $test[$c1].IndexOf(" ")
    $leftpart = $test[$c1].Substring(0, $space_position)
    $rightpart = $test[$c1].Substring($space_position+1)
    $type_cast_rightpart = [int]$rightpart
    for ($c3 = 0; $c3 -lt $compare_test.Length; $c3++) {
        $space_position_2 = $compare_test[$c3].IndexOf(" ")
        $leftpart_2 = $compare_test[$c3].Substring(0, $space_position_2)
        $rightpart_2 = $compare_test[$c3].Substring($space_position_2+1)
        $type_cast_rightpart_2 = [int]$rightpart_2
        $same_server = $leftpart_2.CompareTo($leftpart)
        if ($same_server -eq 0) {
            if ($type_cast_rightpart -gt $type_cast_rightpart_2) {
                $entry_server_log = $leftpart + " " + $type_cast_rightpart
                $myarray += $entry_server_log
                break
            }
            else {
                $entry_server_log = $leftpart + " " + $type_cast_rightpart_2
                $myarray += $entry_server_log
                break
            }
        }
        elseif ($same_server -eq 1 -or $same_server -eq -1) {
            $entry_server_log = $leftpart_2 + " " + $type_cast_rightpart_2
            $myarray += $entry_server_log
            break
        }
    }
}
Set-Content compare_test.txt $myarray

The elseif part executes everytime I tried to run the powershell script. The test.txt and compare_test both contain same set of strings as follows

NTHKGTBP126 2401
NTHKGTBP132 806

and so on.

It's hard to answer without access to the data. Have you looked at the Compare-Object cmdlet?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM