简体   繁体   中英

Error when using powershell while remoting in Exchange 2010

I'm trying to script some of our onboarding processes, and in that I'm trying to enable mailboxes in exchange. I have some lines that seem to work outside of the script, but throw an error inside the script. Can you help me out?

The codes is as follows:

Function enableExchangeMailbox {
#Grabs admin credentials from xml document and imports it, setting the variable
$UserCredential = Import-Clixml 'SecureCredentials.xml'

#Sets up a new remote session
$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri http://mxex2010.minnetronix.com/Powershell -Authentication Kerberos -Credential $UserCredential

#Enable the mailbox on the server
Invoke-Command -Session $Session -ScriptBlock {
    Enable-Mailbox -Identity $global:userName -Database $global:exchangeDatabase
}

#cleanup
Remove-PSSession $Session
}

The error that it throws is this:

错误信息

The global variable for "identity" was set earlier in the script and works in my other functions. Any help would be appreciated.

The scriptblock argument to Invoke-Command will be running on a remote computer and won't have access to the global scope of the caller.

Pass $userName as a parameter argument to the function, and pass it to the remote session with the using: qualifier:

Function enableExchangeMailbox {

    param($userName)

    #Grabs admin credentials from xml document and imports it, setting the variable
    $UserCredential = Import-Clixml 'SecureCredentials.xml'

    #Sets up a new remote session
    $Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri http://mxex2010.minnetronix.com/Powershell -Authentication Kerberos -Credential $UserCredential

    #Enable the mailbox on the server
    Invoke-Command -Session $Session -ScriptBlock {
        Enable-Mailbox -Identity $using:userName -Database $global:exchangeDatabase
    }

    #cleanup
    Remove-PSSession $Session
}

The call like:

enableExchangeMailbox -userName $userName

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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