Powershell "ExternalEmailAddress can not convert the system.collection.arraylist - powershell

My Goal:
To create in bulk Mail Contact using Powershell.
My program asks me to input manually the ExternalEmailAddres.
When I do so, the program works.
I can not do that because of the big number of Mail contact to create.
I just do not know see where my error is.
Anyone can help? Please.
My code:
$UserCredential = Get-Credential
$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri http://xxx.yyy.com/PowerShell/ -Authentication Kerberos -Credential $UserCredential
Import-PSSession $Session -DisableNameChecking
Import-Module ActiveDirectory
$User = Import-CSV C:\CREATE-MAIL-CONTACT.csv
$Params = #{
Name = $user.Name
ExternalEmailAddress = $User.PrimarySmtpAddress
OrganizationalUnit = "OU=Mail Contacts,DC=xxx,DC=com"
}
New-MailContact #Params
My CSV:
------
Displayname Name PrimarySmtpAddress
John Smith John Smith john.smith#abc.com

What your code is missing is to iterate over each row of your CSV, one way to do that is with ForEach-Object:
Import-CSV C:\CREATE-MAIL-CONTACT.csv | ForEach-Object {
try {
$Params = #{
Name = $_.Name
ExternalEmailAddress = $_.PrimarySmtpAddress
OrganizationalUnit = "OU=Mail Contacts,DC=xxx,DC=com"
}
New-MailContact #Params
}
catch {
# error handling here
Write-Warning $_.Exception.Message
}
}

Related

Connect-MsolService - providing credentials without exposing password in script

I wish to run the below PowerShell script as a scheduled task to pull provisioning logs from Azure AD. However, I do not wish to embed the password. I appreciate this is not a problem specific to PowerShell or Microsoft Online. What technique can I use to not have the password stored as clear text? Thanks
Script credits go to: Pawel Janowicz
$AzureUsername = 'log.reader#tenant.net'
$Password = "xxxxxx"
$SecureString = ConvertTo-SecureString -AsPlainText $Password -Force
$SecuredCreds = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $AzureUsername,$SecureString
$OutputCSV = "$Env:USERPROFILE\desktop\DirSyncProvisioningErrors_$(Get-Date -Format "yyyyMMdd").csv"
###### Connecting ############################################################################################################
Try{
[void] (Connect-MsolService -Credential $SecuredCreds)
$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://outlook.office365.com/powershell-liveid/ -Credential $SecuredCreds -Authentication Basic -AllowRedirection
[void] (Import-PSSession $Session -DisableNameChecking)
}
Catch{
$_.Exception.Message
Read-Host 'Press enter to close the window'
Remove-PSSession $Session
Exit
}
###### Getting errors ########################################################################################################
If(Get-MsolHasObjectsWithDirSyncProvisioningErrors){
Try{
$Errors = Get-MsolDirSyncProvisioningError -All | select DisplayName,ObjectID,ObjectType,ProvisioningErrors
$Results = Foreach ($i in $Errors){
$AllErrors = $i.ProvisioningErrors
$AllErrors | %{
$ErrorItem = $_
Get-AzureADObjectByObjectId -ObjectIds $i.objectid | Foreach{
New-Object PSObject -Property ([ordered]#{
'Displayname' = $i.displayname
'ObjectType' = $i.ObjectType
'Attribute' = $ErrorItem.propertyname
'Conflicting value' = $ErrorItem.propertyvalue
})
}
}
}
}
Catch{
$_.Exception.Message
Read-Host 'Press enter to close the window'
Remove-PSSession $Session
Exit
}
}
###### Results ###############################################################################################################
If($Results){
$Results | Format-Table -AutoSize
#Exporting CSV
$Results | Export-CSV $OutputCSV -NoTypeInformation -Force
}
Remove-PSSession $Session
Thank You Theo for providing your suggestion as a comment. Making this as answer to help other community member.
I have executed the command and getting a display to enter the password rather than it was manually provided in script itself.
$SecuredCreds = Get-Credential -UserName 'log.reader#tenant.net' -Message "Please enter credentials"
$OutputCSV = "$Env:USERPROFILE\desktop\DirSyncProvisioningErrors_$(Get-Date -Format "yyyyMMdd").csv"
###### Connecting ############################################################################################################
Try{
[void] (Connect-MsolService -Credential $SecuredCreds)
$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://outlook.office365.com/powershell-liveid/ -Credential $SecuredCreds -Authentication Basic -AllowRedirection
[void] (Import-PSSession $Session -DisableNameChecking)
}
Catch{
$_.Exception.Message
Read-Host 'Press enter to close the window'
Remove-PSSession $Session
Exit
}
###### Getting errors ########################################################################################################
If(Get-MsolHasObjectsWithDirSyncProvisioningErrors){
Try{
$Errors = Get-MsolDirSyncProvisioningError -All | select DisplayName,ObjectID,ObjectType,ProvisioningErrors
$Results = Foreach ($i in $Errors){
$AllErrors = $i.ProvisioningErrors
$AllErrors | %{
$ErrorItem = $_
Get-AzureADObjectByObjectId -ObjectIds $i.objectid | Foreach{
New-Object PSObject -Property ([ordered]#{
'Displayname' = $i.displayname
'ObjectType' = $i.ObjectType
'Attribute' = $ErrorItem.propertyname
'Conflicting value' = $ErrorItem.propertyvalue
})
}
}
}
}
Catch{
$_.Exception.Message
Read-Host 'Press enter to close the window'
Remove-PSSession $Session
Exit
}
}
###### Results ###############################################################################################################
If($Results){
$Results | Format-Table -AutoSize
#Exporting CSV
$Results | Export-CSV $OutputCSV -NoTypeInformation -Force
}
Remove-PSSession $Session

Powershell - Organizer Email Address

I'm trying to retrieve the email address of the Organizer of a meeting in MS Exchange 2010, using Powershell.
(Get-Mailbox -Identity "John Doe").PrimarySmtpAddress
I get the below error
The operation couldn't be performed because object 'John Doe' couldn't be found on 'xxxxxxxxxxxxxx'
These are for meetings that have just been created, so how can the Organizer not exist?
Edit:
Here's the sequence of events:
Fetch list of calendar events from exchange within specific date range
Fetch email address of Organizer for each event <-- this is where I'm stuck
Full script:
$credential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $username,$password
$session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri http://xxxxxxxxxxxxxxx/PowerShell -Authentication kerberos -Credential $credential
Import-PSSession -Session $session -DisableNameChecking
#Date ranges
$exportDate = Get-Date -Format d
$startTime = (Get-Date).AddDays(-1)
$endTime = (Get-Date).AddDays(+1)
$app = New-Object -ComObject Outlook.Application
$ns = $app.GetNamespace('MAPI')
$calFolder = 9
$calItems = $ns.GetDefaultFolder($calFolder).Items
$calItems.Sort("[Start]")
$calItems.IncludeRecurrences = $true
$dateRange = "[Start] >= '{0}' AND [End] <= '{1}'" -f $startTime.ToString("g"), $endTime.ToString("g")
$calExport = $calItems.Restrict($dateRange)
$exportFile = "D:\file.csv"
$calExport | select Subject, StartInStartTimeZone, EndInEndTimeZone, Duration, Organizer, RequiredAttendees, OptionalAttendees, Location | sort StartUTC -Descending | Export-Csv $exportFile
$exportData = Import-Csv $exportFile
foreach ($line in $exportData)
{
$emailAddress = $line.Organizer
$emailAddress = (Get-Mailbox -Identity $line.Organizer).PrimarySmtpAddress
$line | Add-Member -Membertype Noteproperty -Name OrganizerEmail -Value $emailAddress
[array]$csvData += $line
$emailAddress = $null
}
Remove-PSSession $session
Please assist!
Here's what I used to get the Organizers email address
Get-ADUser -Filter {SamAccountName -like "*John Doe*"}

Powershell invoke-command $input

I have a trouble.. Can someone help me?
Here is my Code :
$A = '123'
$servers = 'computer1'
$Properties = [ordered]#{A = $A
servers = $servers
}
$MyObject = New-Object -TypeName PSObject -Property $Properties
$MyObjec
...
$result = Invoke-Command -ComputerName Machine -UseSSL -InDisconnectedSession -ScriptBlock {
$MyObject.A
$MyObject.servers
$env:computername
}`
–InputObject $MyObjec -port 5986 -ConfigurationName myEndpoint -SessionOption #{OutputBufferingMode="Drop"} -Credential $credential | Receive-PSSession
$result
Question:
Why the $result doesn't show anything about $MyObject?
It only show $MyObjec (not in the invoke-command) and $env:computername (in the invoke-command)
How can I fix it?
P.S this is really what I want to make,
I want to get into multiple machine which in 6 different AD in the same time, but they should use different username,
and I need $A in the remote machine to deal another thing.
$A = '123'
$servers = 'computer1'
$Properties = [ordered]#{A = $A
servers = $servers
}
$MyObject = New-Object -TypeName PSObject -Property $Properties
$MyObjec
...
#Add
$servers#{'Machine1','Machine2','Machine3'}
Foreach ($servers in $servers) {
Star-Job {
$username = $servers+'account'
$password = $password
$credential = ....($username,$password)
$result = Invoke-Command -ComputerName $servers -UseSSL -InDisconnectedSession -ScriptBlock {
$MyObject.A
$MyObject.servers
$env:computername
}`
–InputObject $MyObjec -port 5986 -ConfigurationName myEndpoint -SessionOption #{OutputBufferingMode="Drop"} -Credential $credential | Receive-PSSession
$result
}
}
I will try -Argument-List and param{}
Beacase I try Start-Job with -Argument-List and $Using, there have an error.
Thank u for your reply!
Because the part within -Scriptblock { ... } gets executed on the remote system and has therefore no access to the variables on the local system (different scope).
You can change that by passing the variables to the remote system using the -Argument-List parameter like this:
Invoke-Command -ComputerName Machine -ArgumentList $MyObject -ScriptBlock {
param($MyObject)
$MyObject.A
}
Or use $using: to get access to the locally defined variables like that:
Invoke-Command -ComputerName Machine -ScriptBlock {
$using:MyObject.A
}

PowerShell Get Users Email Address To Exchange

Trying to do an auto ligation hold script using an ad synced group up to Azure. Would anyone be able to help with the below?
I'm trying to get all my users from the MsolGroup by doing a return of the MsolGroupMembers, I would like to return the users then from that I need to get their UPN/Email Address so I can pipe it into an exchange online command to turn litigation hold on for each of them users from the group.
Import-Module MSOnline
$user="removed"
$file = "removed"
$password = Get-Content $File | ConvertTo-SecureString
$cred = New-Object System.Management.Automation.PsCredential($user,$password)
Connect-MsolService -Credential $cred
$UserCredential = Get-Credential -Credential $cred
$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://outlook.office365.com/powershell-liveid/ -Credential $UserCredential -Authentication Basic -AllowRedirection
Import-PSSession $Session
$usersOfGroup = Get-MsolGroupMember -GroupObjectId removedID -All
foreach ($user in $usersOfGroup)
{
$mailbox = Get-Mailbox $user.EmailAddress
Write-Output $mailbox
if ($mailbox.LitigationHoldEnabled -eq $false -and $mailbox.RecipientTypeDetails -eq "UserMailbox")
{
Write-Output "Current mailbox: " $mailbox.UserPrincipalName
Set-Mailbox -Identity $mailbox.UserPrincipalName -LitigationHoldEnabled $true -LitigationHoldDuration 2555 -WarningAction SilentlyContinue
}
}
Remove-PSSession $Session
This should do the trick.
#Useful Microsoft documentation
#https://technet.microsoft.com/en-us/library/dn767952(v=exchg.160).aspx
#Connect to Exchange Online
Import-Module MSOnline
$O365Cred = Get-Credential
$O365Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri "https://ps.outlook.com/powershell" -Credential $O365Cred -Authentication Basic -AllowRedirection
Import-PSSession $O365Session -AllowClobber
Connect-MsolService -Credential $O365Cred
#Filter mailboxes for the HR Department, pipe to the set litigation command for 365 days
Get-Recipient -RecipientTypeDetails UserMailbox -ResultSize unlimited -Filter 'Department -eq "HR"' | Set-Mailbox -LitigationHoldEnabled $true -LitigationHoldDuration 365
Remove-PSSession -Id $O365Session.Id

PowerShell Script Balloon tip does not show $variable output

I have a script that is related to exchange online PowerShell. This script moves mail item from deleted mailbox to a new mailbox and once completed shows the balloon tip with the status. The Balloon tip script has a $variable which does not show the right output.
Script is as below:-
$User = "Admin#domain.com"
$mypass = cat "C:\pass.txt" | convertTo-securestring -AsPlainText -Force
$mycreds = New-Object System.Management.Automation.PSCredential ("$User", $mypass)
$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://outlook.office365.com/powershell-liveid/ -Credential $mycreds -Authentication Basic -AllowRedirection
Import-PSSession $Session
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.VisualBasic")
$DeletedUser = [Microsoft.VisualBasic.Interaction]::InputBox("Enter Deleted Mailbox Email Address", "Deleted Mailbox")
$UserMailbox = [Microsoft.VisualBasic.Interaction]::InputBox("Enter Destination Mailbox Email Address", "Destination Mailbox")
$DeletedGUID = Get-Mailbox -SoftDeletedMailbox $DeletedUser | fw guid
$DestinationGUID = Get-Mailbox $UserMailbox | fw guid
New-MailboxRestoreRequest -SourceMailbox $DeletedGUID -TargetMailbox $DestinationGUID -AllowLegacyDNMismatch
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
$Status = Get-MailboxRestoreRequest | Get-MailboxRestoreRequestStatistics | FW StatusDetail
$objNotifyIcon = New-Object System.Windows.Forms.NotifyIcon
$objNotifyIcon.Icon = (join-path ([environment]::GetFolderPath('MyDocuments')) "EXO.ico")
$objNotifyIcon.BalloonTipIcon = "Error"
$objNotifyIcon.BalloonTipText = "Mail Item move has $Status"
$objNotifyIcon.BalloonTipTitle = "Operation $Status"
$objNotifyIcon.Visible = $True
$objNotifyIcon.ShowBalloonTip(50000)
The Balloon tip cannot parse the variable. Can anyone help?
Thanks in Advance!