How To Windows Commands Exit with the Wrong Code

Windows commands often exit with a 0 code, even if the command fails. Catch errors like this using Select-String; the Powershell equivalent of grep.

1
2
3
4
5
6
7
8
echo "Attempting to sync Group Policy..."
$out = gpupdate
echo $out

$result = Select-String -InputObject $out -Pattern "error"
if ($result.length -ne 0) {
    exit 1
}