As Technet Gallery is retiring so moving the code to Git Hub. (click below link, creating first link to my blog for those who are unfamiliar with github)

 

 Take Ownership and Grant Permissions

 

 

 

Sharing a advanced script that I have used for one of our projects, This script is compatible with Powershell Version 2.0 & 3.0

There was a requirement from Backup Team that 

Let me demonstrate the script with an example:

Create a Share folder Name Root:

Create Subfolders inside it

Now I will remove ownership & permissions randomly from the folders /sub folders/files inside these folders

After removing file ownership & permissions for backup account below will be the results for files:

After removing folder ownership & permissions for bakup account below will be the results for folders:

Now edit the TakeOwnAddpermv1.ps1 powershell Script

$RootPath1 = "\\labfileserver\root"

$domain = "domain"



Now run the batch file: Takeownperm.bat, It will ask you for the account that, script should grant ownership/access.(just enter samaccountname)

Script will generate the logs inside the logs folders:

 

After execution you will be able to succesfully access the folder you have set as No acces/removed ownership.

Download the zip file from above/extract it & follow the steps as mentioned above.

 

 

 

PowerShell
Edit|Remove
############################################################################### 
#            Author: Vikas Sukhija 
#            Reviewer: Vikas Sukhija 
#            Date: 11/18/2015 
#            Review: 11/19/2015 
#            Modified: 11/19/2015 -- Add comments / Changed variables 
#            Modified: 11/19/2015 -- Add Recursion via Function 
#            Description: Change Owbnersjhip & Grant permissions  
#            if Pemissions are not present         
############################################################################### 
###############################Define Variables/Logs########################### 
 
$RootPath1 = "\\labfsserver\root"  
 
$User = Read-Host "Input the sAMAccountName of user :" ##A 
 
$domain = "domain" 
 
if(Test-path .\error.txt){Remove-Item .\error.txt -Force} 
 
#######################For Log Files######################## 
$date = get-date -format d  
$date = $date.ToString().Replace(“/”, “-”)  
$time = get-date -format t  
$time = $time.ToString().Replace(":""-")  
$time = $time.ToString().Replace(" """)  
$logs = ".\Logs" + "\" + "FolderACL" + $date + "_" + $time + "_.txt" 
$ErrorFile = ".\Logs" + "\" + "ErrorFile" + $date + "_" + $time + "_.txt" 
$NewOwnerFile = ".\Logs" + "\" + "NewOwner" + $date + "_" + $time + "_.txt" 
$ErrorFolders = ".\Logs" + "\" + "ErrorFolders" + $date + "_" + $time + "_.txt" 
 
##############################Takeownership function##################### 
 
function Take-Ownership { 
 param( 
  [String]$Folder 
 ) 
 takeown.exe //$Folder 
 $CurrentACL = Get-Acl $Folder 
 #write-host ...Adding NT Authority\SYSTEM to $Folder -Fore Green 
  $valtype = (Get-Item $Folder-is [System.IO.DirectoryInfo] 
 if($valtype -like $true){ 
 #$SystemACLPermission = "NT AUTHORITY\SYSTEM","FullControl","ContainerInherit,ObjectInherit","None","Allow" 
 $AdminACLPermission = "$domain\$user","FullControl","ContainerInherit,ObjectInherit","None","Allow"} 
 else{ 
 #$SystemACLPermission = "NT AUTHORITY\SYSTEM","FullControl","Allow" 
 $AdminACLPermission = "$domain\$user","FullControl","Allow"} 
  
 #$SystemAccessRule = new-object System.Security.AccessControl.FileSystemAccessRule $SystemACLPermission 
 #$CurrentACL.AddAccessRule($SystemAccessRule) 
 write-host ...Adding User account to $Folder -Fore Green 
  
 $SystemAccessRule = new-object System.Security.AccessControl.FileSystemAccessRule $AdminACLPermission 
 $CurrentACL.AddAccessRule($SystemAccessRule) 
  
 Set-Acl -Path $Folder -AclObject $CurrentACL 
} 
 
########################################################################## 
 
Start-Transcript -Path $logs 
 
######################Traverse to the Child items Recursively############ 
 
Function ChangeOwnRecursively ($Rootpath){ 
$Error.Clear() 
$shares = $null 
$shares = @() 
$Folders = get-childitem $Rootpath -Recurse -ea silentlycontinue 
$countPf = $Error -match "The specified network name is no longer available" 
$countpf3 = $Error -match "Access to the path (.*) is denied." 
$count1 = $countPf.count 
$count2 = $countpf3.count 
$count = $count1 + $count2 
 
Write-host "Problematic folder count during recursion of $Rootpath $count" -foregroundcolor yellow 
 
if($error -ne $null){ 
$Error | out-file .\error.txt 
 
$getshptherror1 = Select-String -Pattern "ReadError:"  -Path .\error.txt 
$getshptherror2 = Select-String -Pattern "PermissionDenied:"  -Path .\error.txt 
 
if($getshptherror1 -ne $null){ 
 
$getshptherror1 | ForEach-Object{ 
 
$getshare1 = $_ -split ":"  
$share1=$getshare1[5] 
$share2 = ($share1.replace("(","")).trim() 
$shares+$share2 
} }  
 
if($getshptherror2 -ne $null){ 
$getshptherror2 | ForEach-Object{ 
$getshare2 = $_ -split ":"  
$share3=$getshare2[5] 
$share4 = ($share3.replace("(","")).trim() 
$shares+$share4 
} }} 
 
if($error -ne $null){Add-Content $ErrorFolders "$shares" 
$shares} 
 
 
if(Test-path .\error.txt){Remove-Item .\error.txt -Force} 
 
$Error.Clear() 
if($Folders.count -gt "0"){ 
    Foreach($Folder in $Folders) 
    { 
    $Folder  
    $permission = get-acl $Folder.FullName -ErrorAction SilentlyContinue 
        $citem1get-childitem $Folder.FullName -ErrorAction SilentlyContinue 
        if($error -ne $null) { 
        $citerror1 = $Error -match "The specified network name is no longer available" 
    $citerror2 = $Error -match "Attempted to perform an unauthorized operation" 
        Write-host "Folder/file $folder can't be browsed" -foregroundcolor yellow} 
#####################If Permissions found######################### 
    
 
    if(($permission-and ($citerror1 -eq $null-and ($citerror2 -eq $null)) 
    { 
    Write-Host "User $user has rights on $folder" -foregroundcolor green 
    } 
    Else  
    { 
 
    Write-Host "$User doesn't have any permission on $Folder" -foregroundcolor Magenta 
 
    $FolderPath = $Folder.FullName 
    $FolderPath 
 
    $error.clear() 
    Take-Ownership ($FolderPath) 
 
    if($error -ne $null) 
    { 
    Write-host "Take ownership /access operation failed" -foregroundcolor Yellow 
 
    Add-Content $ErrorFile "Complete path : $FolderPath : Take ownership /access operation failed for $user" 
 
    } 
    else 
    { 
    $Acl = get-acl $Folder.FullName 
    $UserAccess = New-Object System.Security.Principal.NTAccount("$domain""$User") 
    $ACL.SetOwner($UserAccess) 
    Set-Acl -Path $Folder.FullName -AclObject $Acl 
    Add-Content $NewOwnerFile "Complete path : $FolderPath New Owner is $User " 
    Write-host "$FolderPath New Owner is $User" -foregroundcolor Green 
    } 
     
   } 
$error.clear() 
$permission = $null 
$citem1 = $null 
$citerror1 = $null 
$citerror2 = $null 
 
  }} 
if($shares -ne $null){ 
$shares | ForEach-Object { 
ChangeOwnRecursively  $_ }} 
 
} 
 
ChangeOwnRecursively $RootPath1 
Stop-Transcript 
 
##################################################################
 

 

 Regards

 

 Sukhija Vikas

 

 

 http://msexchange.me