Search code examples
c#powershellpowershell-cmdlet

C# Cmdlet call GetChildItem


I'm writting a c# cmdlet, and I need to use Get-ChildItems PowerShell cmdlet. Nee

How can I call this cmdlet from my code, without invoking "string PowerShell command"? Basically I try to call the c# GetChildItem code.

[Cmdlet(VerbsCommon.Get, "SampleCmdlet")]
public class GetSampleCmdlet : Cmdlet
{
    [Parameter()]
    public string Parameter1 { get; set; }

    protected override void ProcessRecord()
    {
        //Call c# Get-ChildItem and do something with results

        //Don't want to do somthing like:
        //string stringCommand = "Get-ChildItem 'c:\\*.Txt'";
        //InvokePowerShellCommand(stringCommand);

    }

}

I only need the FileSystemProvider, but it should be a way to call directly GetChildItem cmdlet.


Solution

  • If you extend PSCmdlet instead of Cmdlet, you can access the current provider through the InvokeProvider property - from the docs:

    If your Cmdlet requires access to the MSH Runtime (for example, variables in the session state, access to the host, or information about the current Cmdlet Providers,) then you should instead derive from the PSCmdlet base class.

    You can invoke the Get-ChildItem provider cmdlet via:

    InvokeProvider.ChildItem.Get(@"C:\path\to\dir", false);