Importing a File Share into Document Library via PowerShell

So today I was asked for a way to automate importing files from a file share into a document library.  For this, ACL's were not an issue, however using PS's Get-ACL function can get you that as well to match the insert.

Here is what I came up with as a quick and dirty response.  I though it might be nice to post for other people to use as a base script for things like synchronizing file shares with document libraries etc.

$targetLibrary = "Imported Documents"
$sourceDirectory = "\\somemachine\someshare"
$siteUrl = "http://localhost/sites/somesite"
#open the SPWeb/SPSite
$site = New-Object "Microsoft.SharePoint.SPSite" $siteUrl
$web = $site.OpenWeb()
#get all the files and directories on the share and iterate them
foreach ($file in get-childitem $sourceDirectory -recurse)
    $fileName = ($file | Select-Object Name).Name    #get the base file nname
    $parentPath = ($file | Select-Object PSParentPath) #get the path
    #eliminate everything in the path prior to the root folder
    $parentPath = $parentPath.Substring($parentPath.PSParentPath.ToLower().IndexOf($sourceDirectory.ToLower())+$sourceDirectory.Length)
    $parentPath = $parentPath.Replace("\","/")    #make the path url friendly
    $targetPath = "/$targetLibrary$parentPath/$fileName" #combine for a full url
    #check if this is a directory or file
    if (($file.GetType() | Select-Object Name).Name -eq "DirectoryInfo")
        "Adding Folder: $targetPath"
        $parentFile = ($file | Select-Object FullName).FullName #gets the full path to the file
        "Adding File: $targetPath"
        $fileBytes = [System.IO.File]::OpenRead("$parentFile") #read the file to a byte arry
#dispose of the web/site

Comments (1)

  1. Entwicklung What you need to know about AllowUnsafeUpdates (Part 1) What you need to know about AllowUnsafeUpdates

Skip to main content