If you don't specify DataDir in the xml this function errors as it tries to remove the trailing '\' from a string that is null.
The line:
$dataDir = $dataDir.TrimEnd("\")
needs to be moved from before the line:
if ([string]::IsNullOrEmpty($dataDir)) {$dataDir = "%PROGRAMFILES%\Microsoft Office Servers\$env:spVer.0\Data"}
to after it.
The line:
$dataDir = $dataDir.TrimEnd("\")
needs to be moved from before the line:
if ([string]::IsNullOrEmpty($dataDir)) {$dataDir = "%PROGRAMFILES%\Microsoft Office Servers\$env:spVer.0\Data"}
to after it.