Copying filesystem permissions for long paths using AlphaFS nad Powershell

AlphaFS is my go-to library when working with Long Paths, since PowerShell’s built in functions do not support long paths and error out.

As I couldn’t find good PowerShell examples using GetAccessControl and SetAccessControl with the AlphaFS library, I wanted to post my script here for those googling an example 🙂

Param(
    [String]$sourcePath,
    [String]$targetPath
)

[System.Reflection.Assembly]::UnsafeLoadFrom('https://gitlab.com/Lieben/assortedFunctions/-/raw/master/lib/AlphaFS.dll?inline=false')

$sourcePath = [Alphaleonis.Win32.Filesystem.Path]::GetLongPath($sourcePath)
$targetPath = [Alphaleonis.Win32.Filesystem.Path]::GetLongPath($targetPath)

if([Alphaleonis.Win32.Filesystem.Directory]::Exists($sourcePath)){
    Write-Verbose "Detected sourcePath as FOLDER"
    $sourceObject = New-Object Alphaleonis.Win32.Filesystem.DirectoryInfo($sourcePath)
}elseif([Alphaleonis.Win32.Filesystem.File]::Exists($sourcePath)){
    Write-Verbose "Detected sourcePath as FILE"
    $sourceObject = New-Object Alphaleonis.Win32.Filesystem.FileInfo($sourcePath)
}else{
    Throw "sourcePath not found"
}

if([Alphaleonis.Win32.Filesystem.Directory]::Exists($targetPath)){
    Write-Verbose "Detected targetPath as FOLDER"   
    $targetObject = New-Object Alphaleonis.Win32.Filesystem.DirectoryInfo($targetPath)
}elseif([Alphaleonis.Win32.Filesystem.File]::Exists($targetPath)){
    Write-Verbose "Detected targetPath as FILE"
    $targetObject = New-Object Alphaleonis.Win32.Filesystem.FileInfo($targetPath)
}else{
    Throw "targetPath not found"
}

$sourceACL = $sourceObject.GetAccessControl("Access")
$targetObject.SetAccessControl($sourceACL)

Git: https://gitlab.com/Lieben/assortedFunctions/-/blob/master/copy-longPathACL.ps1

Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments