How to import custom PowerShell module into the remote session?

前端 未结 5 1300
名媛妹妹
名媛妹妹 2020-12-13 02:18

I\'m developing a custom PowerShell module, which I\'d like to use in context of a remote session to a different computer. The following code (which obviously doesn\'t work)

5条回答
  •  难免孤独
    2020-12-13 02:41

    Thanks for this thread it was helpfull….

    But i actually rewrote the function.

    Be aware, that nether the original function in this post or this rewritten function includes module manifest data. So you cant rely on version checks on the module.

    function Import-ModuleRemotely {
        Param (
            [string] $moduleName,
            [System.Management.Automation.Runspaces.PSSession] $session
        )
    
        Import-Module $moduleName
    
        $Script = @"
        if (get-module $moduleName)
        {
            remove-module $moduleName;
        }
    
        New-Module -Name $moduleName { $($(Get-Module $moduleName).Definition) } | Import-Module
    "@
    
        Invoke-Command -Session $Session -ScriptBlock {
            Param($Script)
            . ([ScriptBlock]::Create($Script))
            Get-Module 
        } -ArgumentList $Script
    }
    

提交回复
热议问题