PowerShell脚本异常:isPrgmRunning返回False却进入if分支
PowerShell脚本异常排查:函数返回False但if条件仍执行
我是PowerShell新手,上周五才开始学习,若问题浅显还请见谅!我编写了一个脚本,用于检测指定程序(如Minecraft)是否运行,同时检测网络连接状态。但遇到异常:isPrgmRunning函数明明返回False,第一个if (isPrgmRunning -eq $true)语句却仍执行了。
原代码片段
if (isPrgmRunning -eq $true) { isPrgmRunning #Return false, why the last if statement pass ??? write-output "Programme is running" $isRunning = $true while($isRunning) { write-output "While the programme keep running" if(CheckInternetConnection) { if(isPrgmRunning -eq $false) { isPrgmRunning #Check again value, and it's false Write-Output "If it's not running anymore" $isRunning = $false } } } }
完整脚本包含CheckInternetConnection、ShowMessageBox、isPrgmRunning等函数,主逻辑在Main函数中循环检测网络和程序状态。
问题解决
原isPrgmRunning函数使用Get-Process -Name "Minecraft" -ErrorAction Stop存在问题,改用Get-Process | where{$_.Name -eq "Minecraft"} -ErrorAction Ignore后恢复正常,修改后的函数如下:
Function isPrgmRunning { $process = Get-Process | where{$_.Name -eq "Minecraft"} -ErrorAction Ignore #可替换为Teams等其他程序名 if($process){ return $true } else{ return $false } }
内容的提问来源于stack exchange,提问作者WypSteur
相关产品推荐
相关产品推荐

