[SPS] Dump user membership and upload results to document library

Script’s purpose:

* Cycles through every SharePoint Site/Web and lists the users and their group memberships. The final results are written in the folder c:\reports\AllFarmUsers<date>.csv

* Get the last report file from the C:\reports\ folder, compresses it using 7-ZIP and puts the ZIP file in the folder c:\reports-ZIP\AllFarmUsers<date>.zip

* Gathers the last zip file from the c:\reports-ZIP\ folder and puts it in SharePoint document library (webapp and document library are hardcoded)

The document library where the script results are put is: http://intranet.pbnet.local/NOC/Shared%20Documents

 

Software requirements: 

The scripts make use of the following components:

* Windows PowerShell

* SharePoint 2010 Management Shell (also known as Microsoft.SharePoint.Powershell)

* 7-ZIP

The folders c:\reports and c:\reports-zip have to exist prior to running the scripts.

Also, the document library where the final zip has to be uploaded needs to exits.

 

and now the script itself:

 

# CopyRight 2014 Andrei Rachita
#getalluserseverywhere
Add-PSSnapin microsoft.sharepoint.powershell -ErrorAction SilentlyContinue
clear
$timestamp = get-date -format “yyyyMMdd_hhmmtt”
$filenameStart = “AllFARMUsers”
#$logfile = (“{0}{1}.csv” -f $filenamestart, $timestamp)
#Note that the c:\reports folder has to be present on the drive
cd c:\reports\
$logfile = (“{0}{1}.csv” -f $filenamestart, $timestamp)

$header = “type,user,group,weburl,webname”
$header | out-file -FilePath $logfile

$iissitelist = get-spwebapplication
foreach($onesite in $iissitelist)
{

foreach ($SiteCollection in $onesite.sites)
{
write-host $SiteCollection -foregroundcolor black
foreach ($web in $SiteCollection.Allwebs)
{
write-host ” ” $web.url $web.name “users:” -foregroundcolor black
# Write-host ” ” $web.users | select name
foreach ($userw in $web.users)
{
#if ($userw -like “domain\*”)
#{
write-host ” ” $userw -foregroundcolor black
#$msg = (“{0},{1} user:{2}” -f $web.url,$web.name, $userw)
$msg = (“RootUser,{0},-,{1},{2}” -f $userw, $web.url,$web.name)
$msg | out-file -FilePath $logfile -append
# }
}

foreach ($group in $web.Groups)
{
Write-host ” ” $web.url $group.name: -foregroundcolor black
foreach ($user in $group.users)
{
# if ($user -like “Domain\*”)
#{
Write-host ” ” $user -foregroundcolor black
#$msg = (“{0},{1},group:{2}, user:{3}” -f $web.url, $web.name, $group, $user)
$msg = (“GroupUser,{0},{1},{2},{3}” -f $user, $group, $web.url, $web.name)
$msg | out-file -FilePath $logfile -append
#}
}
}
$web.Dispose()
}

}
}

# Since CSV File is larger than 20MB, we need to zip the file
# Note that 7-ZIP http://downloads.sourceforge.net/sevenzip/7z920-x64.msi needs to be installed on the server

function create-7zip([String] $aDirectory, [String] $aZipfile){
[string]$pathToZipExe = “C:\Program Files\7-zip\7z.exe”;
[Array]$arguments = “a”, “-tzip”, “$aZipfile”, “$aDirectory”, “-r”;
& $pathToZipExe $arguments;
}

#get latest file from reports and zip it
$dir=”c:\reports\”
$latest = Get-ChildItem -Path $dir | Sort-Object LastAccessTime -Descending | Select-Object -First 1
$latest.name
$path=”c:\reports\”+$latest.Name
$path
$string=$latest.Name
$string2=$string -replace “.csv”
$string2
create-7zip $path C:\Reports-ZIP\$string2.zip
#put ZIP file in C:\Reports-ZIP (folder needs to exist on the drive)
$dirsend=”C:\Reports-ZIP”
$latestzip=Get-ChildItem -Path $dirsend | Sort-Object LastAccessTime -Descending | Select-Object -First 1
$latestzip.name
$sendpath=”C:\Reports-ZIP\”+$latestzip.name

#Uploading last reports to pre-defined doclib on a site collection

function UploadFileInLibrary
{
[CmdletBinding()]
Param(
[Parameter(Mandatory=$true,ValueFromPipeline=$true)]
[string]$webUrl,
[Parameter(Mandatory=$true)]
[string]$DocLibName,
[Parameter(Mandatory=$true)]
[string]$FilePath
)

Start-SPAssignment -Global
$spWeb = Get-SPWeb -Identity $webUrl
$spWeb.AllowUnsafeUpdates = $true;
$List = $spWeb.Lists[$DocLibName]
$folder = $List.RootFolder
$FileName = $FilePath.Substring($FilePath.LastIndexOf(“\”)+1)
$File= Get-ChildItem $FilePath
[Microsoft.SharePoint.SPFile]$spFile = $spWeb.GetFile(“/” + $folder.Url + “/” + $File.Name)
$flagConfirm = ‘y’
if($spFile.Exists -eq $true)
{
$flagConfirm = Read-Host “File $FileName already exists in library $DocLibName, do you want to upload a new version(y/n)?”
}

if ($flagConfirm -eq ‘y’ -or $flagConfirm -eq ‘Y’)
{
$fileStream = ([System.IO.FileInfo] (Get-Item $File.FullName)).OpenRead()
#Add file
write-host -NoNewLine -f Blue “Copying file ” $File.Name ” to ” $folder.ServerRelativeUrl “…”
[Microsoft.SharePoint.SPFile]$spFile = $folder.Files.Add($folder.Url + “/” + $File.Name, [System.IO.Stream]$fileStream, $true)
write-host -f Green “…Success!”
#Close file stream
$fileStream.Close()
write-host -NoNewLine -f Blue “Update file properties ” $spFile.Name “…”
$spFile.Item[“Title”] = “Site Owners List”
$spFile.Item.Update()
write-host -f Green “…Success!”
}
$spWeb.AllowUnsafeUpdates = $false;

Stop-SPAssignment -Global
}
function create-7zip([String] $aDirectory, [String] $aZipfile){
[string]$pathToZipExe = “C:\Program Files\7-zip\7z.exe”;
[Array]$arguments = “a”, “-tzip”, “$aZipfile”, “$aDirectory”, “-r”;
& $pathToZipExe $arguments;
}
$dirsend=”C:\Reports-ZIP”
$latestzip=Get-ChildItem -Path $dirsend | Sort-Object LastAccessTime -Descending | Select-Object -First 1
$latestzip.name
$sendpath=”C:\Reports-ZIP\”+$latestzip.name

#hardcoded Webapp and Documet library follows
$webUrl = “http://intranet.pbnet.local/NOC/”
$DocLibName = “Shared Documents”
$filePath = $sendpath
UploadFileInLibrary $webUrl $DocLibName $filePath

#Waiting for 10 seconds

Start-Sleep -s 10
#Deleting stored logfiles from server
#Deleting original CSV
if (Test-Path $latest) {
Remove-Item $latest
}
#Deleting ZIPed report
if (Test-Path $sendpath) {
Remove-Item $sendpath
}