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: 3258

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 2
avatar
Mr.Vico Apr 13, 2023
Hi!
Unfortunately this script copies files also, you need to use -Directory parameter after $items = Get-ChildItem -Path $sourceFolder. And it only copies 1 level subfolders not subfolders in subfolders... how would you solve it? I want to be able to copy all subfolders in all levels not only the first level subfolders. Would appreciate if you could solve it.
avatar
Support Apr 13, 2023
Hello,

As per Microsoft documentation, adding the -Directory parameter to the Get-ChildItem should do exactly what you need. However, it seems that there are some issues with the cmdlets used in the script. They sometimes work exactly as expected and sometimes not copying certain folders. The issue is not related to Adaxes at all. If you need assistance with making the script work properly, we recommend you to contact Microsoft support.
Leave a comment
Loading...

Got questions?

Support Questions & Answers