Skip to content

Instantly share code, notes, and snippets.

@briandenicola
Created April 5, 2013 16:35
Show Gist options
  • Save briandenicola/5320694 to your computer and use it in GitHub Desktop.
Save briandenicola/5320694 to your computer and use it in GitHub Desktop.
These are two simple functions that I use on a daily basis to interact with a SharePoint List - Get List Items and Create a New List Item. The parameters for Get-SPListViaWebService are pretty straight forward. The URL is the URL of the SharePoint Web were the list resides. If a view GUID is not passed then the list items in the default view are…
function Get-SPListViaWebService( [string] $url, [string] $list, [string] $view = $null )
{
begin {
$listData = @()
$service = New-WebServiceProxy (Get-WebServiceURL -url $url) -Namespace List -UseDefaultCredential
$FieldsWS = $service.GetList( $list )
$Fields = $FieldsWS.Fields.Field | where { $_.Hidden -ne "TRUE"} | Select DisplayName, StaticName -Unique
$data = $service.GetListItems( $list, $view, $null, $null, $null, $null, $null )
}
process {
$ErrorActionPreference = "silentlycontinue"
$data.data.row | % {
$item = $_
$t = new-object System.Object
$Fields | % {
$StaticName = "ows_" + $_.StaticName
$DisplayName = $_.DisplayName
if( $item.$StaticName -ne $nul ) {
$t | add-member -type NoteProperty -name $DisplayName.ToString() -value $item.$StaticName
}
}
$listData += $t
}
}
end {
return ( $listData )
}
}
function WriteTo-SPListViaWebService ( [String] $url, [String] $list, [HashTable] $Item, [String] $TitleField )
{
begin {
$service = New-WebServiceProxy (Get-WebServiceURL -url $url) -Namespace List -UseDefaultCredential
}
process {
$xml = @"
<Batch OnError='Continue' ListVersion='1' ViewName='{0}'>
<Method ID='1' Cmd='New'>
{1}
</Method>
</Batch>
"@
$listInfo = $service.GetListAndView($list, "")
foreach ($key in $item.Keys) {
$value = $item[$key]
if( -not [String]::IsNullOrEmpty($TitleField) -and $key -eq $TitleField ) {
$key = "Title"
}
$listItem += ("<Field Name='{0}'>{1}</Field>`n" -f $key,$value)
}
$batch = [xml]($xml -f $listInfo.View.Name,$listItem)
$response = $service.UpdateListItems($listInfo.List.Name, $batch)
$code = [int]$response.result.errorcode
if ($code -ne 0) {
Write-Warning "Error $code - $($response.result.errortext)"
} else {
Write-Host "Success"
}
}
end {
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment