PowerShell / SHiPS

Simple Hierarchy in PowerShell - developing PowerShell provider got so much easier
MIT License
186 stars 31 forks source link

[Question] Pass parameters to the module scope #69

Closed DexterPOSH closed 6 years ago

DexterPOSH commented 6 years ago

As a POC, I am creating a PSDrive which will map the Dell PowerEdge servers inside a PESystem PSDrive, for this to happen we need to discover the open CIM sessions or create new CIM sessions on the fly when the PSDrive loads.

Below is how my PESystem.psm1 looks like at the moment.

using namespace Microsoft.PowerShell.SHiPS
using module .\PEServer.psm1

[SHiPSProvider(UseCache=$true)]
class PESystem: ShiPSDirectory {

    PESystem(): base($this.GetType())
    {
    }

    [object[]] GetChildItem()
    {
        $obj = @()
        # fetch the CIM session for the PEDRAC servers
        # IDRAC
        $iDRACSessions = @(& "CimCmdlets\Get-CimSession") # this does not find any live CIM sessions from outside scope
        Write-Verbose -Message "Found iDRACSessions -> $($iDRACSessions.Count)" -Verbose
        foreach ($iDRACSession in $iDRACSessions) {
            $obj += [PEServer]::new($iDRACSession)
        }
        return $obj;
    }

}

If I create the CIM sessions in the outside scope they are not visible to the PSDrive while loading (guessing because of module running in their own scope).

I can always pass/create CIM sessions inside the PESystem.psm1 aswell by adding required parameters. But again when the PSDrive loads it does not allow us to pass arguments.

Any guidance on how my PESystem.psm1 can access/create CIMSessions?

jianyunt commented 6 years ago

@DexterPOSH yes not visible because it runs on different runspace. If you want your users to pass in parameters for example, "dir -cimsession ", you can use dynamicparameters see samples https://github.com/PowerShell/SHiPS/tree/development/samples/DynamicParameter

Another approach I can think of is, if you are allowed to create CIM sessions within your PESystem class, you may put these logics to a private method for example.

     ...
   hidden [object[]] $cimSessions = $nulll

    PESystem([string]$name) : base ($name)
    {
        ...
       $this.cimSessions = $this.CreateMyCimSessions($name)
        ...
    }

   [object] CreateMyCimSessions([string]$mydata)
    {
      # create CIM sessions here.
    }

    [object[]] GetChildItem()
    {
        # for each $this.cimSessions and return
    }
DexterPOSH commented 6 years ago

@jianyunt Thanks, I will take a look at using Dynamicparameter, that should serve our purpose.