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.
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
}
}