SharePoint 2010 PowerShell: Upload Files, Preserve Create and Modified Dates
Not sure why one might want to do this. Test data, maybe. Or maybe if you wanted to do a site migration the hard way and write a PowerShell script to migrate the content.
In any case, a friend of mine recently asked how one might go about uploading files to a SharePoint document library via PowerShell, while maintaining the files Created and Modified date. I don’t think he realizes that files inside of SharePoint actually have two Created/Modified dates: one for the file itself (just like it does on a file system) and a second for its metadata (like any other list item). So you actually need to add the file to the folder, then update the SPFile object’s list item.
At any rate, here’s the script to do it (using c# formatting since BEDN doesn’t have a PS formatter to my knowledge). Edit: Syntax Highlighter found powershell :)
#Add-PsSnapin Microsoft.SharePoint.Powershell <- load this so you can u se the Get-SPWeb cmdlet
$DLPath = "/Docs"; # The server relative path to the document library
$WebLocation = "http://localhost/"; # The url of the site containing the DL
$FolderPath = "C:\somefiles\"; # Local path to the folder containing files
$username = "mastdemo\administrator"; # username of the user to assign to created/modifed
start-spassignment -global # < - this is so our SPWeb's don't get disposed right away
$web = Get-SPWeb $WebLocation; # get the SPWeb object
$docLibFolder = $web.GetFolder($DLPath); # get the folder in the document library
$files = Get-ChildItem $FolderPath; # get the SPFileInfo objects from the local folder
$spuser = $web.AllUsers[$username]; # get the SPUser from the Site Collection
foreach($file in $files)
{
"Uploading "+$file.FullName;
$bytes = Get-Content -Path $file.FullName -Encoding Byte; # Get Byte[] of the file
if($bytes) #can't upload empty files
{
#using this add method: http://msdn.microsoft.com/en-us/library/ms439259.aspx
$spfile = $docLibFolder.Files.Add($file,$bytes,$spuser,$spuser,
$file.CreationTime, $file.LastWriteTime);
#synch the items created and modified date
$spfile.Item["Created"] = $file.CreationTime;
$spfile.Item["Modified"] = $file.LastWriteTime;
$spfile.Item.UpdateOverwriteVersion();
# ^ this update command is important, the
#standard Update won't let you edit Created/Modified
"Succesfully Uploaded "+$file.FullName+" to "+$WebLocation+$spfile.url;
}
else
{
$file.FullName+" is empty!"
}
}
stop-spassignment -global #<- this is so our SPWeb object gets disposed.
Comments welcome if you think I should have done something better, or differently.
If you like you can just download the ps1 file right here: