Site Loader

Hello,

Did you ever had the issue get-childitem : The specified path, file name, or both are too long when you are changing the acl of some files?

I just had… Some users are putting the whole life in name of the file! WHY???!!!!

Normally you whould think you can fix this with get-childitem like this:

# In this eample I try to set the owner for all copied folders and files
$owner = New-Object System.Security.Principal.NTAccount($upn)
$folders = get-childitem $Userfolders -Recurse -Force #also includes files
foreach ($folder in $Folders){
    $acl = get-acl -LiteralPath $folder.fullname
    $acl.setowner($owner)
    set-acl -LiteralPath $folder.fullname $acl
}

In the end you will receive the message: get-childitem : The specified path, file name, or both are too long.
You cannot fix this with a New-PSDrive because $folder.fullname overrules the path of the psdrive!

After some testing and searching I found the solution!

$owner = New-Object System.Security.Principal.NTAccount($upn)
[string[]]$folders = [System.IO.Directory]::GetDirectories($Userfolders)
#sets the owner foreach folder
foreach ($folder in $folders) {
    $acl = get-acl -LiteralPath $folder
    $acl.setowner($owner)
    set-acl -LiteralPath $folder $acl
    [string[]]$files = [System.IO.Directory]::GetFiles($folder, "*.*", [System.IO.SearchOption]::AllDirectories)
    #sets the owner foreach file in that folder
    foreach ($file in $files) {
        if($file.Length -lt '254'){
            $acl = get-acl -LiteralPath $file
            $acl.setowner($owner)
            set-acl -LiteralPath $file $acl
           } else {
            #I want to know what files are too long!
            $file | out-file $char256prob -Append
        } #end if file
    } #end foreach file
} #end foreach folder

I hope this will help you setting the acl of your files and folders in PowerShell.

Sander

https://cubik.com.tw/ click to find out more