PowerShell: Renaming a System File

System files are typically owned by the TrustedInstaller account and protected from deletion or changes. This function is to bypass this block. Please use it wisely!

function renameSystemFile($file,$newName){    
    #This function currently doesn't deal with UNC paths. Hence, local paths are assumed.
    $ErrorActionPreference='stop'
    if(!(test-path $file)){
        write-warning "$file is not accessible."
        return $False
    }
    if(!$newName){
        $newName="$(split-path $file -leaf).bak"
    }
    $newFile="$(split-path $file -parent)\$newName"
    try{
        if(test-path $newFile){
            $newFileInfo=(get-item $newFile).VersionInfo
            $originalFileName=$newFileInfo.OriginalFileName
            $originalVersion=$newFileInfo.ProductVersion
            rename-item $newFile "$originalFileName`_$originalVersion.bak" -force
        }
        if(!(get-command takeown -ea Ignore)){
            write-warning "C:\Windows\system32\takeown.exe is missing"
        }else{
            try {
                & takeown /f $file
            }catch{
                write-warning $_
            }
        }
        write-host "Granting $env:username and Administrators full access to $file..."
        $acl=Get-ACL $file
        $originalOwnerAccess=New-Object System.Security.AccessControl.FileSystemAccessRule($acl.Owner,"FullControl","Allow")
        $userAccess = New-Object System.Security.AccessControl.FileSystemAccessRule($env:username,"FullControl","Allow")
        $administratorsAccess=New-Object System.Security.AccessControl.FileSystemAccessRule('Administrators',"FullControl","Allow")
        $acl.AddAccessRule($originalOwnerAccess)
        $acl.AddAccessRule($userAccess)
        $acl.AddAccessRule($administratorsAccess)
        Set-Acl $file $acl
        write-host "Renaming $file to $newName..."
        rename-item $file $newName -force
    }catch{
        write-warning $_
        return $False
    }
    if(!(Test-Path $file) -and (Test-Path $newFile)){
        write-host "$file has been successfully renamed to $newName" -ForegroundColor Green
        return $True
    }else{
        write-warning "$file has NOT been renamed to $newName"
        return $False
    }
}
# Sample Output

PS C:\WINDOWS\system32> renameSystemFile c:\log.txt
SUCCESS: The file (or folder): "c:\log.txt" now owned by user "DESKTOP-007\rambo".
Granting rambo and Administrators full access to c:\log.txt...
Renaming c:\log.txt to log.txt.bak...
c:\log.txt has been successfully renamed to log.txt.bak
True

PS C:\WINDOWS\system32> renameSystemFile c:\log.txt.bak log.txt
SUCCESS: The file (or folder): "c:\log.txt.bak" now owned by user "DESKTOP-007\rambo".
Granting rambo and Administrators full access to c:\log.txt.bak...
Renaming c:\log.txt.bak to log.txt...
c:\log.txt.bak has been successfully renamed to log.txt
True

Leave a Reply

Your email address will not be published. Required fields are marked *