Insert random username to SharePoint 2013 column from array PowerShell script

506 Views Asked by At

I wrote script to create N number of items to custom SharePoint list in PowerShell. I made it work with fixed values, but now I would like to create items with random values.
I created internal variables that are array of values and I would like out of those to be set in list columns.
I made it work for some simple columns like date, single and multi line of text, etc. But I can't seem to make it work for lookup and people picker values. Bellow is example of script I made. For this example, I don't get error in PowerShell I just get incorrect result in columns, example is I get username in people picker column that is not in value userName array. I get ID;#User8 (for example) that is not in array.

If you have any suggestion what I should change or add to get only values from array?

Add-PSSnapin Microsoft.SharePoint.PowerShell -EA SilentlyContinue

$webUrl = "site url"
$listName = "list name"
$numberItemsToCreate = N
# userName is array of values of usernames that would be set to people picker column
$userName = ID;#user1, ID;#User2, ID;#User3, ID;#User6, ID;#User10
# projectName is array of values of projects that are lookup column from another list
$projectName = 1;#Project1, 2;#Project2, 3;#Project3, 4;#Project4
# 

$web = Get-SPWeb $webUrl
$list = $web.Lists[$listName]

for($i=1; $i -le $numberItemsToCreate; $i++)
{
$newItem = $list.AddItem()
$newItem["Title"] = "Title"
$newItem["Project"] = (Get-Random $projectName)
$newItem["DueDate"] = "2017-12-12 00:00:00"
$newItem["Assigned_x0020_To"] = (Get-Random $userName)
$newItem["EstimatedFinishDate"] = "2017-12-12 00:00:00"
#$newItem["Status"] = "ToDo"
$newItem["URLs"] = "www.google.com"

$newItem.Update()
}

$web.Dispose()
1

There are 1 best solutions below

1
On BEST ANSWER

This "$userName = ID;#user1, ID;#User2, ID;#User3, ID;#User6, ID;#User10" is not a PowerShell array or hashtable

Using an array:

$userName = @("#user1", "#User2", "#User3", "#User6", "#User10")
$newItem["Assigned_x0020_To"] = Get-Random $userName

Using a hashtable:

$projectName = @{1="#Project1"; 2="#Project2"; 3="#Project3"; 4="#Project4"}
$newItem["Project"] = $ProjectName.(Get-Random @($ProjectName.Keys))

Or just:

$newItem["Project"] = Get-Random @($ProjectName.Values)