02 September 2016

PowerShell: Taking Ownership of Files and Folders

Recently, I ran into a situation where a deployment required taking ownership of a specific folder and all subfolders, including files. While formulating a method of doing this, I wanted to also make sure the script not only took ownership, but also verified it happened.

With the help of Sapien's PowerShell Studio, I wrote the following function that will do just that. It will take ownership using the credentials the script is executed under. It will then query the item(s) that is takes ownership of and verify the ownership of the item matches the ownership the script is being executed under. It will then return an success/failure screen output that is color coded yellow for success and red for failure. The script can be used for either single folders or files, or using the -Recurse tells it to change ownership for all subfolders and files.

You can download the script from here.

TakeOwnership.ps1

1:  <#  
2:       .SYNOPSIS  
3:            A brief description of the TakeOwnership.ps1 file.  
4:         
5:       .DESCRIPTION  
6:            This script will grant ownership of files to the credentials this script is being executed under.  
7:         
8:       .PARAMETER FilesFolders  
9:            Files and folders to change permissions on.  
10:    
11:       .EXAMPLE  
12:            powershell.exe -executionpolicy bypass -file TakeOwnership.ps1 -FilesFolders "c:\Users\Mick\AppData\Roaming\Microsoft\Windows"  
13:         
14:       .NOTES  
15:            ===========================================================================  
16:            Created with:     SAPIEN Technologies, Inc., PowerShell Studio 2016 v5.2.127  
17:            Created on:       9/2/2016 9:49 AM  
18:            Created by:       Mick Pletcher  
19:            Organization:  
20:            Filename:         TakeOwnership.ps1  
21:            ===========================================================================  
22:  #>  
23:  [CmdletBinding()]  
24:  param  
25:  (  
26:       [ValidateNotNullOrEmpty()][string]  
27:       $FilesFolders  
28:  )  
29:    
30:  function Grant-FolderOwnership {  
31:  <#  
32:       .SYNOPSIS  
33:            Take FileFolder Ownership  
34:         
35:       .DESCRIPTION  
36:            Take ownership of the FileFolder  
37:         
38:       .PARAMETER FileFolder  
39:            File or FileFolder to take ownership of  
40:         
41:       .PARAMETER Recurse  
42:            Take ownership of all subfolders  
43:         
44:       .EXAMPLE  
45:            PS C:\> Grant-FolderOwnership -FileFolder 'Value1'  
46:         
47:       .NOTES  
48:            Additional information about the function.  
49:  #>  
50:         
51:       [CmdletBinding()]  
52:       param  
53:       (  
54:            [ValidateNotNullOrEmpty()][string]  
55:            $FileFolder,  
56:            [switch]  
57:            $Recurse  
58:       )  
59:         
60:       $Errors = $false  
61:       If ((Test-Path $FileFolder) -eq $true) {  
62:            $Output = "Taking ownership of " + $FileFolder + "....."  
63:            If ($Recurse.IsPresent) {  
64:                 #Take ownership of the top folder  
65:                 $Items = takeown.exe /F $FileFolder  
66:                 #Take ownership of all child folders and files  
67:                 $Items = Get-ChildItem $FileFolder -Recurse | ForEach-Object { takeown.exe /F $_.FullName }  
68:            } else {  
69:                 #Take ownership of the individual folder  
70:                 $Executable = takeown.exe /F $FileFolder  
71:            }  
72:       }  
73:       #Get the current user this script is being executed under  
74:       [string]$CurrentUser = [Environment]::UserDomainName + "\" + [Environment]::UserName  
75:       If ($Recurse.IsPresent) {  
76:            #Test if files are owned by the current user this script is being executed under  
77:            $Item = Get-Item $FileFolder | where-object { (get-acl $_.FullName).owner -ne $CurrentUser }  
78:            $Items = Get-ChildItem $FileFolder -Recurse | where-object { (get-acl $_.FullName).owner -ne $CurrentUser }  
79:            #If no files/folders were added to $Items, then it is a success  
80:            If ((($Item -ne "") -and ($Item -ne $null)) -and (($Items -ne "") -and ($Items -ne $null))) {  
81:                 $Output += "Failed"  
82:            } else {  
83:                 $Output += "Success"  
84:            }  
85:       } else {  
86:            [string]$FolderOwner = (get-acl $FileFolder).owner  
87:            If ($CurrentUser -ne $FolderOwner) {  
88:                 $Output += "Failed"  
89:                 $Errors = $true  
90:            } else {  
91:                 $Output += "Success"  
92:            }  
93:       }  
94:       Write-ToDisplay -Output $Output  
95:       If ($Errors -eq $true) {  
96:            #Error 5 is an arbitrary number I chose to flag if this fails  
97:            Exit 5  
98:       }  
99:  }  
100:    
101:  function Write-ToDisplay {  
102:  <#  
103:       .SYNOPSIS  
104:            Output Success/Failure to Display  
105:         
106:       .DESCRIPTION  
107:            Write the output to the Display color coded yellow for success and red for failure  
108:         
109:       .PARAMETER Output  
110:            Data to display to the screen  
111:         
112:       .EXAMPLE  
113:                      PS C:\> Write-ToDisplay -Output 'Value1'  
114:         
115:       .NOTES  
116:            Additional information about the function.  
117:  #>  
118:         
119:       [CmdletBinding()]  
120:       param  
121:       (  
122:            [ValidateNotNullOrEmpty()]$Output  
123:       )  
124:         
125:       $OutputSplit = (($Output.Replace(".", " ")).Replace("   ", ".")).Split(".")  
126:       Write-Host $OutputSplit[0]"....." -NoNewline  
127:       If ($OutputSplit[1] -like "*Success*") {  
128:            Write-Host $OutputSplit[1] -ForegroundColor Yellow  
129:       } elseif ($OutputSplit[1] -like "*Fail*") {  
130:            Write-Host $OutputSplit[1] -ForegroundColor Red  
131:       }  
132:  }  
133:    
134:  Grant-FolderOwnership -FileFolder $FilesFolders  
135:    

0 comments:

Post a Comment