Wednesday, 15 January 2014

Powershell: How to use select-object to get a dynamic set of properties? -



Powershell: How to use select-object to get a dynamic set of properties? -

i using powershell in conjunction sharepoint 07 list stuff out. trying allow (power) user specify fields want display. for example, run code follows: .\psextractor -fields "type|name|user desc after doing list of files displaying fields listed above. using select-object identifier , wondering if possible. if not, there way without using 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: used graimer's solution below few tweaks

solution:

param([object[]]$flds) $props=@() #globally declared since of done in functions later $mflds = $("author","created","modified","modified by") #mandatory fields $mflds | foreach{ if($flds -notcontains $_){ $flds += $_ } } #had utilize regular loop because $_ identifier conflicting ($i =0; $i -lt $flds.count; $i++) { $props += @{n=$flds[$i];e=([scriptblock]::create("`$_[`$flds[$i]]"))} } #other mandatory custom fields #the create method 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 suggest taking in paramters normal string[] (array) parameter, , utilize create array of hashtables (custom expressions select-object). supply hashtable select-object. ex:

param ( [string[]]$fields ) #create property-array 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 list fields specified after '-fields'

powershell powershell-v2.0

No comments:

Post a Comment