Powershell 脚本忽略 $userInput 变量

问题描述 投票:0回答:2
function processSearch {
Get-Process -Name "$processSearch*"
}

function processKill {
Stop-Process -Name "$processSearch*"
}

$processSearch = Read-Host -Prompt "Enter the full or partial name of the process: "

processSearch

 if ((Get-Process -Name "$processSearch*") -eq $null) {
    Write-Output "ERROR: NO PROCESS FOUND."
    [Threading.Thread]::Sleep(3000) 
 }

if ((Get-Process -Name "$processSearch*") -ne $null) {
    $userInput= Read-Host -Prompt "Kill process?"
} 
     
if ($userInput -eq "y" -or "Y") {
    processKill
}
elseif ($userInput -eq "n" -or "N") {
    Write-Output "Process not killed."   
}
else {
    Write-Output "ERROR: UNHANDLED INPUT."
}            

当我的脚本到达

$userInput= Read-Host -Prompt "Kill process?"
并且我输入任何文本时,脚本将终止所选进程。

我是脚本新手,所以请让我知道我的逻辑哪里有缺陷,谢谢。

powershell syntax comparison-operators
2个回答
3
投票

您遇到的问题是因为当您检查

$userInput
变量时,您忘记了在子句的
-or
部分中声明要检查的变量。

此代码:

if ($userInput -eq "y" -or "Y") {
    processKill
}
elseif ($userInput -eq "n" -or "N") {
    Write-Output "Process not killed."   
}
else {
    Write-Output "ERROR: UNHANDLED INPUT."
}  

应该变成:

if ($userInput -eq "y" -or $userInput -eq "Y") {
    processKill
}
elseif ($userInput -eq "n" -or $userInput -eq "N") {
    Write-Output "Process not killed."   
}
else {
    Write-Output "ERROR: UNHANDLED INPUT."
}  

您还可以使用区分大小写的 -cin 运算符使 if 语句稍微简洁一些,因为这将检查该值是否位于给定值的数组中,如下所示:

if ($userInput -cin "y", "Y") {
    processKill
}
elseif ($userInput -cin "n", "N") {
    Write-Output "Process not killed."   
}
else {
    Write-Output "ERROR: UNHANDLED INPUT."
}

1
投票

NiMux 的回答提出了很好的观点,但值得退一步:

  • PowerShell 的运算符默认不区分大小写

    • 'y' -eq 'Y'
      $true
  • 要执行

    区分大小写操作,在操作员名称前加上c

    ;例如-ceq
    
    

      'Y' -ceq 'Y'
    • $true
      ,但是
      'y' -ceq 'Y'
      $false
      
      
  • 因此:

  • $userInput -eq 'y'

    $userInput -eq 'n'
    对于您的情况来说就足够了。
    
    

  • 如果您确实有
  • 多个

    值可供测试,请使用-in运算符

    ;例如:

      $userInput -in 'y', 'n', 'c'
    • 
      
至于
你尝试过的

由于 PowerShell 的

运算符优先级

$userInput -eq "y" -or "Y"

评价为:

($userInput -eq "y") -or ("Y")

也就是说,
-or

操作的RHS操作数是字符串

"Y"
alone
,并且在布尔上下文中的PowerShell中计算非空字符串始终会产生$true(无论字符串包含什么) .
实际上,您的尝试相当于以下内容,即

始终

$true

($userInput -eq "y") -or $true

对您的尝试的直接(但次优)修复将是 NiMux 的答案中所示的内容:使用两个单独的 
-eq

操作 (

$userInput -eq 'y' -or $userInput -eq 'Y'
)。
    

© www.soinside.com 2019 - 2024. All rights reserved.