Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
206 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 Reply

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
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...