The below code is annoyingly not just returning the contents of the $t variable, of even if the contents of $t are instead returned like return "!! Quitting...":
function AddADUser
{
....
$Answer = [System.Windows.Forms.MessageBox]::Show("WARNING: The below account already exists in domain $domain. Continue to update it (yes), or quit and rerun should it be needed after investigation (no)?", "$ScriptFileName", "YesNo")
if($Answer -eq "no")
{
write-host "Before return"
$t = "!! Quitting script on user cancellation, due to not wanting to update existing user(s) data with new details provided`r`n"
write-host "$t"
return $t
}
}
Instead the console output before and after the function returns:
Before return
!! Quitting script on user cancellation, due to not wanting to update existing user(s) data with new details provided
System.Management.Automation.PSCustomObject !! Quitting script on user cancellation, due to not wanting to update existing user(s) data with new details provided
$t contains nothing prior to being assigned after the first write-host
This must be a quirk to Powershell function return, but I can't figure it out where the darned System.Management.Automation.PSCustomObject is coming from, apart from maybe if the function returned at a later stage, it would contain an object (I have checked with a write-host it is not proceeding to that stage though). What is going on!?
$null = .... If you don't discard such output, it becomes part of a script or function's "return value" (stream of output objects), which is not limited to what is passed to an - optional -returnstatement. See this answer for more information.PSCustomObjectvalue being sent to the function’s output stream. Note thatwrite-hostresults in immediate console output, but the values from the output stream could potentially be delayed for… reasons… so the offending line could even be in the….part of your code. Check each line of your original function for uncaptured expressions, and suppress them with$null = …as suggested above.write-hostthat was producing the PSObject `write-host "$($AccountsMatching.gettype())". Like this, the output is no longer polluted!