0

This is a two part question I suppose. I have code as follows :

Try{
    Add-Type -Path 'C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\15\ISAPI\Microsoft.SharePoint.Client.dll'
    Add-Type -Path 'C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\15\ISAPI\Microsoft.SharePoint.Client.Runtime.dll'
    Add-Type -Path 'C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\15\ISAPI\Microsoft.SharePoint.Client.Publishing.dll'
    Add-Type -Path 'C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\15\ISAPI\Microsoft.SharePoint.Client.Taxonomy.dll'
}

catch {
    Throw "Unable to load SharePoint Client runtime"
}

Function DryRun-UploadFile($DestinationFolder, $File, $FileSource)
{


    if($FileSource -eq $null){
        $FileSource = $Folder
    }
    $path= [String]$FileSource+'\'+$File
    $Size = get-item $Path
    $Size = $Size.length

    if($Size -lt 160000){
        if($path -like '*.doc*' -Or $path -like '*.xls*' -Or $path -like '*.ppt*'){
        ##Get authors of document
            if($path -like '*.doc*'){
                $application = New-Object -ComObject word.application
                $application.Visible = $false
                $document = $application.documents.open($path)
            }
            if($path -like '*.xls*'){
                $application = New-Object -ComObject Excel.application
                $application.Visible = $false
                $document = $application.workbooks.open($path)
            }   
            if($path -like '*.ppt*'){
                $application = New-Object -ComObject powerpoint.application
                $application.Visible = [Microsoft.Office.Core.MsoTriState]::msoTrue
                $document = $application.presentations.open($path)
            }   


            $binding = "System.Reflection.BindingFlags" -as [type]
            $properties = $document.BuiltInDocumentProperties
            foreach($property in $properties)
            {
                $pn = [System.__ComObject].invokemember("name",$binding::GetProperty,$null,$property,$null)

                trap [system.exception]
                {

                    continue
                }
                if ($pn -eq "Last author") {
                    $lastSaved = [System.__ComObject].invokemember("value",$binding::GetProperty,$null,$property,$null)
                    $lastSaved = [String]$lastSaved

                }
                if ($pn -eq "author") {
                    $author = [System.__ComObject].invokemember("value",$binding::GetProperty,$null,$property,$null)
                    $author = [String]$author
                }

    }

    $document.Close()
    $application.quit()
    if($path -like '*.ppt*'){
        $application = $null
        [gc]::collect()
        [gc]::WaitForPendingFinalizers()
        Stop-Process –name powerpnt 
    }
    ##set author if null returned
    if($lastSaved -eq ''){
        $lastSaved = "Rob Ireland"
    }
    if($author -eq ''){
        $author = "Rob Ireland"
    }

    $author =$Context.Web.EnsureUser($author)
    $lastSaved = $Context.Web.EnsureUser($lastSaved)
    }else{

        $CreationOwner =Get-Acl $path | Select-Object Owner
        #$lastSaved = "Rob Ireland"
        #$author = "Rob Ireland"

    }
    ##Get created date
    $CreationDate = Get-ItemProperty -Path $FileSource\$File | Select-Object CreationTime
    $CreateDT =  [string]$CreationDate.CreationTime
    $revDate,$Time = $CreateDT.Split(" ",2)
    $arr = $revDate -split '/'
    $revDate = $arr[2]+'-'+$arr[0]+'-'+$arr[1]
    $DateSP = $revDate+'T'+$Time

    ##Get Modified date
    $ModifiedDate = Get-ItemProperty -Path $FileSource\$File | Select-Object LastWriteTime
    $ModDT =  [string]$ModifiedDate.LastWriteTime
    $ModDate,$ModTime = $ModDT.Split(" ",2)
    $Modarr = $ModDate -split '/'   
    $ModDate = $Modarr[2]+'-'+$Modarr[0]+'-'+$Modarr[1] 
    $ModDateSP = $ModDate+'T'+$ModTime


    $FileStream = New-Object IO.FileStream($File.FullName,[System.IO.FileMode]::Open)
    $FileCreationInfo = New-Object Microsoft.SharePoint.Client.FileCreationInformation
    $FileCreationInfo.Overwrite = $true
    $FileCreationInfo.ContentStream = $FileStream
    $FileCreationInfo.URL = $File
    $Upload = $DestinationFolder.Files.Add($FileCreationInfo)
    $Context.Load($Upload)
    $Context.ExecuteQuery()

    $ListItem = $Upload.ListItemAllFields;

    $Listitem["Modified"] = $ModDateSP

    $Listitem["Created"] = $DateSP
    $Listitem["Author"] = $author  
    $Listitem["Editor"] = $lastSaved  

    $ListItem.Update()
    $Context.Load($Upload)
    $Context.ExecuteQuery()
    }else{
    $global:Count=$global:Count+1

    }
}

function DryRun-PopulateFolder($ListRootFolder, $FolderRelativePath, $Count)
{
    #split the FolderRelativePath passed into chunks (between the backslashes) so that we can check if the folder structure exists
    $PathChunks = $FolderRelativePath.substring(1).split("\")

    #Make sure we start with a fresh WorkingFolder for every folder passed to the function
    if($WorkingFolder)
    {
        Remove-Variable WorkingFolder
    }

    #Start with the root folder of the list, load this into context
    $WorkingFolder = $ListRootFolder
    $Context.load($WorkingFolder)
    $Context.ExecuteQuery()

    #Load the folders of the current working folder into context
    $Context.load(($WorkingFolder.folders))
    $Context.executeQuery()

    #Set the FileSource folder equal to the absolute path of the folder that passed to the function
    $FileSource = $Folder + $FolderRelativePath

    #Loop through the folder chunks, ensuring that the correct folder hierarchy exists in the destination
    foreach($Chunk in $PathChunks)
    {
        #Check to find out if a subfolder exists in the current folder that matches the patch chunk being evaluated
        if($WorkingFolder.folders | ? {$_.name -eq $Chunk})
        {
            #Log the status to the PowerShell host window


            #Since we will be evaluating other chunks in the path, set the working folder to the current folder and load this into context.
            $WorkingFolder = $WorkingFolder.folders | ? {$_.name -eq $Chunk}
            $Context.load($WorkingFolder)
            $Context.load($WorkingFolder.folders)
            $Context.ExecuteQuery()

        }
        else
        {
            #If the folder doesn't exist, Log a message indicating that the folder doesn't exist, and another message indicating that it is being created


            #Load the working folder into context and create a subfolder with a name equal to the chunk being evaluated, and load this into context
            $Context.load($WorkingFolder)
            $Context.load($WorkingFolder.folders)
            $Context.ExecuteQuery()
            $WorkingFolder= $WorkingFolder.folders.add($Chunk)
            $Context.load($WorkingFolder)
            $Context.load($WorkingFolder.folders)
            $Context.ExecuteQuery()


        }

    }

    #Folder is confirmed existing or created - now it's time to list all files in the source folder, and assign this to a variable
    $FilesInFolder = Get-ChildItem -Path $FileSource | ? {$_.psIsContainer -eq $False}

    #For each file in the source folder being evaluated, call the UploadFile function to upload the file to the appropriate location
    Foreach ($File in ($FilesInFolder))
    {

        #Notify the operator that the file is being uploaed to a specific location

        if(!($File -like '*.txt')){

        #Upload the file
        DryRun-UploadFile $WorkingFolder $File $FileSource 
        }else{
            $global:Count=$global:Count+1

        }

    }



}


Function DryRun-Copy-Files{

    [CmdletBinding()] 
    param(
        [Parameter(Mandatory=$true)][string]$User,
        [Parameter(Mandatory=$true)][string]$SiteURL,
        [Parameter(Mandatory=$true)][string]$Folder,
        [Parameter(Mandatory=$true)][string]$DocLibName,
        [Parameter(Mandatory=$false)][System.Net.NetworkCredential]$credentials,


    )





    try{
        #Bind to site collection
        $Context = New-Object Microsoft.SharePoint.Client.ClientContext($SiteURL)

    }catch{                          
                Write-Host $_.Exception.Message
                Write-Host "No further parts of the migration will be completed, The script will now exit" 
                Exit
        }
                $pass =  ConvertTo-SecureString $credentials.Password -AsPlainText -Force
                $Creds = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($credentials.UserName,$pass)
        $Context.Credentials = $Creds
    #Retrieve list
    $List = $Context.Web.Lists.GetByTitle($DocLibName)
    $Context.Load($List)
    $Context.ExecuteQuery()

    #Get a recursive list of all folders beneath the folder supplied by the operator
    $AllFolders = Get-ChildItem -Recurse -Path $Folder |? {$_.psIsContainer -eq $True}

    #Get a list of all files that exist directly at the root of the folder supplied by the operator
    $FilesInRoot = Get-ChildItem -Path $Folder | ? {$_.psIsContainer -eq $False}

    #Upload all files in the root of the folder supplied by the operator
    Foreach ($File in ($FilesInRoot))
    {


        if(!($File -like '*.txt')){
        #Upload the file
        DryRun-UploadFile($list.RootFolder) $File
        }else{
             $global:Count=$global:Count+1

        }



    }

    #Loop through all folders (recursive) that exist within the folder supplied by the operator
    foreach($CurrentFolder in $AllFolders)
    {
        #Set the FolderRelativePath by removing the path of the folder supplied by the operator from the fullname of the folder
        $FolderRelativePath = ($CurrentFolder.FullName).Substring($Folder.Length)

        #Call the PopulateFolder function for the current folder, which will ensure that the folder exists and upload all files in the folder to the appropriate location
        DryRun-PopulateFolder ($list.RootFolder) $FolderRelativePath



    }

Write-output "Number of files excluded is: "$global:Count | Out-file DryRun.txt 




}

This file uploads a file structure to sharepoint online. this works fine I just want to add to it. Firstly is there anyway to check the performance of the upload so check how many MB/S the files are being uploaded by. Secondly How can I turn this into a dry/practice run so it doesn't actually do the upload?

0

You already have the file size so time your upload using Measure-Command or [Diagnostics.StopWatch]. You can do the math from there.

PowerShell advanced cmdlets enable you to use the -WhatIf param. You will need to add [cmdletBinding(SupportsShouldProcess=$true)] immediately below your function. You can then wrap actions in an if like this:

if ($pscmdlet.ShouldProcess($foo)) {
    Get-Item $foo
}

To perform a dry run just execute the function with the -whatIf param. Alternatively you can maintain another script and just Write-Host your executions. I'd advise investing the time with advanced functions though.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.