Last active
August 18, 2023 16:40
-
-
Save Citillara/43a70ec781b101db1a3aaf1a7a7d68b9 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$source = @" | |
using System; | |
using System.IO; | |
using System.Security.AccessControl; | |
using System.Security.Principal; | |
public class Program | |
{ | |
public static void Main() | |
{ | |
WindowsIdentity currentIdentity = WindowsIdentity.GetCurrent(); | |
NTAccount account = (NTAccount)currentIdentity.User.Translate(typeof(NTAccount)); | |
ProcessDirectory(new DirectoryInfo(Environment.CurrentDirectory), account); | |
} | |
public static void ProcessDirectory(DirectoryInfo di, NTAccount newOwner) | |
{ | |
foreach(DirectoryInfo dir in di.GetDirectories()) | |
{ | |
if ((dir.Attributes & FileAttributes.ReparsePoint) != FileAttributes.ReparsePoint && | |
(dir.Attributes & FileAttributes.System) != FileAttributes.System) | |
{ | |
ChangeDirectoryOwner(dir.FullName, newOwner); | |
ProcessDirectory(dir, newOwner); | |
} | |
} | |
foreach(FileInfo file in di.GetFiles()) | |
{ | |
if ((file.Attributes & FileAttributes.ReparsePoint) != FileAttributes.ReparsePoint && | |
(file.Attributes & FileAttributes.System) != FileAttributes.System) | |
{ | |
ChangeFileOwner(file.FullName, newOwner); | |
} | |
} | |
} | |
public static void ChangeFileOwner(string filePath, NTAccount newOwner) | |
{ | |
FileSecurity fileSecurity = File.GetAccessControl(filePath); | |
fileSecurity.SetOwner(newOwner); | |
File.SetAccessControl(filePath, fileSecurity); | |
} | |
public static void ChangeDirectoryOwner(string directoryPath, NTAccount newOwner) | |
{ | |
DirectorySecurity directorySecurity = Directory.GetAccessControl(directoryPath); | |
directorySecurity.SetOwner(newOwner); | |
Directory.SetAccessControl(directoryPath, directorySecurity); | |
} | |
} | |
"@ | |
# Add the C# type | |
Add-Type -TypeDefinition $source | |
# Call the static method | |
[Program]::Main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment