我希望能夠使用PowerShell創建列表和選擇列,但選擇列總是失敗。我發現了幾個例子顯示我的代碼工作,所以我必須錯過一些東西。使用PowerShell創建SharePoint選項字段
clear
Add-PSSnapin Microsoft.SharePoint.PowerShell
function CreateCustomList($siteCollectionUrl, $listName, $listTitle, $listDescription) {
$spWeb = Get-SPWeb -Identity $siteCollectionUrl
$spTemplate = $spWeb.ListTemplates["Custom List"]
$spListCollection = $spWeb.Lists
$spListCollection.Add($listName, $listDescription, $spTemplate)
$path = $spWeb.url.trim()
#set display name
$spList = $spWeb.GetList("$path/Lists/$listName")
$spList.Title = $listTitle
$spList.Update()
return $spList
}
function AddChoiceField($spList, $title){
#create choices collection
$choices = New-Object System.Collections.Specialized.StringCollection
$choices.Add("Completed") | Out-Null
$choices.Add("Pending") | Out-Null
$choices.Add("Not Applicable") | Out-Null
#create choice field
$name = $title -replace '\s',''
$spFieldType = [Microsoft.SharePoint.SPFieldType]::Choice
$name = $spList.Fields.Add($name,
[Microsoft.SharePoint.SPFieldType]::Choice,
$false,
$false,
$choices);
#Set display Name
$spCol = $spList.Fields[$name]
$spCol.Title = $title
$spCol.Update()
}
$siteCollectionUrl = "http://URL"
$listName = "CustomCheckList"
$listTitle = "Custom Checklist"
$listDescription = "This checklist is used because of reasons"
$spList = CreateCustomList $siteCollectionUrl $listName $listTitle $listDescription
AddChoiceField $spList, "First checklist item"
編輯: 這裏是返回的錯誤消息
Cannot find an overload for "Add" and the argument count: "5".
At line:11 char:5
+ $name = $spList.Fields.Add($name,
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodException
+ FullyQualifiedErrorId : MethodCountCouldNotFindBest
Exception setting "Title": "Object reference not set to an instance of an object."
At line:19 char:5
+ $spCol.Title = $title
+ ~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], SetValueInvocationException
+ FullyQualifiedErrorId : ExceptionWhenSetting
添加fieldAsXml而不是寫這麼多的代碼。 – Vaibhav
「我的一堆代碼不起作用:* splat *」不是一個好問題。失敗如何?它應該做什麼,它做了什麼?它給了什麼錯誤?你曾經嘗試過什麼來隔離代碼行,或者修復它? – TessellatingHeckler
我不好,我忘了添加錯誤的詳細信息。 – Swazimodo