I'm trying to use powershell to add a new item to a SharePoint list AND set the created by/author field. I don't have much experience with powershell but this seems fairly straightforward.
I have a 2013 environment and a list called Favorites that users populate with links they want to save. However, I'd like to be able to add a favorite for a user as read and edit access is limited to items created by the user.
My powershell script:
Add-PSSnapin Microsoft.SharePoint.PowerShell -EA SilentlyContinue
$SPWeb = Get-SPWeb "http://sharepoint";
$SPList = $SPWeb.GetList("http://sharepoint/Lists/Favorites");
$userName = "i:0#.w|[domain]\[username]";
$user = Get-SPUser -web $SPWeb -Identity $userName;
$SPListItem = $SPList.Items.Add();
$SPListItem["URL"] = "http://www.cnn.com";
$SPListItem["Author"] = $user;
$SPListItem.Update();
However, this gives the error:
Exception calling "Update" with "0" argument(s): "Invalid data has been used to update
the list item. The field you are trying
to update may be read only."
At line:11 char:1
$SPListItem.Update();
~~~~~~~~~~~~~~~~~~~~
CategoryInfo : NotSpecified: (:) [], MethodInvocationException
FullyQualifiedErrorId : SPException
If the field has a read only property, I thought it would be possible to change that:
$SPList.Fields["Author"].ReadOnlyField = $false;
However, that gives me this error:
Property 'ReadOnlyField' cannot be found on this object; make sure it exists and is
settable.
At line:6 char:1
$SPList.Fields["Author"].ReadOnlyField = $false;
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
CategoryInfo : InvalidOperation: (:) [], RuntimeException
FullyQualifiedErrorId : PropertyNotFound
Edit: after further investigation, there were recent security updates made to our SharePoint server by our network admin that may be related to this script no longer working. I will try to update this post with what I find out.
Any ideas are still appreciated.
Edit 2: see below for the solution I used.