Reputation: 185
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.
Upvotes: 0
Views: 166
Reputation: 174900
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
Upvotes: 1