I am using powershell in conjunction with sharepoint 07 to list some stuff out. I am trying to allow a (power) user to specify which Fields they want to display.
For example, I could run my code as follows:
.\psextractor -fields “Type|name|User Desc
After doing this I would get a list of files displaying the fields listed above. Currently I am using the Select-Object identifier and I was wondering if this was possible. If not, is there a way to do this without using the create-object cmdlet?
My code:
#$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
}
}
EDIT:
I used Graimer’s solution below with a few tweaks
SOLUTION:
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
}
}
I would suggest taking in the paramters as a normal
string[](Array) parameter, and use it to create an array of hashtables (custom expressions forSelect-Object). Then supply the hashtable withSelect-Object. Ex: