cleanup-old-file.ps1
· 1.2 KiB · PowerShell
Bruto
# Define the path to the file or folder
$path = "C:\Program Files (x86)_1"
# Get the current user's identity
$currentUser = [System.Security.Principal.WindowsIdentity]::GetCurrent().Name
# Create a security identifier (SID) for the current user
$currentUserAccount = New-Object System.Security.Principal.NTAccount($currentUser)
$currentUserSid = $currentUserAccount.Translate([System.Security.Principal.SecurityIdentifier])
# Process each item recursively
Get-ChildItem -Path $path -Recurse -Force | ForEach-Object {
# Get the current ACL of the item
$acl = Get-Acl $_.FullName
# Set the owner to the current user
$acl.SetOwner($currentUserSid)
# Create a new access rule for FullControl
$rule = New-Object System.Security.AccessControl.FileSystemAccessRule($currentUser, "FullControl", "ContainerInherit,ObjectInherit", "None", "Allow")
# Add the new access rule to the ACL
$acl.AddAccessRule($rule)
# Apply the modified ACL (including new owner and permissions) to the item
Set-Acl -Path $_.FullName -AclObject $acl
}
Write-Host "Ownership and permissions have been updated successfully."
Remove-Item -Path $filePath -Recurse -Force
| 1 | # Define the path to the file or folder |
| 2 | $path = "C:\Program Files (x86)_1" |
| 3 | |
| 4 | # Get the current user's identity |
| 5 | $currentUser = [System.Security.Principal.WindowsIdentity]::GetCurrent().Name |
| 6 | |
| 7 | # Create a security identifier (SID) for the current user |
| 8 | $currentUserAccount = New-Object System.Security.Principal.NTAccount($currentUser) |
| 9 | $currentUserSid = $currentUserAccount.Translate([System.Security.Principal.SecurityIdentifier]) |
| 10 | |
| 11 | # Process each item recursively |
| 12 | Get-ChildItem -Path $path -Recurse -Force | ForEach-Object { |
| 13 | # Get the current ACL of the item |
| 14 | $acl = Get-Acl $_.FullName |
| 15 | |
| 16 | # Set the owner to the current user |
| 17 | $acl.SetOwner($currentUserSid) |
| 18 | |
| 19 | # Create a new access rule for FullControl |
| 20 | $rule = New-Object System.Security.AccessControl.FileSystemAccessRule($currentUser, "FullControl", "ContainerInherit,ObjectInherit", "None", "Allow") |
| 21 | |
| 22 | # Add the new access rule to the ACL |
| 23 | $acl.AddAccessRule($rule) |
| 24 | |
| 25 | # Apply the modified ACL (including new owner and permissions) to the item |
| 26 | Set-Acl -Path $_.FullName -AclObject $acl |
| 27 | } |
| 28 | |
| 29 | Write-Host "Ownership and permissions have been updated successfully." |
| 30 | Remove-Item -Path $filePath -Recurse -Force |