We use cookies to improve your experience.
By your continued use of this site you accept such use.
For more details please see our privacy policy and cookies policy.

Script Repository

Copy folder structure with permissions

September 18, 2019 Views: 1902

The script copies all the items from the source folder to the target folder keeping the permissions.

Parameters:

  • $sourceFolder - Specifies the directory path to the source folder.
  • $targetFolder - Specifies the directory path to the target folder.
Edit Remove
PowerShell
$sourceFolder = "\\SourceServer\share\SourceFolder" # TODO: modify me
$targetFolder = "\\TargetServer\share\users\%username%" # TODO: modify me

# Get items
try
{
    $items = Get-ChildItem -Path $sourceFolder -Recurse -ErrorAction Stop
}
catch
{
    $Context.LogMessage("An error occurred while getting items to copy. Error: " + $_.Exception.Message, "Warning")
    return
}

foreach ($item in $items)
{
    # Build item path
    $itemParentPath = ($item.FullName | Split-Path).ToLower()
    $targetFolderPath = $itemParentPath.Replace($sourceFolder.ToLower(), $targetFolder.ToLower())
    
    try
    {
        # Copy item
        Copy-Item -Path $item.FullName -Destination $targetFolderPath -Force -ErrorAction Stop
    }
    catch
    {
        $Context.LogMessage("An error occurred while copying item. Error: " + $_.Exception.Message, "Warning")
        continue
    }

    try
    {
        # Update permissions
        $targetItemPath = Join-Path -Path $targetFolderPath -ChildPath $item.Name
        Get-Acl -Path $item.FullName | Set-Acl -Path $targetItemPath  -ErrorAction Stop
    }
    catch
    {
        $Context.LogMessage("An error occurred while copying permissions. Error: " + $_.Exception.Message, "Warning")
        continue
    }
}

Comments 0
Leave a comment
Loading...

Got questions?

Support Questions & Answers