简体   繁体   English

如何在 Where-Object Powershell 中使用 If Else

[英]How To Use If Else In Where-Object Powershell

I am attempting to search HotFixes installed on a machine and pipe the machine name with the specified KB installed to an excel sheet "else" pipe the machine names without the KB installed to another excel sheet.我正在尝试搜索安装在机器上的 HotFixes,并将安装了指定 KB 的机器名称通过管道传输到 Excel 工作表,“否则”将没有安装 KB 的机器名称传输到另一个 Excel 工作表。

I've gotten the basic command down that will do this but because it uses the % (foreach) command, it is appending the machine name to the excel sheet for each KB it finds or doesn't find and I end up with dozens of duplicates.我已经完成了执行此操作的基本命令,但是因为它使用 % (foreach) 命令,它会将机器名称附加到它找到或找不到的每个 KB 的 Excel 表中,我最终得到了几十个重复。

How can I get this code to append a single entry for each search through all the KBs and not for each KB?我怎样才能让这个代码为所有 KB 的每次搜索而不是每个 KB 附加一个条目?

Get-HotFix | %{if($_.HotFixID -match "KB2687455"){(get-wmiobject win32_computersystem).name | Out-File C:\Installed.txt -append}` else{(get-wmiobject win32_computersystem).name | Out-File C:\NotInstalled.txt -Append}}

EDIT:编辑:

I have found a work around.我找到了解决方法。 Instead of trying to do this in a command line type of code I rewrote the code and surprisingly it worked.我没有尝试在命令行类型的代码中执行此操作,而是重新编写了代码,结果令人惊讶的是它起作用了。 Let me know if you see any potential issues with this code.如果您发现此代码有任何潜在问题,请告诉我。

if (Get-HotFix |?{$_.HotFixID -match "KB2687455"}) {
    (get-wmiobject win32_computersystem).name | out-file C:\Installed.txt
}
else {
    (get-wmiobject win32_computersystem).name | out-file C:\NotInstalled.txt
}

You are looping over the hot fixes that are installed, and writing results for each hot fixes when it looks like all you want to do is write whether a given machine has a hot fix installed or not.您正在循环安装已安装的修补程序,并在看起来您想要做的只是写出给定机器是否安装了修补程序时为每个修补程序编写结果。 I'm assuming you will be running this on multiple machines and that the output file will be on a network share.我假设您将在多台机器上运行它,并且输出文件将位于网络共享上。

You need to break out of your ELSE block after the initial pass:您需要在初始通过后跳出 ELSE 块:

Get-HotFix | % { 
    if($_.HotFixID -match "KB2687455") {
        (get-wmiobject win32_computersystem).name | Out-File C:\temp\Installed.txt -append
    } else{
        (get-wmiobject win32_computersystem).name | Out-File C:\temp\NotInstalled.txt -Append
        break
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM