Binary Cmdlets and Directory.GetCurrentDirectory() don’t mix

Problem:

From with in my C# based binary PowerShell Module I need to know the current folder of my PowerShell session. Using Directory.GetCurrentDirectory() returns the location of my binary not the location of the user in the PowerShell session.

Solution:

Steven Murawski pointed out that you can use the Path property of the SessionState property of your PSCmdlet derived class.

image

If your class derives directly from Cmdlet you will not have access to the SessionState property. There you can issue a PowerShell call to Get-Location to get the same information.

   1:  public override string GetCurrentLocation()
   2:  {
   3:     // We can't use Directory.GetCurrentDirectory()
   4:     var ps = PowerShell.Create(RunspaceMode.CurrentRunspace);
   5:     var results = ps.AddCommand("Get-Location").Invoke();
   6:   
   7:     return results[0].ImmediateBaseObject.ToString();
   8:  }

Add comment

Loading