如何正确使用 IF 使用函数? [英] How can I use IF using a function properly?

查看:59
本文介绍了如何正确使用 IF 使用函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面的函数返回一个结果,但是当我在 IF 语句中指定值时,它只返回Yes";无论我在 -eq 值中输入什么.

The function below returns a result, but when I specify the value in an IF statement, it just return "Yes" whatever I put in the -eq value.

function GetRemoteLogonStatus ($computer = 'localhost') { 
if (Test-Connection $computer -Count 2 -Quiet) { 
    try { 
        $user = $null 
        $user = gwmi -Class win32_computersystem -ComputerName $computer | select -ExpandProperty username -ErrorAction Stop 
        } 
    catch { "Not logged on"; return } 
    try { 
        if ((Get-Process logonui -ComputerName $computer -ErrorAction Stop) -and ($user)) { 
            "Workstation locked by $user" 
            } 
        } 
    catch { if ($user) { "$user logged on" } } 
    } 
else { "$computer Offline" } 
}

if (getremotelogonstatus -eq "blah blah blah")
{
write-host "Yes"
}
Else
{
Write-Host "no"
}

谢谢

推荐答案

用于从 命令(例如 GetRemoteLogonStatus)的输出参与表达式,命令调用(包括其参数,如果有的话)必须包含在 (...) 中,分组运算符:

For output from a command (such as GetRemoteLogonStatus) to participate in an expression, the command call (including its arguments, if any) must be enclosed in (...), the grouping operator:

if ((GetRemoteLogonStatus) -eq "blah blah blah") {
  "Yes"
}
Else {
  "No"
}

注意:

  • 如果命令输出多个对象,-eq操作符将充当过滤器,而不是返回$true$false,将返回匹配元素的子数组 - 请参阅概念 about_Comparison_Operators 帮助主题.

  • If the command outputs multiple objects, the -eq operator will act as a filter and, instead of returning $true or $false, will return the subarray of matching elements - see the conceptual about_Comparison_Operators help topic.

要详细了解 PowerShell 的两种基本解析模式 - argument(命令)模式与 表达式 模式 - 请参阅这个答案.

To read more about PowerShell's two fundamental parsing modes - argument (command) mode vs. expression mode - see this answer.

至于你尝试了什么:

getremotelogonstatus -eq等等等等"

  • 因为这个片段是在argument模式下解析的,它调用命令getremotelogonstatus传递-eqblah blah blah 作为它的参数.

  • Because this snippet is parsed in argument mode, it invokes command getremotelogonstatus and passes -eq and blah blah blah as arguments to it.

由于您的命令既不正式 声明参数(带有 param(...) 块)也不处理 自动 $args 变量 包含未绑定的位置参数,这些参数是有效的忽略.

Since your command neither formally declares parameters (with a param(...) block) nor processes the automatic $args variable containing unbound positional arguments, these arguments are effectively ignored.

这篇关于如何正确使用 IF 使用函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆