Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
260 views
in Technique[技术] by (71.8m points)

Windows Powershell 'if' always returning $true - What am I doing wrong?

Question pretty much says it all. I have a simple script (below) but the IF won't cooperate. It always evaluates to true even when the values don't match. Thanks in advance for any advice.

Add-Type -AssemblyName System.Windows.Forms
$pos = [System.Windows.Forms.Cursor]::Position
$x = $pos.X
$y = $pos.Y

while ($true)
{
  
  Write-Host "on loop strt: x = $($x), y = $($y)"

  $check = (($x -eq $pos.X) -and ($y -eq $pos.Y))
  write-host $check

  if (($x -eq $pos.X) -and ($y -eq $pos.Y))
  {
      for ($i = 0; $i -lt 2500; $i++)
      {
        $pos = [System.Windows.Forms.Cursor]::Position
        $x = ($pos.X % 1024) + 1
        $y = ($pos.Y % 768) + 1
        [System.Windows.Forms.Cursor]::Position = New-Object System.Drawing.Point($x, $y)
        for ($d = 0; $d -lt 1000; $d++) {} #add a little delay
      }
  }

  Write-Host "On loop exit: x = $($x), y = $($y)"

  Start-Sleep -Seconds 5

  $pos = [System.Windows.Forms.Cursor]::Position
  $x = $pos.X
  $y = $pos.Y
}
question from:https://stackoverflow.com/questions/66056699/windows-powershell-if-always-returning-true-what-am-i-doing-wrong

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Issue seemed to be trying to compare directly against pos.X and pos.Y -- I added 2 more variables $a and $b to compare against.

Add-Type -AssemblyName System.Windows.Forms

$pos = [System.Windows.Forms.Cursor]::Position
$x = $pos.X
$y = $pos.Y

$a = $x
$b = $y
while ($true)
{
  if ($x -eq $a -and $y -eq $b)
  {
    for ($i = 0; $i -lt 2500; $i++)
    {
        $pos = [System.Windows.Forms.Cursor]::Position
        $x = [int]($pos.X % 1024) + 1
        $y = [int]($pos.Y % 768) + 1
        [System.Windows.Forms.Cursor]::Position = New-Object System.Drawing.Point($x, $y)
        for ($d = 0; $d -lt 1000; $d++) {}
    }
  }
  else 
  { 
    $pos = [System.Windows.Forms.Cursor]::Position
    $x = $pos.X
    $y = $pos.Y
    $a = $x
    $b = $y
  }

  Start-Sleep -Seconds 5

  $pos = [System.Windows.Forms.Cursor]::Position
  $x = [int]$pos.X
  $y = [int]$pos.Y
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...