PSObject.BaseObject Property

 

Updated: April 27, 2016

Applies To: Windows PowerShell

Gets the base object of the PSObject object. If the base object is another PSObject object, then its base object is returned.

Namespace:   System.Management.Automation
Assembly:  System.Management.Automation (in System.Management.Automation.dll)

public object BaseObject { get; }

Property Value

Type: System.Object

A Object object or a PSCustomObject object that represents the encapsulated object.

To get a base object that is itself a PSObject object, call the ImmediateBaseObject property.

A base object of type PSCustomObject indicates that the encapsulating PSObject object does not have a meaningful base object. However, this type of encapsulating PSObject object does provide a type name property bag that cmdlet developers can add extended members to. Developers can also specify the object's type name, which allows this object to share its extended members with other PSObject objects of the same type name.

The following code example uses BaseObject to retrieve an error message.

private void ReportException(Exception e)
{
  if (e != null)
  {
    object error;
    IContainsErrorRecord icer = e as IContainsErrorRecord;
    if (icer != null)
    {
      error = icer.ErrorRecord;
    }
    else
    {
      error = (object)new ErrorRecord(e, "Host.ReportException", ErrorCategory.NotSpecified, null);
    }

    lock (this.instanceLock)
    {
      this.currentPowerShell = PowerShell.Create();
    }

    this.currentPowerShell.Runspace = this.myRunSpace;

    try
    {
      this.currentPowerShell.AddScript("$input").AddCommand("out-string");

      // Do not merge errors, this function will swallow errors.
      Collection<PSObject> result;
      PSDataCollection<object> inputCollection = new PSDataCollection<object>();
      inputCollection.Add(error);
      inputCollection.Complete();
      result = this.currentPowerShell.Invoke(inputCollection);

      if (result.Count > 0)
      {
        string str = result[0].BaseObject as string;
        if (!string.IsNullOrEmpty(str))
        {
          // Remove \r\n, which is added by the Out-String cmdlet.    
          this.myHost.UI.WriteErrorLine(str.Substring(0, str.Length - 2));
        }
      }
    }
    finally
    {
      // Dispose of the pipeline and set it to null, locking it  because 
      // currentPowerShell may be accessed by the ctrl-C handler.
      lock (this.instanceLock)
      {
        this.currentPowerShell.Dispose();
        this.currentPowerShell = null;
      }
    }
  }
}
Return to top

Community Additions

ADD
Show: