views:

22

answers:

1

How can I get the return code from the following command:

RunspaceConfiguration rsConfig = RunspaceConfiguration.Create(); 
PSSnapInException snapInException = null; 
PSSnapInInfo info = rsConfig.AddPSSnapIn("Microsoft.Exchange.Management.PowerShell.Admin", out snapInException);
Runspace myRunSpace = RunspaceFactory.CreateRunspace(rsConfig); myRunSpace.Open();

    //Create pipeline and feed it the script text
    Pipeline pipeline = myRunSpace.CreatePipeline();

    string strScript = "new-storagegroup -Server KINGKONG"
        + " -LogFolderPath c:\\rsg\\logs -Name RecoveryGroup -SystemFolderPath c:\\rsg\\data -Recovery";

    //Add the command to the Commands collection of the pipeline.
    pipeline.Commands.AddScript(strScript)

    Collection<PSObject> results = pipeline.Invoke();
A: 

You can query the execution status of the last command (boolean) by getting the value of the $? variable e.g.:

bool succeeded = myRunspace.SessionStateProxy.GetVariable("?");
Keith Hill
Why would it always return true, even when it failed to create the recovery group as it already existed?
RPS
Execution status is a bit weird in PowerShell, IIRC it indicates that a terminating error occured e.g. `gci xyzzy; $?` returns True even though the file doesn't exist. You can capture non-terminating errors in several ways but the most straight forward is to use the ubiquitous parameter -ErrorVariable (-ev for short). `$status = $null;gci xyzzy -ev status; $status` - in this case $status will hold the non-terminating error information.
Keith Hill