powershell - Powershell if语句

标签 powershell powershell-4.0

在我的其中一台服务器中,我们有一个程序,每个月需要更新一次,该程序在终端服务器上运行。

我的基本脚本正在运行(非常简单):


Get-SmbOpenFile |where {$_.Path -eq "D:\Shares\Programs\test.exe"} |select ClientUserName, path |ft -autosize

pause

但是我试图使其更“智能”,因此我尝试使用IF语句:

第一次测试:
$open = Get-SmbOpenFile |where {$_.Path -eq "D:\Shares\Programs\test.exe"} |`
select ClientUserName, path |ft -autosize



if ($open -eq "true")
{ write-host "showing open files"
}

elseif ($open -eq "false")
{ "All cloesd"
}

pause

第二次测试:
$open = Get-SmbOpenFile |where {$_.Path -eq "D:\Shares\Programs\test.exe"} |`
select ClientUserName, path |ft -autosize


if ($open -eq $true)
{
 write-host "showing open files"
}

elseif ($open -eq $false)
{ 
"All cloesd"
}

我也尝试过以这种方式定义变量:
$open = Get-SmbOpenFile |where {$_.Path -eq "D:\Shares\Programs\test.exe"} 

当我使用IF语句时,实际上根本没有任何输出。

非常感谢你的帮助 !

最佳答案

  • 仅使用Format-* cmdlet(例如ft(Format-Table))进行显示格式设置;如果必须对数据进行编程处理,请不要使用Format-* cmdlet输出格式说明,而不是数据-请参阅this answer
  • 即使删除了| ft -autosize,也不应将$open$true 进行比较,因为如果LHS尚未为 bool(boolean) 值(类型$false)[1],则这样的显式比较通常将无法正常工作。相反,利用PowerShell的隐式to-Boolean转换-请参阅this answer的底部。
  • 您的[bool]分支实际上并不输出if;它仅向显示屏输出$open状态消息。

  • 放在一起:
    $open = Get-SmbOpenFile | 
              Where-Object {$_.Path -eq "D:\Shares\Programs\test.exe"} |
                Select-Object ClientUserName, Path
    
    if ($open) {
      Write-Host "showing open files"
      $open  # output the result
    }
    else {
      Write-Host "all closed"
    }
    
    Write-Host返回以下之一:
  • 一个Select-Object实例[2](具有属性[pscustomobject].ClientUserName的自定义对象)
  • 任何.Path实例(无论其结构如何)都会在 bool(boolean) 上下文中求值为[pscustomobject]
  • 如果$true cmdlet在[System.Management.Automation.Internal.AutomationNull]::Value的输出中找不到指定的路径,则为
  • 或“nothing”(从技术上来说,为Where-Object)。
  • 在 bool(boolean) 上下文中,“Nothing”的计算结果为Get-SmbOpenFile

  • 同样,请参见this answer的底部,以获取完整的隐式到 bool(boolean) 转换规则。

    [1]值得注意的是,由于LHS与$false相比,非原始对象始终会产生$false(尽管操作数取反)。例如$true;同样,任何不完全是(Get-Item /) -eq $true的非零数字都将指示1;例如:$false。此外,使用数组值的LHS时,2 -eq $true充当过滤器,返回匹配项的子数组(例如,-eq返回(1, 2, 1) -eq $true

    [2]通常,1, 1可以返回多个对象,在这种情况下,Select-Object将收到$open类型的[object[]]实例数组。具有2个或更多元素的数组在 bool(boolean) 上下文中始终为[pscustomobject]

    关于powershell - Powershell if语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61365415/

    相关文章:

    .net - 如何将ManagementObjectCollection对象转换为Powershell可读的格式?

    excel - 使用每个列出的 OU 的所有计算机创建 excel csv 文件

    powershell - 在 powershell 中读取具有可变列数的 CSV

    Powershell - "Expressions are only allowed as the first element of a pipeline"

    powershell-4.0 - Powershell:使用 ScriptBlock::Invoke 时如何获取异常行号

    powershell-4.0 - 如何从powershell提示中删除 "username@host"?

    powershell - 通过 Graph 更新 AzureAD/O365 UPN

    安装 Windows 更新后检查重启状态的 Powershell

    powershell - 在目标目录的每个子目录中创建 CSV 文件

    powershell - 检查用户是否存在于组中