1

here is my issue. I had an incident last week on my sharepoint infrastructure and a lot of files has been moved to different wrong libraries. I made an extraction from sql to find all this bad files and exported this selection to a csv. Now I'm trying to write a script in order to move this files (with their metadatas) to their correct libraries.

I've tried following this example : https://www.sharepointdiary.com/2016/03/copy-files-between-document-libraries-using-powershell-in-sharepoint.html

And did something like this :

##Script copie de fichiers d'une librairie à une autre

Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue

Start-Transcript -Path c:\temp\transcript.txt

#Variables
$WebURL="http://MySPurl"
$ListingTESTQual = Import-Csv -Path C:\temp\TestQualifMoveSP.csv -Delimiter ';' -Encoding UTF8
$SourceFileTEST = $ListingTESTQual.URLactuelle

$TargetLibrary = "TempoCourrier_MED"

 
#Get Objects
$Web = Get-SPWeb $WebURL
$SourceFileTEST = $Web.GetFile($SourceFileTEST)


#Copie Meta-Data
#$ItemPREV = $FilePREV.Item
#$ItemFSS = $FileFSS.Item

foreach($fichiers in $ListingTESTQual)

{
if ($ListingTESTQual.NomLot -match "PRE")
        {
        $FilePREV = $TargetLibrary.Files.Add($SourceFileTEST.Name, $SourceFileTEST.OpenBinary(), $true) 
        $ItemPREV = $FilePREV.item      
        $ItemPREV["Created"] = $SourceFileTEST.TimeCreated.ToLocalTime()
        $ItemPREV["Modified"] = $SourceFileTEST.TimeLastModified.ToLocalTime()
        $ItemPREV["Author"] = $SourceFileTEST.Author
        $ItemPREV["Editor"] = $SourceFileTEST.ModifiedBy
        $ItemPREV["STATUT"] = $SourceFileTEST.STATUT
        $ItemPREV["DateNumerisation"] = $SourceFileTEST.DateNumerisation
        }

else {
     if ($ListingTESTQual.NomLot -match "FSS")
        {
        $FileFSS = $TargetLibrary.Files.Add($SourceFileTEST.Name, $SourceFileTEST.OpenBinary(), $true)
        $ItemFSS = $FileFSS.Item
        $ItemFSS["Created"] = $SourceFileTEST.TimeCreated.ToLocalTime()
        $ItemFSS["Modified"] = $SourceFileTEST.TimeLastModified.ToLocalTime()
        $ItemFSS["Author"] = $SourceFileTEST.Author
        $ItemFSS["Editor"] = $SourceFileTEST.ModifiedBy
        $ItemFSS["STATUT"] = $SourceFileTEST.STATUT
        $ItemFSS["DateNumerisation"] = $SourceFileTEST.DateNumerisation
        }      
        
     }
}

 

#Update
$ItemPREV.UpdateOverwriteVersion()
$ItemFSS.UpdateOverwriteVersion()

My CSV looks like this :

NomLot;URLactuelle;NomFichier;URLdestination    
PRE_Batch1.xml;http://ActualURL1;FileName1.pdf;http://DestinationURL1
FSS_Batch2.xml;http://ActualURL2;FileName2.pdf;http://DestinationURL2

And I got this mesage as soon as I run my script :

Exception lors de l'appel de «OpenBinary» avec «0» argument(s): «Le nom de
fichier ou de dossier contient des caractères non autorisés. Utilisez un autre
nom.»
Au caractère Ligne:6 : 9
+         $FilePREV = $TargetLibrary.Files.Add($SourceFileTEST.Name, $S ...
+         ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : SPException

Impossible d’appeler une méthode dans une expression Null.
Au caractère Ligne:7 : 9
+         $ItemPREV["Created"] = $SourceFileTEST.TimeCreated.ToLocalTim ...
+         ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation : (:) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull

Seems like there is a problem with a syntax, I've tried looking for the explanation but couldn't find

Any idea?

And it's not even entering my loop which is surely wrong!!

2 Answers 2

1

In Order to copy files with meta data and version history. Here is the script to do so. If Content type of both libraries are same then this will update all the fields.

    Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue
    
    #Custom Function to Copy Files from Source Folder to Target
    Function Copy-Files($SourceFolder, $TargetFolder)
    {
        write-host "Copying Files from:$($SourceFolder.URL) to $($TargetFolder.URL)"
        #Get Each File from the Source
        $SourceFilesCollection = $SourceFolder.Files
        
        #Iterate through each item from the source
        Foreach($SourceFile in $SourceFilesCollection)
        {
            $CountFileVersions = $SourceFile.Versions.Count
            #Get the created by and created
            $CreatedBy = $SourceFile.Author;
            #Convert the "TimeCreated" property to local time
            $CreatedOn = $SourceFile.TimeCreated.ToLocalTime();
            #Loop Through Each File Version
            for ($i = 0; $i -le $CountFileVersions; $i++){
                #Initialize variables
                $SourceProp;
                $FileStream;
                $ModifiedBy;
                $ModifiedOn;
                $VersionComment = "";
                $MajorVer = $False;
                #If Index is not the Last Published Version
                if ($i -lt $CountFileVersions){
                        #Get all versions file, history, properties, createdBy, checkInComment
                        $fileSourceVer = $SourceFile.Versions[$i];
                        $SourceProp = $fileSourceVer.Properties;

                        $ModifiedBy = If ($i -eq 0) {$CreatedBy}  ELSE {$fileSourceVer.CreatedBy};
                        $ModifiedOn = $fileSourceVer.Created.ToLocalTime();
                        $VersionComment = $fileSourceVer.CheckInComment;
                        $MajorVer = If ($fileSourceVer.VersionLabel.EndsWith("0")) {$True} Else {$False}
                        $FileStream = $fileSourceVer.OpenBinaryStream();
                }
                else {
                        #Get current versions file, history, properties, createdBy, checkInComment
                        $ModifiedBy = $SourceFile.ModifiedBy;
                        $ModifiedOn = $SourceFile.TimeLastModified.ToLocalTime();
                        $SourceProp = $SourceFile.Properties;
                        $VersionComment = $SourceFile.CheckInComment;
                        $MajorVer = If ($SourceFile.MinorVersion -eq 0) {$True} Else {$False}
                        $FileStream = $SourceFile.OpenBinaryStream();
                }
                #URL library destination
                $DestFileURL = $TargetFolder.URL + "/" + $SourceFile.Name;
                #Add initial File to destination library         
                $DestFile = $TargetFolder.Files.Add($DestFileURL, $FileStream, $SourceProp, $CreatedBy, $ModifiedBy, $CreatedOn, $ModifiedOn, $VersionComment, $True);
                #Update all previous file versions
                $itmNewVersion = $DestFile.Item;
                $itmNewVersion["Author"] = $CreatedBy;
                $itmNewVersion["Editor"] = $ModifiedBy;
                $itmNewVersion["Created"] = $CreatedOn;
                $itmNewVersion["Modified"] = $ModifiedOn;
                $itmNewVersion.UpdateOverwriteVersion();
                
                #If Major Version Publish it
                if ($MajorVer){
                    $DestFile.Publish($strVerComment);
                }                 
            }
        
            Write-host "File:"$SourceFile.Name ." is uploaded successfully with version count:" $countVersions
        }
        
        #Process SubFolders
        Foreach($SubFolder in $SourceFolder.SubFolders)
        {
            if($SubFolder.Name -ne "Forms")
            {
                #Check if Sub-Folder exists in the Target Library!
                $NewTargetFolder = $TargetFolder.ParentWeb.GetFolder($SubFolder.Name)
    
                if ($NewTargetFolder.Exists -eq $false)
                {
                    #Create a Folder
                    $NewTargetFolder = $TargetFolder.SubFolders.Add($SubFolder.Name)
                }
                #Call the function recursively
                Copy-Files $SubFolder $NewTargetFolder
            }
        }
    }
    
    #Variables for Processing
    $WebURL="http://MySPurl/"
    $SourceLibrary ="SourceLibrary"
    $TargetLibrary = "DestinationLibrary"
    
    #Get Objects
    $Web = Get-SPWeb $WebURL
    $SourceFolder = $Web.GetFolder($SourceLibrary)
    $TargetFolder = $Web.GetFolder($TargetLibrary)
    
    #Call the Function to Copy All Files
    Copy-Files $SourceFolder $TargetFolder
0

Your module probably doesnt get imported up here:

Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue

Remove the Erroraction SilentlyContinue and fix this error, and dont continue to use Add-PSSnapin, as this is the old method. The new one to import a module would be

Import-Module xyz

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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