Need to add a item to a list in SharePoint with PowerShell?
I have create a small function that allows you to use the REST API in SharePoint to create a list item.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 |
################################################ <# Function - Start #> #Creates a PS credential object. Function Create-PSCredential { [cmdletbinding()] Param ( [Parameter(Mandatory=$true, HelpMessage="Please provide a valid username, example 'Domain\Username'.")]$Username, [Parameter(Mandatory=$true, HelpMessage="Please provide a valid password, example 'MyPassw0rd!'.")]$Password ) #Convert the password to a secure string. $SecurePassword = $Password | ConvertTo-SecureString -AsPlainText -Force; #Convert $Username and $SecurePassword to a credential object. $Credential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $Username,$SecurePassword; #Return the credential object. Return $Credential; } #Adds a SharePoint List Item using REST. Function Create-SPListItem { [cmdletbinding()] Param ( [Parameter(Mandatory=$True)]$Credential, [Parameter(Mandatory=$True)][string]$Site, [Parameter(Mandatory=$True)][string]$List, [Parameter(Mandatory=$True)][HashTable]$Content ) #Construct path to list API. $ListSvc = ($Site + "/_vti_bin/listdata.svc/" + $List); #Webrequest headers. $Headers = @{ "Accept" = "application/json;odata=verbose"; } #Convert hashtable to JSON. $Body = $Content | ConvertTo-Json; #Invoke the REST API. $Result = Invoke-WebRequest -Uri $ListSvc -Method Post -Credential $Credential -Headers $Headers -ContentType "application/json" -Body $Body; #If the status description is set to created. If($Result.StatusDescription -eq "Created") { #True. Return $true; } Else { #False. Return $false } } <# Functions - End #> ################################################ <# Main - Start #> #SharePoint site. $SPSite = "https://sharepoint.contoso.com/site/123"; #SharePoint list name. $SPList = "MyList"; #Credentials. $Username = “Contoso\User”; $Password = “MyPassword”; $Credential = Create-PSCredential -Username $Username -Password $Password; #List Item Data. $Content = @{ Column1 = "Data1"; Column2 = "Data2"; Column3 = "Data3"; } Create-SPListItem -Credential $Credential -Site $SPSite -List $SPList -Content $Content; <# Main - End #> ################################################ |
Hi.
I am using Powershell ver 3.0 and it gives me this error
Invoke-WebRequest : The ‘Accept’ header must be modified using the appropriate property or method.
Parameter name: name
Is there a workaround?
Pretty useful. Thx