Powershell Remoting: using imported module cmdlets in a remote pssession

前端 未结 7 2123
我在风中等你
我在风中等你 2021-02-05 12:34

Is there a way to use modules that were imported in a local session in a remote session? I looked at import-pssession, but I don\'t know how to get the local session. Here\'s a

7条回答
  •  你的背包
    2021-02-05 13:07

    As an alternate to what Jonathan mentions, if you have source modules you want to push over the wire, then you can do that without too much trouble. If you have binaries, you might be able to do something similar.but I'd say all bets are off there. Essentially you push the files over as params in a hash, write to temp, then import.

    function Export-SourceModulesToSession
    {
        Param(
         [Management.Automation.Runspaces.PSSession]
         [ValidateNotNull()]
         $Session,
    
        [IO.FileInfo[]]
        [ValidateNotNull()]
        [ValidateScript(
        {
          (Test-Path $_) -and (!$_.PSIsContainer) -and ($_.Extension -eq '.psm1')
        })]
       $ModulePaths
      )
    
       $remoteModuleImportScript = {
         Param($Modules)
    
         Write-Host "Writing $($Modules.Count) modules to temporary disk location"
    
         $Modules |
           % {
             $path = ([IO.Path]::GetTempFileName()  + '.psm1')
             $_.Contents | Out-File -FilePath $path -Force
             "Importing module [$($_.Name)] from [$path]"
             Import-Module $path
           }
       }
    
      $modules = $ModulePaths | % { @{Name = $_.Name; Contents = Get-Content $_ } }
      $params = @{
        Session = $Session;
        ScriptBlock = $remoteModuleImportScript;
        Argumentlist = @(,$modules);
      }
    
      Invoke-Command @params
    }
    

    Call like

    $session = New-PSSession -ComputerName Foo
    Export-SourceModulesToSession $session -ModulePaths '.\module.psm1','.\module2.psm1'
    

    Also theoretically possible, exporting a current localhost session to module and pushing that over the wire -- untested pseudo-code. This might not work...

    $localSession = New-PSSession #defaults to localhost
    
    # if you don't have modules automatically loading in the profile, etc, then manually load them
    Invoke-Command -Computer $localSession -ScriptBlock { Import-Module 'foo'; Import-Module '.\module.ps1' }
    Export-PSSession $localSession -OutputModule TempLocalModule
    #now that you have TempLocalModule written out, it's possible you can send that thing across the wire in the same way
    

提交回复
热议问题