Friday, December 03, 2010

修改SharePoint網站之清單"建立者"欄位

Environment
Server: Win2003 + SharePoint Service 3

需求: 當透過WSS UI的「儲存清單為範本」+「包括內容」選項將清單匯出後,再匯入時,所有清單項目的「建立者」欄位都會變成匯入人的名字。如果資訊人員佛心來的想替使用者改掉... 是可以做的,寫程式囉。

利用Microsoft提供的SharePoint API: Microsoft.SharePoint.dll。這支dll可以在SharePoint server上的\\Computer_Name\Drive$\Program Files\Common Files\Microsoft Shared\web server extensions\12\ISAPI 內找到。

但是,如果你覺得把他複製出來到自己本機開發那就錯了。這麼做應該會遇到「無法載入檔案或組件或其相依性的其中之一」的錯誤,就像這篇SharePoint Forums上的討論,請直接在裝有SharePoint Service的server上做開發.. 如果有測試機器是再好不過的,就可以參考這篇文章(Can we update the values of “Created By”, "Modified By” columns in SharePoint lists?)直接在Visual Studio上參考上述組件做開發。

如果你正好沒有測試環境,而且也無法在production上安裝VisualStudio這麼龐大的怪物的話,就參考這篇文章(Updating the “Created By” and "Modified By” Columns in SharePoint lists using POWERSHELL)。沒錯! 就是用POWERSHELL。這也是我用的方法。

script:

   1:  # Get the SharePoint Assembly 


   2:  # You will need to run this on the SharePoint Server


   3:  [Reflection.Assembly]::Load("Microsoft.SharePoint, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c") 


   4:   


   5:  # create a new object called $SPSite


   6:  # Make sure you have the last “/” in the url on the site 


   7:  # allow $SPWeb to be the OpenWeb from the site


   8:  $SPSite = New-Object Microsoft.SharePoint.SPSite("http://server-name/")


   9:  $SPWeb = $SPSite.OpenWeb() 


  10:   


  11:  # Get the list ModifyCreatedBy 


  12:  $SPList = $SPWeb.Lists["ListName"] 


  13:   


  14:  # Get the Collection of the List Items


  15:  $SPListItemCollection = $SPList.Items 


  16:   


  17:  # iterate the Collection


  18:  foreach ($ListItem in $SPListItemCollection) 


  19:  {


  20:   


  21:    # The user in this case was UserA with id of 8 from the SPWeb users 


  22:    $SPFieldUserValue = New-Object Microsoft.SharePoint.SPFieldUserValue($SPWeb,8,"UserA") 


  23:   


  24:    $ListItem["Author"] = $SPFieldUserValue


  25:   


  26:    # Note: Editor will be the account that you are running the Powershell under unless you update Editor as well 


  27:    # ListItem["Editor"] = $SPFieldUserValue


  28:   


  29:    $ListItem.Update() 


  30:  } 


  31:   


  32:  $SPWeb.Update() 


  33:   


  34:  # Still TODO Disposes, Error Checking, Change to take Parameters, etc


  35:   



 
上面的script是改了整個指定清單的建立者欄位,如果你還需要先判斷是那些文件,可以參考一下MSDN Library看看SPListItem還有哪些properities可以用。若是powershell語法不熟的話(尤其他又喜歡跟一般語法同.... 特別是比較運算子...),請參考reference#4, #5,或自行google。



嗯.. 大概就以上資訊,即可作業!!



Ref:




  1. [SharePoint Forums] Could not find Microsoft.SharePoint.Library.dll


  2. [MSDN Blog] Can we update the values of “Created By”, "Modified By” columns in SharePoint lists?


  3. [MSDN Blog] Updating the “Created By” and "Modified By” Columns in SharePoint lists using POWERSHELL


  4. [TechNet 技術文件庫] Running Windows PowerShell Scripts


  5. [賴榮樞的軟體資訊誌] scripting_PowerShell tag


  6. [MSDN Library] Microsoft.SharePoint Namespace

Tags