简体   繁体   English

PowerShell返回PSSession对象

[英]PowerShell returning a PSSession object

I'm new to PowerShell and trying to write some Exchange Online modular scripts for various tasks. 我是PowerShell的新手,正在尝试为各种任务编写一些Exchange Online模块化脚本。 The model I'm working on is to have a control script that calls other parameterised scripts to perform reusable functions. 我正在研究的模型是有一个控制脚本,该脚本调用其他参数化脚本来执行可重用的功能。

I've written a connection script, but when I return the PSSession object to my command script I can't import the session, it is somehow getting cast to an object. 我已经编写了一个连接脚本,但是当我将PSSession对象返回到我的命令脚本时,我无法导入会话,因此某种程度上它被强制转换为对象。

How should I be sharing this session around my scripts? 我应该如何围绕脚本共享此会话?

Control script: 控制脚本:

$session = .\Connection.ps1 -user admin@mydomain.com
Import-PSSession $session

Connection script (summary): 连接脚本(摘要):

Param (
[string]$userparam
)
$UserCredential = Get-Credential -userName $userparam
$Exch = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://outlook.office365.com/powershell-liveid/ -Credential $UserCredential -Authentication Basic -AllowRedirection
return $Exch

First, this is happening because when you run a script it runs in its own scope. 首先,这是因为您在运行脚本时会在自己的范围内运行脚本。 You'll get the return value as an object, but it won't be "live" anymore because the scope in which it was created doesn't exist. 您将获得作为对象的返回值,但是它将不再有效,因为创建它的范围不存在。

Second, it sounds an awful lot like what you really want is a module . 其次,这听起来很像您真正想要的是模块 Write these pieces as functions, not scripts, and then make them into a single package by writing them as a module. 将这些片段作为函数而不是脚本编写,然后通过将它们作为模块编写,使其成为一个软件包。

Doing so would solve your scope problem as well, but the advantages are many. 这样做也可以解决您的示波器问题,但是优点很多。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM