Search code examples
powershellscriptingexchange-serverpowershell-remotingexchange-server-2010

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:

error message

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


Solution

  • 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