我正在使用 powershell 和 sharepoint 07 来列出一些东西。我试图允许(高级)用户指定他们想要显示的字段。
例如,我可以按如下方式运行我的代码:
.\psextractor -fields "类型|名称|用户描述
这样做后,我会得到一个文件列表,显示上面列出的字段。目前我正在使用 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
}
}
编辑:
我在下面使用了 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
}
}
最佳答案
我建议将参数视为正常 string[]
(Array) 参数,并使用它来创建一个哈希表数组(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'
关于Powershell:如何使用 select-object 获取一组动态属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14731782/