@Syuhei Mashino - I tested the above script at my end and it was working fine.However, there are few minute changes I have done.
I am assuming you have imported the necessary CSOM modules to the Automation Account - If not you can perform the step
**Importing the Module to the Automation Account **
I have uploaded the Sharepoint CSOM DLLs to the module of the Automation Account.
I created Zip file named Microsoft.SharePoint.Client and added the Microsoft.SharePoint.Client.dll and Microsoft.SharePoint.Client.Runtime.dll file under it.
The above DLLs can be found at your local machine. Default location would be (C:\Program Files\Common Files\microsoft shared\Web Server Extensions\16\ISAPI). But if you had given different installation location - you may find it in another path.
I added the ZIP file to the Modules section of the Automation Account using the Add Module. (Automation Account -> Modules -> Add Module)
Importing the Module to the Runbook
Added the below two lines to import the CSOM Module for performing the interaction with Sharepoint Client.
Add-Type -Path “C:\Modules\User\Microsoft.SharePoint.Client\Microsoft.SharePoint.Client.dll"
Add-Type -Path “C:\Modules\User\Microsoft.SharePoint.Client\Microsoft.SharePoint.Client.Runtime.dll"
Instead of your earlier code which imports the module from the GAC (This would work in local machine, but you may need import it explicitly in the run book by running the above command)
Complete Code :
Add-Type -Path “C:\Modules\User\Microsoft.SharePoint.Client\Microsoft.SharePoint.Client.dll"
Add-Type -Path “C:\Modules\User\Microsoft.SharePoint.Client\Microsoft.SharePoint.Client.Runtime.dll"
"Starting Execution"
$siteUrl = "SHAREPOINTSITE" #dummy
$accountName = "<USER>" #dummy
$passWord = ConvertTo-SecureString -AsPlainText -Force "<PASSWORD>" #dummy
$listName = "<LISTNAME>" #dummy
$ctx = New-Object Microsoft.SharePoint.Client.ClientContext($siteUrl)
$credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($accountName, $passWord)
$ctx.Credentials = $credentials
$list = $ctx.Web.Lists.GetByTitle($listName)
$listInfo = $list.Fields
$ctx.Load($listInfo)
$ctx.ExecuteQuery()
"Field Count in the list : "
$listInfo.count
"Creating the Item...."
$creation = New-Object Microsoft.SharePoint.Client.ListItemCreationInformation
$item = $list.AddItem($creation)
$item["Title"] = "CreateTestItem"
$item.Update()
$ctx.Load($item)
$ctx.ExecuteQuery()
"Item Created in the list"
Output :
Note :
Also, pls confirm your account is not subjected to Multi Factor Authentication (MFA) outside the organizational network/device. If this is the case, you may need to use Service accounts to overcome the MFA Authentication. Since Runbook is more of automated process - it will not be able handle the MFA process.