Quantcast
Channel: Windows PowerShell forum
Viewing all articles
Browse latest Browse all 21975

Sharepoint batch delete from cvs file Powershell script not working

$
0
0

Hi,

I'm trying to use a Powershell script to check if a SharePoint list contains items from a cvs file. If there is a match the script should delete the item from the SharePoint list and move on to the next row.

The code was something I found here: http://sharepointcherie.blogspot.nl/2014/01/use-powershell-to-edit-delete-and-add.html

I used the first part of the code and changed the "exists = 0" to "exists =1" and "if ($exists -eq 0)" to "if ($exists -eq 1)". This because the original code was to remove items when the item was not in the csv list. Also I changed the "if ($item.Title -eq $row.PID)" to "if ($item.<columnname> -eq $row.<columnname>)" because I have a different column I needed to compare than the Title or PID.

Unfortunately it didnt work. Can someone help me to make this work?

#specify file and check to see if it exists.  If it does, continue operations
$csvVariable= Import-CSV "\\networkpath\MyFile.csv"
if ($csvVariable) {"File exists"} else {exit}

# Check if the Sharepoint Snapin is loaded already, and load if not
if ( (Get-PSSnapin -Name Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue) -eq $null )
{Add-PSSnapin Microsoft.SharePoint.PowerShell}
$WebURL = "http://mySharePoint/sites/mysharepointsite"#site name
$listName = "MyListName" # list name
$web = Get-SPWeb -identity $WebURL #Get the SPWeb object and save it to a variable
$list = $web.Lists[$listName] #Get the SPList object to retrieve the list
$items = $list.items #Get all items in this list and save them to a variable

#loop through SharePoint list and delete items that don't appear in csv file
    foreach($item in $items)
    {
      $exists = 0
      #loop through csv and compare item to each row
      foreach ($row in $csvVariable)
      {
        if ($item.Title -eq $row.PID)
        {$exists++}
      }
      #if the item hasn't been found, delete from SharePoint list
      if ($exists -eq 0)
      {$list.GetItemById($item.ID).Delete()}
    }


Viewing all articles
Browse latest Browse all 21975

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>