I have created PowerShell script to gather all users mailbox detail such as "PrimarySmtpAddress, Identity, displayname" on Exchange On-Premises. I am trying to run this command from powershell:
$UserNameInSmtpFormat = Get-Mailbox -Identity $User -ErrorAction Stop | Select PrimarySmtpAddress, Identity, displayname
This command is working fine (powershell.exe "c:\pstest\readUsers.ps1" 'Administrator@domain.com' 'Password' 'users.txt' 'http://Exchange/PowerShell/'
) Which is save as 'testok.cmd'
In this command I am getting error:- (powershell.exe "c:\pstest\readUsers.ps1" 'User@domain.com' 'Password' 'users.txt' 'http://Exchange/PowerShell/'
) This is saved as 'testproblem.cmd'
I am getting the below error
Error:- When I am giving the administrator account credential then it is working fine but when I am trying to gather the same by using Normal 'User' Credential then i am getting below error;
The operation couldn't be performed because object 'user@domain.com' couldn't be found on 'dc.Domain.com'..Exception.Message
Below is the Script
( #Constant Variables
$Office365AdminUsername = $args[0]
$Office365AdminPassword = $args[1]
$UserNamesFile = $args[2]
$connectionUri = $args[3]
#Main
Function Main {
#Remove all existing Powershell sessions
Get-PSSession | Remove-PSSession
#Encrypt password for transmission to Office365
$SecureOffice365Password = ConvertTo-SecureString -AsPlainText $Office365AdminPassword -Force
#Build credentials object
$Office365Credentials = New-Object System.Management.Automation.PSCredential $Office365AdminUsername, $SecureOffice365Password
Write-Host "Credentials object created"
#Create remote Powershell session
$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri $connectionUri -Credential $Office365credentials -Authentication Kerberos –AllowRedirection
Write-Host "Remote session established"
#Check for errors
if ($Session -eq $null){
Write-Host "Invalid creditials"
}else{
Write-Host "Login success"
#Import the session
Import-PSSession $Session
}
try {
Write-Host "SMTPADDRESS"
Foreach($User in (get-content $UserNamesFile))
{
Write-Host "mailboxIdentity : $User"
$UserNameInSmtpFormat =Get-Mailbox -Identity $User -ErrorAction Stop | Select PrimarySmtpAddress, Identity, displayname
$UserNameInSmtpFormat
}
Write-Host "ENDSMTPADDRESS"
}
catch {
write-host "EXCEPTION"
write-host "`r`n $_.Exception.Message"
}
finally {
Exit-PSSession
Remove-PSSession $Session
}
}
# Start script
. Main
)
Solution was "Role Permission rights" and it is solved by giving the same to the user from which I was trying to get the mailbox detail. I have assigned the "Mail Recipient" role to the user from Permission tab in ECP.
Thank you.