4

我将 powershell 与 sharepoint 07 结合使用来列出一些内容。我试图允许(高级)用户指定他们想要显示的字段。
例如,我可以按如下方式运行我的代码:
.\psextractor -fields "Type|name|User
Desc想知道这是否可能。如果没有,有没有办法在不使用 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

    }

 }

编辑: 我在下面使用了 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

    }

 }
4

2 回答 2

6

我建议将参数作为普通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'
于 2013-02-06T15:19:37.307 回答
1

你可以这样尝试:

param([object[]]$fields)

$fields += "DisplayName"

 $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 $fields
    }

 }

像这样调用你的函数:

myfunction.ps1 -fields Type,name,User,Description
于 2013-02-06T15:17:45.437 回答