2

我正在通过 PowerShell 连接到 Exchange 2010 for Live@edu。我可以使用标准方法进行连接。但是,每次都下载和导入会话命令似乎很浪费,尤其是因为它不在 LAN 上。此外,有时,这些脚本会向网页返回数据,而且导入时间似乎也很浪费。

我找到了如何使用 Export-PSSession cmdlet 导出会话。如果我使用 Import-Module 导入导出的模块,则一切正常,除了一个问题。当我从模块运行 cmdlet 时,它希望我通过 GUI 以交互方式设置密码。我真正想要的是让我的脚本以非交互方式运行,但在本地加载模块。

这可能吗?

4

1 回答 1

2

您面临的问题是您需要能够为所有导入的函数隐式设置 PSSession。为此,您需要能够运行该Set-PSImplicitRemotingSession功能。

不幸的是,该功能没有被导出,因此您无法访问它。要解决这个问题,您需要做的是破解打开 PSM1 文件并将该功能添加到$script:ExportModuleMember. 现在,当您导入模块时,该功能将能够为所有功能设置 PSSession。

这是您的 powershell 或脚本需要运行才能使用任何导入的模块。

Import-Module "C:\Credentials.psm1"
Import-Module "C:\ExportedPSSession.psm1"
$Cred = Import-Credential -path C:\Cred.xml
$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri "https://ps.outlook.com/powershell/" -Authentication Basic -AllowRedirection -Credential $Cred
Set-PSImplicitRemotingSession -PSSession $Session -createdByModule $True
#You can now run any of the imported functions.

Credentials.psm1 当心!任何可以加载 xml 文件的人现在都可以冒充您!

function Export-Credential($cred, $path) {    
  $cred = $cred | Select-Object *    
  $cred.password = $cred.Password | ConvertFrom-SecureString
  $obj = New-Object psobject
  $obj | Add-Member -MemberType NoteProperty -Name UserName -Value $cred.username
  $obj | Add-Member -MemberType NoteProperty -Name Password -Value $cred.password
  $obj | Export-Clixml $path
}

function Import-Credential($path) {    
  $obj = Import-Clixml $path    
  $obj.password = $obj.Password | ConvertTo-SecureString
    return New-Object system.Management.Automation.PSCredential( $obj.username, $obj.password)
}
于 2011-03-23T01:39:44.677 回答