【问题标题】:Powershell: Passing an array of objects (SSRS.ReportingServices.CatalogItem) to a functionPowershell:将对象数组(SSRS.ReportingServices.CatalogItem)传递给函数
【发布时间】:2021-01-27 16:56:13
【问题描述】:

我正在使用 PowerShell 管理一个新的 SSRS 实例。我写了一个很长的脚本,但我想把它分解成函数。

第一步是获取服务器上的报告列表。我使用一个函数来做到这一点。

function Get-ReportList {
    [CmdLetBinding()]
    param (
        [Parameter(Mandatory)][string]$Server,
        [Parameter(Mandatory)][string]$Path,
        [Parameter(Mandatory)][string]$Type
    )

    try {
        $Proxy = New-WebServiceProxy -Uri $Server -Namespace SSRS.ReportingService2010 -UseDefaultCredential -ErrorAction Stop
    }
    catch {
        Write-Warning -Message "Unable to create Proxy at " $Server
    }
        
    $Reports = $Proxy.ListChildren($Path,$true) | Where-Object{$_.typename -eq $Type} 

    # Output the list of reports
    $Reports
}

接下来我创建了一个函数,该函数获取上述函数的输出并将其导出到 CSV 文件。根据 Microsoft 文档,ReportingService2010 方法 ListChildren 返回一个 CatalogItem 数组。我明确声明我的输入参数是一个 CatalogItems 数组。

$ReportList = Get-ReportList -Server $MyServer -Path $MyPath  -Type 'Report'

function Write-ReportList {
    [CmdLetBinding()]
    param (
        [Parameter(Mandatory)][SSRS.ReportingService2010.CatalogItem[]]$ReportList,
        [Parameter(Mandatory)][string]$CSVPath
    )

    $ReportList | Export-Csv -Path $CSVPath -NoTypeInformation
}

Write-ReportList -ReportList $ReportList -CSVPath "MyPath"

执行上述操作会给出一个令人费解的消息,说明它无法将类型转换为自身:

Write-ReportList : Cannot process argument transformation on parameter 'ReportList'. Cannot convert the 
"SSRS.ReportingService2010.CatalogItem" value of type "SSRS.ReportingService2010.CatalogItem" to type 
"SSRS.ReportingService2010.CatalogItem".

FWIW,代码

$ReportList | Export-Csv -Path "MyPath" -NoTypeInformation

可以自己工作,但我找不到将其包装在函数中的方法。我想创建更多的函数来接受这些对象的列表。有没有办法让我想要的功能发挥作用?

【问题讨论】:

  • "接下来我创建了一个函数,它接受上述函数的输出并将其导出为 CSV 文件。"为什么? Export-Csv 已经存在 :-)
  • 是的,确实如此,但我想创建类似的函数,将报告列表作为输入并做更复杂的事情。我尝试了这个微不足道的功能作为测试。

标签: c# powershell reporting-services


【解决方案1】:

经过一些实验,我找到了一个解决方案:使用 pscustomobject 而不是显式类型。

$ReportList = Get-ReportList -Server $MyServer -Path $MyPath  -Type 'Report'

function Write-ReportList {
    [CmdLetBinding()]
    param (
        [Parameter(Mandatory)][pscustomobject[]]$ReportList,
        [Parameter(Mandatory)][string]$CSVPath
    )

    $ReportList | Export-Csv -Path $CSVPath -NoTypeInformation
}

Write-ReportList -ReportList $ReportList -CSVPath "MyPath"

脚本有效。

【讨论】:

    猜你喜欢
    • 2016-03-30
    • 1970-01-01
    • 2020-12-22
    • 2021-11-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-01
    相关资源
    最近更新 更多