首页 > 解决方案 > Windows Powershell 'if' 总是返回 $true - 我做错了什么?

问题描述

问题几乎说明了一切。我有一个简单的脚本(如下),但 IF 不会合作。即使值不匹配,它也总是评估为真。提前感谢您的任何建议。

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
}

标签: powershell

解决方案


问题似乎试图直接与 pos.X 和 pos.Y 进行比较——我添加了另外 2 个变量 $a 和 $b 进行比较。

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
}

推荐阅读