Check if git status is clean inside a Powershell script

git status --porcelain returns git status in an stable, easy-to-parse format.

In my own testing, without additional flags it returns specifically an empty string if there are no modifications to tracked files and also no untracked files. To ignore untracked files, the flag --untracked-files=no may be added. The simple powershell statements below leverage that to yield booleans $hasEditsToTrackedFiles and $hasEditsToTrackedFilesOrHasUntrackedFiles.

Using the --untracked-files=no flag seems a little simpler and easier to understand than doing a regex match. Possibly --short could be used here in place of --porcelain, but i haven't tested it.

$hasEditsToTrackedFiles                    = !([string]::IsNullOrEmpty($(git status --porcelain --untracked-files=no)))
$hasEditsToTrackedFilesOrHasUntrackedFiles = !([string]::IsNullOrEmpty($(git status --porcelain)))

Use git status --porcelain to get the output as a list that's easy to parse.

Untracked files are prefixed with the status ??, so you can easily filter those out and then check if there are uncommitted changes based on whether there is any output left:

if(git status --porcelain |Where {$_ -match '^\?\?'}){
    # untracked files exist
} 
elseif(git status --porcelain |Where {$_ -notmatch '^\?\?'}) {
    # uncommitted changes
}
else {
    # tree is clean
}

I found one another solution using git status --porcelain.

$ChangedFiles = $(git status --porcelain | Measure-Object | Select-Object -expand Count)
if ($ChangedFiles -gt 0)
{
    Write-Output "Found $ChangedFiles changed files"
}