Skip to content

Removing Git Commit History with PowerShell Script

This PowerShell script is designed to remove the commit history of a Git repository while keeping the current state of the files intact. It creates a fresh Git history, starting from a new initial commit, and pushes this new history to the remote repository. This is a highly destructive operation and should be used with caution.

# Initialize Variables
$sourceBranch = "main"
$newCommitMessage = "Initial commit"
$remoteName = "origin"

# Generate a unique orphan branch name using the timestamp
$timestamp = [int](Get-Date -UFormat %s)
$newBranch = "orphan_$timestamp"

# Fetch the latest changes and switch to the source branch
git fetch
git switch $sourceBranch

# Create a new orphan branch, reset the working directory, and stage all files
git checkout --orphan $newBranch
git add -A

# Commit the changes with the specified message
git commit -m $newCommitMessage

# Force push the orphan branch to the remote (this will not overwrite yet)
git push $remoteName $newBranch --force

# Delete the old branch from the remote repository
git push $remoteName --delete $sourceBranch

# Delete the old branch locally after pushing the new history
git branch -D $sourceBranch

# Rename the orphan branch to the source branch locally
git branch -m $newBranch $sourceBranch

# Force push the new history (the renamed orphan branch) to the remote repository
git push -f $remoteName $sourceBranch

# Perform garbage collection to remove old objects
git gc --prune=now

Important Warning

While the script removes the commit history in terms of visibility (the commits won't be listed in the log), the commit history is not actually removed. Instead, it's hidden by creating a new branch with no prior history. This means that the original commit history still exists in the Git repository's internal storage, local clones, and remote forks. If someone knows the repository's object IDs or has access to the previous commits, the history can still be accessed.

Why Remove Commit History?

  • To discard large or unnecessary files from the repository's history.
  • To increase third-party tool compatibility where you cannot specify to checkout only the last commit.

This script does not increase security or privacy in any way.