PowerShell Get Users Email Address To Exchange - powershell

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

Related

Hide specific emails From Address Lists

I try to hide specific emails From Address Lists in 365.
Import-Module MSOnline
$TenantUname = "****"
$TenantPass = cat "C:\****.key" | ConvertTo-SecureString
$TenantCredentials = new-object -typename System.Management.Automation.PSCredential -argumentlist $TenantUname, $TenantPass
$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://ps.outlook.com/powershell/ -Credential $TenantCredentials -Authentication Basic -AllowRedirection
Import-PSSession $Session -AllowClobber
Connect-MsolService -Credential $TenantCredentials
ForEach ($mailbox in (Import-Csv c:\email.csv))
{
Set-Mailbox -Identity $mailbox.Identity -HiddenFromAddressListsEnabled $True
}
In my CSV file identity is the emails of users.
But from some reason, this is not work
I will be very happy to help.

Remote execution on Exchange server failed

I want to remote enable the email-address-policy for a single mailbox on a exchange server (2010).
I can do this:
$samaccountname = $args[0] # gets sam from command line
$EncryptedPassword = Get-Content -Path "C:\temp\password.txt"
$SecurePassword = ConvertTo-SecureString -String $EncryptedPassword
$Credential = New-Object System.Management.Automation.PSCredential "xyzdom\sco_admin", $SecurePassword
$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri http://xyzexcas01/PowerShell/ -Authentication Kerberos -Credential $Credential
Import-PSSession $Session -AllowClobber -CommandName Set-Mailbox
Get-Mailbox -Identity $samaccountname | Set-Mailbox -EmailAddressPolicyEnabled $True
Remove-PSSession $Session
It works if I open a powershell as administrator on the Orchestrator server. Then it executes the command on the exchange server as it should.
But the script does not work if Orchestrator tries to execute it. I do not know what settings Orchestrator uses when executing it. But I have a similar script, which is working with Orchestrator.
$samaccountname = $args[0] # gets sam from command line
$EncryptedPassword = Get-Content -Path "C:\temp\password.txt"
$SecurePassword = ConvertTo-SecureString -String $EncryptedPassword
$Credential = New-Object System.Management.Automation.PSCredential "xyzdom\sco_admin", $SecurePassword
$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri http://xyzexcas01/PowerShell/ -Authentication Kerberos -Credential $Credential
Import-PSSession $Session -AllowClobber -CommandName enable-mailbox
$username_param = $samaccountname
$emailalias_param = $samaccountname
Invoke-Command -ArgumentList $username_param,$emailalias_param –session $Session -scriptblock {
param($username_exc, $alias_exc)
Enable-Mailbox -Identity $username_exc -Alias $alias_exc -DomainController 'xyzdc01.zfpdom.zfp'
}
Remove-PSSession $Session
This script makes a new mailbox. It is working.
Can anyone show me a solution for the first script? I am totally new in powershell so I can't figure it out. Maybe someone can change my first script to do it with this Invoke-Command scriptblock. I am sure, then it will work.
Thank you.
Greetings
Replace the commands inside the invoke-command, and the variables accordingly. Also, add the get-mailbox commandlet to the session. I am not able to try it, though, so I added the -verbose and -whatif switches as a failsafe. Note that if the samaccountname variable is empty, the Set-Mailbox will run on all mailboxes. The script can be tested standalone before running it in the Orchestrator.
$samaccountname = $args[0] # gets sam from command line
$EncryptedPassword = Get-Content -Path "C:\temp\password.txt"
$SecurePassword = ConvertTo-SecureString -String $EncryptedPassword
$Credential = New-Object System.Management.Automation.PSCredential "xyzdom\sco_admin", $SecurePassword
$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri http://xyzexcas01/PowerShell/ -Authentication Kerberos -Credential $Credential
Import-PSSession $Session -AllowClobber -CommandName Set-Mailbox,Get-Mailbox
Invoke-Command -ArgumentList $samaccountname –session $Session -scriptblock {
param($username_exc)
Get-Mailbox -Identity $username_exc| Set-Mailbox -EmailAddressPolicyEnabled $True -verbose -whatif # remove the -whatif to perform changes
}
Remove-PSSession $Session
Another working solution I have found out:
#Parameter Laden
$samaccountname = $args[0] # $samaccountname wird übergeben
$EncryptedPassword = Get-Content -Path "C:\temp\password.txt"
$SecurePassword = ConvertTo-SecureString -String $EncryptedPassword
$Credential = New-Object System.Management.Automation.PSCredential "xyzdom\sco_admin", $SecurePassword
$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri http://xyzexcas01/PowerShell/ -Authentication Kerberos -Credential $Credential
Import-PSSession $Session -AllowClobber -CommandName Set-Mailbox,Get-Mailbox
Get-Mailbox -Identity $samaccountname | Set-Mailbox -EmailAddressPolicyEnabled $True
Remove-PSSession $Session

PowerShell script to enable email forwarding for 50 users

Here is the code, I need to import the CSV and enable forward to some other email address from office 365
$creds = Get-Credential
$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://outlook.office365.com/powershell-liveid/ `
-Credential $creds -Authentication Basic -AllowRedirection
Import-Module MSOnline
Connect-MsolService -Credential $creds
Import-PSSession $Session
$emails = Import-CSV "C:\Users\Lev\Desktop\Email.csv"
ForEach($mail in $emails)
{
Set-Mailbox $mail.Work_email -ForwardingSmtpAddress $mail.home_email -DeliverToMailboxAndForward $true
}
I fixed the code and now this is a working code.
My comment as proper answer:
You need to change the line
Set-Mailbox -Identity $email.Work_email -DeliverToMailboxAndForward $true $email.home_email -ForwardingSMTPAddress $true
to
Set-Mailbox -Identity $email.Work_email -DeliverToMailboxAndForward $true -ForwardingSMTPAddress $email.home_email
See example 1 in Set-Mailbox
$emails = Import-CSV C:\path\to\csv.csv
ForEach($email in $emails)
{
Set-Mailbox $email.email1 -ForwardingAddress $email.email2 -DeliverToMailboxAndForward $true
}

new-pssession in scheduled job

I want to write script that enables mail forwarding for some user on exchange server and turn it off at specified time.
But when $script_bloc executes in job: New-PSSession returns null without any error.
I can pass to New-PSSession hardcoded credentials, and in that case it works as I expect, but I don't want to do it because my passwords can expire at the moment when job starts.
Any idea why New-PSSession doesn't work in a job? And how to make it work?
$user = 'username1'
$fwdto = 'username2'
$remove_date = '19.04.2018 08:33:00'
Set-Mailbox -Identity $user -DeliverToMailboxAndForward $true -ForwardingAddress $fwdto
$job_date=[datetime]::Parse($remove_date)
$job_date=[datetime]::Now.AddSeconds(20) #for test
$trigger = New-JobTrigger -Once -At $job_date
$job_name="rfw_" + $user
$script_block = {
param($user_param,$job_name_param)
Start-Transcript $env:USERPROFILE\jobs\$job_name_param.log -Verbose -Append
$PSOptions = New-PSSessionOption –SkipCACheck –SkipRevocationCheck -SkipCNCheck
$sess = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri http://exchange.company.org/PowerShell/ –SessionOption $PSOptions
Import-PSSession $sess | Out-Default
Set-Mailbox -Identity $user_param -DeliverToMailboxAndForward $false -ForwardingAddress $null | Out-Default
Remove-PSSession $sess | Out-Default
Unregister-ScheduledJob $job_name_param -Force
Stop-Transcript
}
Register-ScheduledJob -Trigger $trigger -Name $job_name -ScriptBlock $script_block -ArgumentList $user, $job_name
When you register a job in PowerShell, its created as a Task in Task scheduler under Microsoft\Windows\PowerShell folder. So any actions which requires authentication inside a task will fail with access denied error if the credentials are not explicitly mentioned.
You can test it by having a Try{} Catch{} in your ScriptBlock.
You can achieve your task by using -Credential parameter for Register-ScheduledJob cmdlet. Then the task will use that credential for any opration,
$script_block = {
param($user_param,$job_name_param)
Try{
Start-Transcript $env:USERPROFILE\jobs\$job_name_param.log -Verbose -Append
$PSOptions = New-PSSessionOption –SkipCACheck –SkipRevocationCheck -SkipCNCheck
$sess = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri http://exchange.company.org/PowerShell/ –SessionOption $PSOptions -ErrorAction Stop
$sess > C:\Session.log
Import-PSSession $sess | Out-Default
Set-Mailbox -Identity $user_param -DeliverToMailboxAndForward $false -ForwardingAddress $null | Out-Default
Remove-PSSession $sess | Out-Default
Unregister-ScheduledJob $job_name_param -Force
Stop-Transcript
}
Catch{
$_ > c:\Error.log
}
}
Use above ScriptBlock with and Without -Credetial parameter to Register-ScheduleJob cmdlet. You can see the difference.

Powershell command not found after PSSession Import

I'm trying to add external contact to MS Exchange with Powershell.
$username = "username#domain.com"
$password = "password"
$secure_password = $password | ConvertTo-SecureString -AsPlainText -Force
$credencial = New-Object System.Management.Automation.PSCredential ($username, $secure_password)
$session_name = "office365_session"
foreach($tmp in Get-PSSession){
if ($tmp.Name -eq $session_name) {
$opened_session = Get-PSSession -Name $session_name
}
}
if ($opened_session -eq $null) {
$opened_session = New-PSSession -Name $session_name -ConfigurationName Microsoft.Exchange -ConnectionUri "https://ps.outlook.com/powershell/" -Credential $credencial -Authentication Basic -AllowRedirection -WarningAction SilentlyContinue -ErrorAction Stop
Import-PSSession $opened_session -AllowClobber -WarningAction SilentlyContinue -ErrorAction Stop -DisableNameChecking | Out-Null
}
New-MailContact -Name "test" -DisplayName "test user" -ExternalEmailAddress "some.email#mail.com" -FirstName "Test" -LastName "User"
But "New-MailContact" command is not found and throws an error:
New-MailContact : The term 'New-MailContact' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
How to run that "New-MailContact" command? Maybe I need import something else or maybe there is another way to add contact?
You missed out the crucial part which is creating a session to the Exchange box therefore your import doesn't work.
Here is an example for O365
$session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://ps.outlook.com/powershell -Credential $credencial -Authentication Basic –AllowRedirection;
only then you can run
Import-PSSession $session -AllowClobber -WarningAction SilentlyContinue -ErrorAction Stop -DisableNameChecking | Out-Null
New-MailContact -Name "test" -DisplayName "test user" -ExternalEmailAddress "some.email#mail.com" -FirstName "Test" -LastName "User"