设置一个等于 powershell 脚本输出的变量

Set a variable equal to the output of a powershell script

这有点难以解释,但我会尽力而为。我正在编写一些代码,使用 Powershell 通过 EWS 将 AD 联系人导入用户的邮箱。

我有一个 Main.ps1 文件调用在后台运行的所有其他脚本(例如 1 导入 AD 模块)另一个导入 O365 模块。

我有 1 个连接到 EWS 的脚本容器。代码如下所示:

#CONFIGURE ADMIN CREDENTIALS
$userUPN = "User@domain.com" 
$AESKeyFilePath = ($pwd.ProviderPath) + "\ConnectToEWS\aeskey.txt"
$SecurePwdFilePath =  ($pwd.ProviderPath) + "\ConnectToEWS\password.txt"
$AESKey = Get-Content -Path $AESKeyFilePath -Force
$securePass = Get-Content -Path $SecurePwdFilePath -Force | ConvertTo-SecureString -Key $AESKey

#create a new psCredential object with required username and password
$adminCreds = New-Object System.Management.Automation.PSCredential($userUPN, $securePass)

Try
{
    [Reflection.Assembly]::LoadFile("\MBX-Server\c$\Program Files\Microsoft\Exchange\Web Services.2\Microsoft.Exchange.WebServices.dll") | Out-Null
    $service = New-Object Microsoft.Exchange.WebServices.Data.ExchangeService([Microsoft.Exchange.WebServices.Data.ExchangeVersion]::Exchange2013_SP1)
    $service.Credentials = New-Object Microsoft.Exchange.WebServices.Data.WebCredentials($userUPN,$adminCreds.GetNetworkCredential().Password)
    $service.Url = new-object Uri("https://outlook.office365.com/EWS/Exchange.asmx");
    
    return $service
}
Catch
{
    Write-Output "Unable to connect to EWS. Make sure the path to the DLL or URL is correct"
}

该代码的输出打印出服务连接,但我希望该输出的信息存储在 $service 等变量中。

然后我将该变量传递给绑定到我想要的邮箱的另一个脚本... 我遇到的问题是 $service 似乎没有存储该信息。当我从上面的脚本中 return 它时,它只打印一次,但它不会在主脚本中附加该信息。当我打印 $service 时,它​​打印了一次,但随后它自己清除了。

这是我的主要脚本

CLS

#Root Path
$rootPath = $pwd.ProviderPath #$PSScriptRoot #$pwd.ProviderPath

Write-Host "Importing all necessary modules."

#******************************************************************
#                            PREREQUISITES
#******************************************************************
#Nuget - Needed for O365 Module to work properly

if(!(Get-Module -ListAvailable -Name NuGet))
{
    #Install NuGet (Prerequisite) first
    Install-PackageProvider -Name NuGet -Scope CurrentUser -Force -Confirm:$False
}

#******************************************************************

#Connect w\ Active Directory Module
& $rootPath\AD-Module\AD-module.ps1

#Load the O365 Module
& $rootPath\O365-Module\O365-module.ps1

#Clear screen after loading all the modules/sessions
CLS

#******************************************************************
#                         PUT CODE BELOW
#******************************************************************

#GLOBAL VARIABLES
$global:FolderName = $MailboxToConnect = $Service = $NULL

#Connect to EWS
& $rootPath\ConnectToEWS\ConnectToEWS.ps1

#Debug
$Service
    
#Create the Contacts Folder

& $rootPath\CreateContactsFolder\CreateContactsFolder.ps1 

#Debug
$service
$ContactsFolder

#Clean up Sessions after use

if($NULL -ne (Get-PSSession))
{
    Remove-PSSession *
}

[GC]::Collect()

我第一次输出 $service 变量时,它打印得很好。在第二个调试输出中,它不再打印出来,我相信这就是为什么当我启动“CreateContactsFolder.ps1”

时脚本失败的原因

这是“CreateContactsFolder.ps1”的内容

CLS

Try
{    
    $service.ImpersonatedUserId = New-Object Microsoft.Exchange.WebServices.Data.ImpersonatedUserId([Microsoft.Exchange.WebServices.Data.ConnectingIdType]::SmtpAddress, $MailboxToConnect);
        
    $RootFolder = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($service,[Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::MsgFolderRoot)
    $RootFolder.Load()
        
    #Check to see if they have a contacts folder that we want
    $FolderView = new-Object Microsoft.Exchange.WebServices.Data.FolderView(1000)
    $ContactsFolderSearch = $RootFolder.FindFolders($FolderView) | Where-Object {$_.DisplayName -eq $FolderName}

    if($ContactsFolderSearch)
    {
        $ContactsFolder = [Microsoft.Exchange.WebServices.Data.ContactsFolder]::Bind($service,$ContactsFolderSearch.Id);

        #If folder exists, connect to it. Clear existing Contacts, and reupload new (UPDATED) Contact Info
        Write-Output "Folder alreads exists. We will remove all contacts under this folder."

        # Attempt to empty the target folder up to 10 times.
        $tries = 0
        $max_tries = 0
        while ($tries -lt 2) 
        {
            try 
            {
                $tries++
                $ErrorActionPreference='Stop'
                $ContactsFolder.Empty([Microsoft.Exchange.WebServices.Data.DeleteMode]::HardDelete, $true)
                $tries++
            } 
            catch 
            {
                $ErrorActionPreference='SilentlyContinue'
                $rnd = Get-Random -Minimum 1 -Maximum 10
                Start-Sleep -Seconds $rnd
                $tries = $tries - 1
                $max_tries++

                if ($max_tries -gt 100) 
                {
                    Write-Output "Error; Cannot empty the target folder; `t$EmailAddress"
                }
            }
        }
    }
    else 
    {
        #Contact Folder doesn't exist. Let's create it
        try 
        {
            Write-Output "Creating new Contacts Folder called $FolderName"
                
            $ContactsFolder = New-Object Microsoft.Exchange.WebServices.Data.ContactsFolder($service);
            $ContactsFolder.DisplayName = $FolderName
            $ContactsFolder.Save([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::MsgFolderRoot)
        } 
        catch 
        {
            Write-Output "Error; Cannot create the target folder; `t$EmailAddress"
        }
    }
}
Catch
{
    Write-Output "Couldn't connect to the user's mailbox. Make sure the admin account you're using to connect to has App Impersonization permissions"
    Write-Output "Check this link for more info: https://help.bittitan.com/hc/en-us/articles/115008098447-The-account-does-not-have-permission-to-impersonate-the-requested-user"
}
    
return $ContactsFolder

在主脚本中,从 EWS 脚本中捕获返回的变量,例如

$service = & $rootPath\ConnectToEWS\ConnectToEWS.ps1

dot-source 该脚本进入主脚本,因此来自 EWS 的变量。ps1 是主脚本的本地变量,因此您不需要在中执行 return $service那里:

. $rootPath\ConnectToEWS\ConnectToEWS.ps1

并对 CreateContactsFolder 执行相同的操作。ps1 脚本

在全局范围内定义被调用脚本中的重要变量 $global:service$global:ContactsFolder 参见 About_Scopes