Monday, September 8, 2014

Read List items and write them into a csv file via PowerShell


I wrote a PowerShell script which can read list items whose status is false in the ‘site created’ column of my list and later write them into a csv file. The following is the PowerShell script I wrote to achieve this task.


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

    $spweb_name = "https://test/sites/4511";
    $list_name = "Site Collection Request list";
    $path_csv_write = "C:\Users\malik\Desktop\PSScripts\ExportCsv\";

    $web = Get-SPWeb $spweb_name;
    $list = (Get-SPWeb $spweb_name).Lists.TryGetList($list_name);
    $items = $list.Items;

    $exportlist = @()

    $filtereditems = $list.Items | Where-Object{[System.Convert]::ToBoolean($_["Site created"]) -eq $False}
    Write-Host "Number of items found: " $filtereditems.Count;  

    foreach($item in $filtereditems){        
           
        $ps_obj = New-Object PSObject -Property @{
                   “ID” = $item["ID"]
                   “Site Title” = $item["Site Title"]
                   "Url Team Site" = $item["URL Team Site"]
                   "Site Owner" = $item["Site Owner"]
                   
                    
        }
    $exportlist += $ps_obj 
    }

    $expath = $path_csv_write + $list_name + ' - Export.csv' 

    if(Test-Path $expath)
    {
        Remove-Item $expath
    }

    if($exportlist.length -gt 0){
             
        $exportlist | Export-Csv -path $expath
        Write-Host "New requests for Team Sites are exported to a a csv file at : " + $expath;
    }
    $web.Dispose();
I hope this will help some one.

No comments:

Post a Comment