How to force powershell function to return an object and set $? to $ false?

I have code in powershell function that looks like this:

try { Invoke-SomethingThatFails } catch [System.Exception] { Write-Error $_.Exception.Message; return New-Object Namespace.CustomErrorType -Property @{ 'Code' = "Fail"; "Message" = $_.Exception.Message; } } 

Now the only problem is I would also like to set $? for $ false. Is it possible?

+4
source share
1 answer

From Bruce Payettes PowerShell In Action (Second Edition) :

$? the variable will be true if the entire operation is successful, and false otherwise. For example, if any of the operations wrote an error object, then $? will be set to false even if the error was thrown using redirection. This is an important point: this means that the script can determine if an error has occurred, even if the error isnt displayed.

PowerShell runtime controls $? value $? and set to false when the error object is written to the pipeline.

Update . Here is how you can write an error object to the pipeline, but not complete it (pipeline):

 function New-Error { [CmdletBinding()] param() $MyErrorRecord = new-object System.Management.Automation.ErrorRecord ` "", ` "", ` ([System.Management.Automation.ErrorCategory]::NotSpecified), ` "" $PSCmdlet.WriteError($MyErrorRecord) } $Error.Clear() Write-Host ('$? before is: ' + $?) New-Error Write-Host ('$? after is: ' + $?) 

Output:

 $? before is: True New-Error : At C:\...\....ps1:14 char:10 + New-Error <<<< + CategoryInfo : NotSpecified: (:String) [New-Error], Exception + FullyQualifiedErrorId : New-Error $? after is: False 
+6
source

Source: https://habr.com/ru/post/1391537/


All Articles