我希望能够使用PowerShell创建列表和选择列,但“选择”列始终失败。我找到了一些显示我的代码工作的例子,所以我必须遗漏一些东西。
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
答案 0 :(得分:1)
您的代码看起来是正确的,因此必定会出现其他问题。
在PowerShell中,如果您愿意使用XML字符串,function AddChoiceField($spList, $title){
$name = $title -replace '\s',''
$xml = '<Field Required="FALSE" Description="" DisplayName="' + $name +
'" Type="Choice" Format="Dropdown" FillInChoice="FALSE">' +
'<CHOICES><CHOICE>Completed</CHOICE><CHOICE>Pending</CHOICE><CHOICE>Not Applicable</CHOICE></CHOICES>' +
'</Field>'
$spList.Fields.AddFieldAsXml($xml);
$spList.Update();
$spCol = $spList.Fields[$name]
$spCol.Title = $title
$spCol.Update()
}
确实会更容易一些。
由于它只有一个参数(并且它是一个字符串),因此PowerShell不太可能与各种对象/参数类型以及潜在或虚构的方法重载混淆。
steve_s_baue
marine_camp_se_bell
mike_wane
答案 1 :(得分:1)
这是一个不了解PowerShell如何处理参数和返回值的情况。
调用函数和传入参数时,如果不使用参数名,则假定将数组传递给函数的第一个参数。这就是为什么Thriggle建议使用AddFieldAsXml不存在而且对我来说失败了。
对于返回值,函数的所有输出都作为数组传回。我使用$ return [-1]从返回值中获取最后一个参数,并将其保存为我想要的列表对象。
$return = CreateCustomList $siteCollectionUrl $listName $listTitle $listDescription
$spList = $return[-1]
AddChoiceField -spList $spList -title "SR Test List"