Powershell:如何使用 select-object 来获取一组动态属性?

Rea*_*tic 4 powershell powershell-2.0

我正在使用 powershell 和 sharepoint 07 来列出一些东西。我试图允许(高级)用户指定他们想要显示的字段。
例如,我可以按如下方式运行我的代码:
.\psextractor -fields "Type|name|User Desc
执行此操作 后,我将获得显示上面列出的字段的文件列表。目前我正在使用 Select-Object 标识符,我想知道这是否可能。如果没有,有没有办法在不使用 create-object cmdlet 的情况下做到这一点?
我的代码:

#$Args
if($Args[0] -eq "-fields" -and $Args.Count -ge 2){
    $flds = $Args[1].split("|")
}

#Later in code
 $web.Lists | foreach{
    $lib = $_
    if($lib.BaseType -eq [Microsoft.SharePoint.SPBaseType]::DocumentLibrary 
           -and $lib.BaseTemplate -eq [Microsoft.SharePoint.SPListTemplateType]::DocumentLibrary){
        $lib.Items |  Select-Object DisplayName,
                  @{n=$flds[0];e={$_.Item($flds[0])}} ,
                  @{n=$flds[1];e={$_.Item($flds[1])}}
                  #, etc, etc

    }

 }
Run Code Online (Sandbox Code Playgroud)

编辑: 我在下面使用了 Graimer 的解决方案并进行了一些调整

解决方案:

param([object[]]$flds)
$props=@() #globally declared since some of this is done in functions later

$mflds = $("Author","Created","Modified","Modified By") #mandatory fields
$mflds | foreach{
    if($flds -notcontains $_){
        $flds += $_
    }
}
#had to use regular for loop because the $_ identifier was conflicting
for ($i =0; $i -lt $flds.Count; $i++) { 
    $props += @{n=$flds[$i];e=([Scriptblock]::Create("`$_[`$flds[$i]]"))}
}
#other mandatory custom fields
    #the create method could have been used here
$props += @{n="FileName";e={"$($_.Item('Name'))"}}
$props += @{n="Url";e={"$wburl/$($_.Url)"}}

#Later in code
 $web.Lists | foreach{
    $lib = $_
    if($lib.BaseType -eq [Microsoft.SharePoint.SPBaseType]::DocumentLibrary 
           -and $lib.BaseTemplate -eq [Microsoft.SharePoint.SPListTemplateType]::DocumentLibrary){
        $lib.Items |  Select-Object -property $props

    }

 }
Run Code Online (Sandbox Code Playgroud)

Fro*_* F. 5

我建议将参数作为普通string[](数组)参数,并使用它来创建一个哈希表数组(用于 的自定义表达式Select-Object)。然后为哈希表提供Select-Object. 前任:

param (
    [String[]]$Fields
)

#Create property-array for Select-Object
$props = @()

#Add mandatory displayname property
$props += @{n="DisplayName";e=([Scriptblock]::Create("`$_.DisplayName"))}

#Add user-defined fields
foreach ($field in $Fields) { 
    $props += @{n=$field;e=([Scriptblock]::Create("`$_.Item($field)"))}
}

#Later in code
$web.Lists | foreach{
    $lib = $_
    if($lib.BaseType -eq [Microsoft.SharePoint.SPBaseType]::DocumentLibrary  `
    -and $lib.BaseTemplate -eq [Microsoft.SharePoint.SPListTemplateType]::DocumentLibrary)
    {
        $lib.Items | Select-Object -Property $props
    }

 }
#Usage: .\psextractor -Fields "Type", "Name", "User", "Desc"
#This will list all fields specified after '-Fields'
Run Code Online (Sandbox Code Playgroud)