Powershell Remoting:在远程 pssession 中使用导入的模块 cmdlet [英] Powershell Remoting: using imported module cmdlets in a remote pssession
问题描述
有没有办法在远程会话中使用在本地会话中导入的模块?我查看了import-pssession,但不知道如何获取本地会话.这是我想要做的示例.
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 sample of what I want to do.
import-module .\MyModule\MyModule.ps1
$session = new-pssession -computerName RemoteComputer
invoke-command -session $session -scriptblock { Use-CmdletFromMyModule }
另外,我不想在远程会话中导入模块,因为 ps1 文件不在该服务器上.
Also, I do not want to import-module in the remote session, as the ps1 files are not on that server.
推荐答案
我最终通过破解这个来工作.我所做的是创建一个本地会话,将模块导入该会话并使用 import-pssession 将模块从创建的本地会话导入远程会话.这很慢.如果有人有更好的方法来做到这一点,或者如果有人知道如何获取基础会话的实例,我很乐意听取您的意见!
I ended up hacking this to work. What I did was create a local session, import modules into that session and used import-pssession to import modules from the created local session into the remote session. This is slow. If anyone has a better way of doing this, or if someone knows how to get an instance of the base session I'd love to hear from you!
远程处理.psm1
function Export-ModuleToSession {
Param(
[ValidateNotNull()]
$session,
[ValidateNotNull()]
$modules
)
$computername = $env:computername
$modulesToImport = get-module -name $modules
invoke-command -session $session -argumentlist @($computername, $modulesToImport) -scriptblock {
Param(
$computername,
$modules
)
write-host ("Creating Temp Session On: " + $computername)
$localSession = New-psSession -computername $computername
$modules | foreach-object {
if($_.ModuleType -ne "Binary") {
$path = $_.path
}
else {
$path = join-path (split-path $_.Path) ("{0}.psd1" -f $_.name)
}
invoke-command -session $localSession -argumentList $path -scriptblock {
Param(
$path
)
$initializeDefaultBTSDrive = $false
set-executionpolicy unrestricted
write-host ("Importing Module To Temp Session: " + $path)
import-module $path
}
}
$initializeDefaultBTSDrive = $false
$modules | foreach-object {
write-host ("Exporting Module: " + $_.name)
import-psSession -session $localSession -Module $_.name | out-null
}
}
}
MyModule.psm1
MyModule.psm1
function MyCmdlet {}
远程测试.ps1
import-module .\remoting.psm1
import-module .\MyModule.psm1
try
{
$remoteSession = New-PsSession -computerName "RemoteComputer"
Export-ModuleToSession -session $remoteSession -modules "MyModule"
Invoke-Command -session $remoteSession -scriptblock { MyCmdlet } -verbose -ea Stop
}
finally
{
Remove-PsSession $remoteSession -ea Continue
Remove-Module "Remoting" -ea Continue
Remove-Module "MyModule" -ea Continue
}
这篇关于Powershell Remoting:在远程 pssession 中使用导入的模块 cmdlet的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!