【问题标题】:Alternative to remotely importing modules in powershell在 powershell 中远程导入模块的替代方法
【发布时间】:2015-08-24 22:24:07
【问题描述】:

我有一个远程执行的包含 3 个部分(remoteScript、script.ps1 和模块)的脚本。第一部分使用 credssp 处理远程执行的身份验证。这个脚本,我们称之为remoteScript,使用invoke-command 来执行另一个脚本。

$script =
{
    Invoke-Expression ("{0}\script.ps1" -f $PSScriptRoot)
}
Invoke-Command -ComputerName "computerName" $script -Authentication Credssp -Credential $cred

script.ps1 导入包含用于执行主体的 cmdlet 的各种模块。问题是模块位于主机上。为了让远程计算机运行脚本,它需要访问模块。在这种情况下,远程计算机无法连接回主机以加载模块。

  1. 我可以将模块中的所有 cmdlet 放入脚本主体,从而生成一个没有人愿意阅读/维护的庞大脚本。

  2. 我可以尝试在 remoteScript 中加载模块,然后使用 export-pssession 将所有当前加载的 cmdlet 导出到远程计算机上的已知位置。然后脚本会加载导出的 pssession。

我不完全确定我会如何做后者,或者您是否甚至可以使用 export-pssession 将它们导出到远程计算机。我发现与此相关的最接近的参数是-OutputModule,但我认为您需要在远程计算机上共享才能将 pssession 保存在那里。

我愿意接受任何想法/想法/反馈。

【问题讨论】:

    标签: powershell powershell-remoting


    【解决方案1】:

    您可以使用${function:<FunctionNameHere>} 语法在远程计算机上运行本地函数,您尝试过吗?

    它是这样工作的:

    # Define a simple function locally
    function Get-Stuff { param($stuff1,stuff2) Write-Host "$stuff1 $stuff2" }
    
    # Similar to calling Get-Stuff "stuffArgument1" "stuffArgument2"
    # Keep in mind that you can only give positional arguments using this method
    Invoke-Command -ComputerName "computerName" -ScriptBlock ${Get-Stuff} -ArgumentList "stuffArgument1","stuffArgument2" -Credential $cred
    

    【讨论】:

    • 谢谢,我试试看。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-02-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-17
    • 1970-01-01
    相关资源
    最近更新 更多