为什么这不起作用? - 尝试将属性保存在变量中以便在函数中多次使用

Why is this not working? - Trying to save properties in a variable for use multiple times in a function

我正在尝试找到一种方法来在 PowerShell 中保存 select 语句的属性,但它不起作用。我还没有找到一种方法来使整个语句成为文字,以便在打开变量之前不会对其进行审查。

这是有效的:

$wsus.GetSummariesPercomputerTarget($CurrentMonthUpdateScope, $ComputerScope) |
    Select-Object @{L="WSUSServer";E={$Server}},
        @{L="FromDate";E={$($CurrentMonthUpdateScope.FromCreationDate).ToString("MM/dd/yyyy")}},
        @{L="ToDate";E={$($CurrentMonthUpdateScope.ToCreationDate).ToString("MM/dd/yyyy")}},
        @{L='Computer';E={($wsus.GetComputerTarget([guid]$_.ComputerTargetID)).FullDomainName}},
        DownloadedCount,
        NotInstalledCount,
        InstalledPendingRebootCount,
        FailedCount,
        Installedcount |
    Sort-Object -Property "Computer"

并且我试图将提到的属性(从 Select-Object 语句之后开始到最后一个管道之前结束)放在一个变量中,这样我就可以在不同的范围内多次使用相同的属性.

我试过这个:

$Properties = '@{L="WSUSServer";E={$Server}},
@{L="FromDate";E={$($CurrentMonthUpdateScope.FromCreationDate).ToString("MM/dd/yyyy")}},
@{L="ToDate";E={$($CurrentMonthUpdateScope.ToCreationDate).ToString("MM/dd/yyyy")}},
@{L="Computer";E={($wsus.GetComputerTarget([guid]$_.ComputerTargetID)).FullDomainName}},
DownloadedCount,
NotInstalledCount,
InstalledPendingRebootCount,
FailedCount,
Installedcount'

$wsus.GetSummariesPercomputerTarget($CurrentMonthUpdateScope, $ComputerScope) |
    Select-Object $Properties |
    Sort-Object -Property "Computer"

虽然它运行时没有提供任何数据,但我认为它混淆了 PowerShell。

这给出了相同的响应:

$Properties = "@{L=`"WSUSServer`";E={$Server}},
@{L=`"FromDate`";E={$($CurrentMonthUpdateScope.FromCreationDate).ToString(`"MM/dd/yyyy`")}},
@{L=`"ToDate`";E={$($CurrentMonthUpdateScope.ToCreationDate).ToString(`"MM/dd/yyyy`")}},
@{L=`"Computer`";E={($wsus.GetComputerTarget([guid]$_.ComputerTargetID)).FullDomainName}},
DownloadedCount,
NotInstalledCount,
InstalledPendingRebootCount,
FailedCount,
Installedcount"

有什么选择、想法等吗?

Select-Object-Property 参数需要一个数组,而不是字符串。所以像这样:

$Properties = @(@{L="WSUSServer";E={$Server}},
                @{L="FromDate";E={$($CurrentMonthUpdateScope.FromCreationDate).ToString("MM/dd/yyyy")}},
                @{L="ToDate";E={$($CurrentMonthUpdateScope.ToCreationDate).ToString("MM/dd/yyyy")}},
                @{L="Computer";E={($wsus.GetComputerTarget([guid]$_.ComputerTargetID)).FullDomainName}},
                "DownloadedCount",
                "NotInstalledCount",
                "InstalledPendingRebootCount",
                "FailedCount",
                "Installedcount")

请注意,您需要将简单的 属性 名称转换为数组中的字符串。