Forum Discussion

j a's avatar
j a
Copper Contributor
May 10, 2018

Declaring inplacerecords

Hi Guy's,

 

I have got hold of a script and started customizing it how i would like. The script itself runs ok after some tweaks, and now i would like to make it do something else.

The main part is supposed to iterate through all sites and subsites and their libraries and look for files that have the metdata column Colour and a value of Red. if so it copies the file/s to a local structure in ntfs that replicates the SharePoint site collection. 

However, i have added in another section whereby i am trying to identify the same files, and it checks if it is not already a record and if it is not, then declare it a record in the library...

But it keeps erroring and doesn't make sense to me. I'm still learning to script so would be great for some help or pointers to understand the issue?

 

Script and error below:

Add-PSSnapin Microsoft.SharePoint.PowerShell -erroraction "silentlycontinue"

 

$exportPath = Read-Host "Enter the export location (eg. C:\export). This directory will be created if it doesn’t exist"

$URL = Read-Host "Enter the url from SharePoint (eg. "https://***.****.net"...https://***.****.net/sites/..). This needs to be a site collection or web"

 

function downloadFiles($OutputLocation, $url){

#Create output folders

$rootFolder = createFolder ($OutputLocation + "\$URL".Split("/")[-1])

$errorFolder = createFolder ($rootFolder + "\Errors")

$InplaceFolder = createFolder ($rootFolder + "\Inplace")

#Create logging files

$loggingFile = createFile ($rootFolder + "\logging.csv")

$notDownloadedFile = createFile ($rootFolder + "\notDownloaded.csv")

$errorFile = createFile ($rootFolder + "\errors.csv")

$InplaceloggingFile = createFile ($InplaceFolder + "\Inplacelogging.csv")

$InplaceloggingFileErrors = createFile ($InplaceFolder + "\InplaceloggingErrors.csv")

#Verify that the URL is a web in SharePoint

#try{

#$web = get-spweb $url -erroraction "silentlycontinue"

#$web.dispose()

write-host "Update: Starting downloading specified web" -foregroundcolor green

 

#Start download of specified url

downloadWeb $url $rootFolder

}

#catch{

#write-host "Error: URL is not a valid web in SharePoint" -foregroundcolor red

#}

#}

 

function createFolder($folderPath){

#Create directory

#first test if the directory is not longer then 248 characters.

$count = $folderPath | measure-object -character

 

if ($count.characters -le 247){

#verify if the path exists

if (!(Test-Path -path $folderPath)){

New-Item $folderPath -type directory | Out-Null

write-host "Folder created: $($folderPath)" -foregroundcolor green

}

else{

write-host "Folder already exists, trying to create a unique folder with random number" -foregroundcolor yellow

 

#create a random to add to the folder name because it already exists

$randomNumber = Get-Random -minimum 1 -maximum 10

if ((Test-Path -path $errorFile) -eq $true){

add-content -value "Folder: $($folderPath) already exists and created a unique folder with number $($randomNumber)" -path $errorFile

}

 

$folderPath = createFolder ($folderPath + $randomNumber)

}

}

else{

#create a folder under errors to download the files to

write-host "Foldername is to long, trying to create a folder under the errors folder" -foregroundcolor yellow

if ((Test-Path -path $errorFile) -eq $true){

add-content -value "Folder: $($folderPath) is to long and documents have been moved to the error folder under $SPWeb.Title" -path $errorFile

}

 

$folderpath = $errorFolder + "\site-" + $SPWeb.Title

New-Item $folderPath -type directory | out-null

}

return $folderPath

}

 

function createFile($filePath){

#Create file

if (!(Test-Path -path $filePath)){

New-Item $filePath -type file | out-null

write-host "File created: $($filePath)" -foregroundcolor green

}

else{

#add a number to the file name if it already exists

write-host "File already exists, trying to create a unique folder with random number" -foregroundcolor yellow

$randomNumber = Get-Random -minimum 1 -maximum 100

add-content -value "File: $($filePath) already exists and created a unique file with number$($randomNumber)" -path $errorFile

$filePath = createFile ($filePath + $randomNumber)

}

return $filePath

}

 

function downloadWeb($startWeb, $rootFolder){

#Get web information with PowerShell

$SPWeb = get-spweb "$startWeb"

 

#Store the full sitefolder url in a variable and create the folder

$siteFolder = createFolder ($rootFolder + "\site_" + $SPweb.Title)

 

#Store the full url in a text file inside the folder

$SPWeb.url | out-file -filepath $siteFolder\siteURL.txt

 

#System Libraries to exclude

$systemList = @("Converted Forms","Master Page Gallery","Customized Reports","Form Templates","List Template Gallery","Theme Gallery",

                "Reporting Templates","Solution Gallery","Style Library","Web Part Gallery","Site Assets","Site Pages")

 

#Loop through all the document libraries

foreach($list in $SPweb.lists){

if(($list.BaseType -eq "DocumentLibrary") -and ($list.hidden -eq $false) -and ($systemList -notcontains $list.title)){

#Get root folder

$listUrl = $web.Url +"/"+ $list.RootFolder.Url

#Download root files

downloadLibrary $list.RootFolder.Url

#Download files in folders

foreach ($folder in $list.Folders){

downloadLibrary $folder.Url

}

}

}

 

#add logging to show which webs have been touched

add-content -value "Downloaded: $($SPWeb.url)" -path $loggingFile

 

#Loop through each subsite of the web

$SPWebs = $SPWeb.webs

foreach($SPweb in $SPwebs){

downloadWeb $SPweb.url $siteFolder

}

 

#dispose web

$SPWeb.dispose()

}

 

function downloadLibrary ($libraryURL){

#Create folder based on document library name

$SPLibrary = $SPWeb.GetFolder($libraryURL)

$libraryFolder = createFolder ($siteFolder + "\lib-" + $SPLibrary.url)

foreach ($file in $SPLibrary.Files | ?{ $_.Item["Colour"] -eq 'Red'  } )

{

            $IsRecord =[Microsoft.Office.RecordsManagement.RecordsRepository.Records]::IsRecord($file)

            $Filetype = $file.FileSystemObjectType

            if($Filetype -eq "File")

            {

                     if ($IsRecord -ne $true)

                     {

                     Write-Host "Declared for " $file.DisplayName -ForegroundColor Green

                    [Microsoft.Office.RecordsManagement.RecordsRepository.Records]::DeclareItemAsRecord($file)

                     #add logging to show which webs have been touched

                     add-content -value "Downloaded: $($File.Url)" -path $InplaceloggingFile

catch{

$ErrorMessage = $_.Exception.Message

Add-Content -Path $InplaceloggingFileErrors -Value $ErrorMessage

Write-Host $ErrorMessage

$ErrorActionPreference="Stop"

}

}

}

}

Write-Host "Downloading library: $($SPLibrary.name)" -foreground darkgreen

add-content -value "Downloading library: $($SPLibrary.name)" -path $loggingFile

 

foreach ($file in $SPLibrary.Files | ?{ $_.Item["Colour"] -eq 'Red'  } ){

#Download file

try{

$binary = $file.OpenBinary()

$stream = New-Object System.IO.FileStream($libraryFolder + "\" + $file.Name), Create

$writer = New-Object System.IO.BinaryWriter($stream)

$writer.write($binary)

$writer.Close()

}

catch{

write-host "File: $($file.Name) error" -foregroundcolor red

add-content -value "File: $($SPWeb.url) has not been downloaded" -path $notDownloadedFile

}

}

}

 

 

 

 

downloadFiles -OutputLocation $exportPath -url $url

 

 

Cannot convert argument "item", with value: "Team_Admin/Dir/xx_x_x - Laptop.msg", for "IsRecord" to type "Microsoft.SharePoint.SPListItem": "Cannot

convert the "Team_Admin/Dir/xx_x_x - Laptop.msg" value of type "Microsoft.SharePoint.SPFile" to type "Microsoft.SharePoint.SPListItem"."

At D:\Audit scripts to use\Inplace-Extraction.ps1:130 char:13

+             $IsRecord = [Microsoft.Office.RecordsManagement.RecordsRepository.Re ...

+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

    + CategoryInfo          : NotSpecified: (:) [], MethodException

    + FullyQualifiedErrorId : MethodArgumentConversionInvalidCastArgument

Cannot convert argument "item", with value: "Team_Admin/Dir/Laptops - allocation details.xlsx", for "IsRecord" to type "Microsoft.SharePoint.SPListItem": "Cannot convert the

"Team_Admin/Dir/Laptops - allocation details.xlsx" value of type "Microsoft.SharePoint.SPFile" to type "Microsoft.SharePoint.SPListItem"."

At D:\Audit scripts to use\Inplace-Extraction.ps1:130 char:13

+             $IsRecord = [Microsoft.Office.RecordsManagement.RecordsRepository.Re ...

+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

    + CategoryInfo          : NotSpecified: (:) [], MethodException

    + FullyQualifiedErrorId : MethodArgumentConversionInvalidCastArgument

  • Try to see SharePointPnPPowerShell cmdlets there some to test, declare and undeclare item as records.

     

Resources