This is my first Powershell script ever so bear with me.
I'm trying to replace values in a sharepoint list from a CSV file:
Param(
[Parameter(Mandatory=$true)][string] $csvFileName = $null,
[Parameter(Mandatory=$true)][string] $sharePointWebUrl = $null
)
$isError = $false
cls
$csvFileName = $csvFileName.Trim()
$sharePointWebUrl = $sharePointWebUrl.Trim()
if ([string]::IsNullOrEmpty($csvFileName))
{
Throw "Please enter parameter values for CSVFileName"
}
if ([string]::IsNullOrEmpty($sharePointWebUrl))
{
Throw "Please enter parameter values for sharePointWebUrl"
}
Add-PSSnapin Microsoft.Sharepoint.Powershell
try
{
$csv = Import-Csv $csvFileName
$subWeb = get-spweb -identity "$sharePointWebUrl"
$mylistitems = $subWeb.Lists["MyList"].Items | sort Title
$csvCollection = New-Object System.Collections.ArrayList
$csv | ForEach-Object {
$temp = "" | select "Topics", "Column1"
$temp.Topics = $_.Topic
$temp.Column1 = $_.NewTopic
$csvCollection.Add($temp) | Out-Null
}
try
{
foreach ($li in $mylistitems) {
$loopcount=0
:loop foreach ($si in $csvCollection)
{
$loopcount =$loopcount + 1
if ($li["Topics"] -eq $si.Topics)
{
$li["Topics"] = $si.Column1
$isFound =$true
$li.Update()
break loop
}
}
}
}
catch
{
$isError = $true
$time = Get-Date
$ErrorMessage = $_.Exception.Message
"Error Occurred ($time) with error message: $ErrorMessage"| out-file ".\error.log" -append
}
}
catch
{
$isError = $true
$time = Get-Date
$ErrorMessage = $_.Exception.Message
"Error Occurred ($time) with error message: $ErrorMessage"| out-file ".\error.log" -append
}
finally
{
if ($web) {
$web.dispose();
}
if ($isError) {
write-host "script completed with error(s), please look into error.log file" -ForegroundColor Red
} else {
write-host "script completed successfully without error(s)" -ForegroundColor Green
}
}
Remove-PsSnapin Microsoft.SharePoint.PowerShell
Basically I am looping through a sharepointlist with a nested loop for the CSV file and comparing values. Is this the most efficient/correct way to do this?
Here are some sample lines from the CSV:
Topic,NewTopic,Comments
Building,Appliance,
Your workplace,My Workplace