Using PowerShell to export SharePoint list items into CSV and then delete the same items from the list

The below code can be used to export list items, if found, info column by column. It then deletes the items that it exported from the list.

if ((Get-PSSnapin “Microsoft.SharePoint.PowerShell” -ErrorAction SilentlyContinue) -eq $null) {
    Add-PSSnapin “Microsoft.SharePoint.PowerShell”
}

# BEGIN CONFIG

$fileNameStamp = Get-Date -UFormat “%Y_%m_%d_%H_%M”
$fileAndPath =”D:\DATA\myData-$fileNameStamp.csv”
$web = Get-SPWeb -identity “http://10.1.1.10/”
$list = $web.Lists[“MyList”]

# END CONFIG
# BEGIN: STEP 1: Export current items in the list to CSV
$listitems = $list.Items.Count;
# Break out if the list has no content. Stops the creation of empty files.
if ($listitems -lt 1) {
    break;
} else {
    #Array to Hold Result – PSObjects
    $ListItemCollection = @()
    #Get All List items”
    $list.Items | foreach {
       $ExportItem = New-Object PSObject
       $ExportItem | Add-Member -MemberType NoteProperty -name “ID” -value $_[“ID”]
       $ExportItem | Add-Member -MemberType NoteProperty -name “Title” -value $_[“Title”]
       $ExportItem | Add-Member -MemberType NoteProperty -name “Created” -value $_[“Created”]
       $ExportItem | Add-Member -MemberType NoteProperty -name “CreatedBy” -value $_[“Created By”]
       #Add the object with property to an Array
       $ListItemCollection += $ExportItem
    }
    #Export the result Array to CSV file
    $ListItemCollection | Export-CSV $fileAndPath -NoTypeInformation
}
# END: STEP 1: Export current items in the list to CSV

# BEGIN: STEP 2: Delete the exported items from the list
Import-CSV $fileAndPath -Header ID,Title | Foreach-Object{
    Write-Host ” Looking for item #” $_.ID “…”;

    $items = $list.Items | Where {$_[“ID”] -eq $_.ID}
    foreach($item in $items)
    {
        $item.Delete();
        break;
    }
}
# END: STEP 2: Delete the exported items from the list

#BEGIN: CLEANUP
$web.Dispose();
#END: CLEANUP