【问题标题】:Powershell; foreach-object; How to create proper output again to pipeline电源外壳; foreach 对象;如何再次创建正确的输出到管道
【发布时间】:2017-11-01 09:12:44
【问题描述】:

我已经进行了相当多的搜索以找到令人满意的答案,但找不到(无论是在 SO 上还是通过 Google)。

我目前正在使用以下命令从打印服务器上的所有打印机驱动程序中获取名称和产品版本,并将其通过管道传输到管道:

Get-WmiObject -Class Win32_PrinterDriver | select name, driverpath | %{ $Name = $_.name; $version = (get-item -LiteralPath $_.driverpath).VersionInfo.ProductVersion; write-output ($Name, $Version) }

从技术上讲,这可行,但管道输出很难看。输出如下所示:

远程桌面轻松打印,3,Windows x64
6.1.7601.17514
通用打印的 PCL6 驱动程序,3,Windows x64
3.4.100.1
MS Publisher 彩色打印机,3,Windows x64
6.1.7600.16385

我想要实现的是类似于以下内容(例如未通过 foreach 对象管道传输的对象的标准输出) - 例如。从以下命令:

Get-WmiObject -Class Win32_PrinterDriver | select name, driverpath

上述命令的输出如下所示:

name                                                        driverpath
----                                                        ----------

Remote Desktop Easy Print,3,Windows x64                     C:\Windows\system32\spool\DRIVERS\x64\3\mxdwdrv.dll
PCL6 Driver for Universal Print,3,Windows x64               C:\Windows\system32\spool\DRIVERS\x64\3\ricu00gr.dll

问题: 如何在 foreach-object 中准备输出以类似于上述格式/对象管道?

感谢您的任何意见。

致以诚挚的问候

【问题讨论】:

    标签: powershell foreach


    【解决方案1】:

    使用 Select-Object cmdlet 创建自定义属性。

    Get-WmiObject -Class Win32_PrinterDriver | select Name,Driverpath,@{l='Version';ex={(get-item -LiteralPath $_.driverpath).VersionInfo.ProductVersion}}
    

    【讨论】:

    • 很好的答案。正是我想要的。感谢这么快的回复。
    【解决方案2】:

    您可以像这样在 foreach 循环中创建一个 pscustomobject:

    Get-WmiObject -Class Win32_PrinterDriver | %{
        [pscustomobject]@{
        Name=$_.Name
        Driverpath=$_.Driverpath
        Version=(Get-Item $_.Driverpath).VersionInfo.ProductVersion
        }
    }
    

    【讨论】:

    • 感谢您的回答。从技术上讲,这是对我的问题的直接答案(如何从 foreach.object 循环内部创建正确的输出到管道。Vincent K 的答案与我以非常优雅的方式解决问题的完全匹配。但是因为你的answer 匹配问题,我给你“接受的答案标志”。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-14
    • 2020-10-10
    • 1970-01-01
    • 2022-01-27
    • 1970-01-01
    • 2014-11-23
    相关资源
    最近更新 更多