Trying to create a powershell script to Delete Exchange Emails - powershell

So I am working on a powershell script that will delete suspected phishing emails from emails mailboxes across the org that match a certain subject line and date. To have the script work i need it to loop at the Get-ComplianceSearch -Identity xxxx part until the status equals complete, but I cannot seem to get it to work and I am not the greatest at powershell. Here is what I have so far:
#it is probably easiest to open this script in Powershell ISE so you can edit the parameters that will match whatever email needs to be deleted
Get-ExecutionPolicy
Set-ExecutionPolicy RemoteSigned
#You will enter your main account username and password(not su, since it has to be an active mail account)
$LiveCred = Get-Credential
$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri http://XXX-XXXX/powershell/ -Credential $LiveCred
Import-PSSession $Session -AllowClobber
#You should now be logged into XXX-XXXX via powershell
#The following will work with the Compliance Center in Exchange to search through all mailboxes and delete a specific email as long as it matches the tags
New-ComplianceSearch `
-Name Test9 `
-ExchangeLocation All `
-ContentMatchQuery 'subject:"INTRODUCING: A new way to consult Cisco experts" AND sent:08/01/2022'
#It should run and you should see the name of the job and that it has NotStarted
Start-ComplianceSearch -Identity Test9
#Just keep entering this next command until you see the status as completed
$GetResults = Get-ComplianceSearch -Identity Test9
Get-ComplianceSearch -Identity Test9
if (Get-ComplianceSearch | Where-Object {$GetResults_.Status -eq "InProgress";})
{
Get-ComplianceSearch -Identity Test9
}
else
{
New-ComplianceSearchAction -SearchName Test9 -Purge
}
exit
So you see the part where it says "#Just Keep entering this next command until you see the status as completed" is the part that I am trying to automate. Normally without scripting you would just keep running the Get-ComplianceSearch - Identity xxxx until you see completed then run the New-ComplianceSearchAction to purge the emails, but in the code posted above I have been trying to thow in an if loop statement to have it continually run that until the status is completed.

Related

Bulk assigning new SMTP addresses & new company name with powershell based on csv file

I have to create a Powershell script that assigns a new main SMTP address to users of a csv file. They also need some other addresses. Besides that, those users need to change their company name. I am really new to all that stuff and tried to cobble some stuff together which wouldn´t work and it´s driving me crazy. :(
If you need more info please tell me. :)
Here is the code I´ve tried so far:
$Cred = Get-Credential
$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://ps.outlook.com/powershell -Credential $Cred -Authentication Basic -AllowRedirection
Import-PSSession $Session
Connect-AzureAD -Confirm
#Assigning addresses & company
Import-CSV "C:\CSVPowershell\userstest.csv" | ForEach {
Set-Mailbox $_.Identity -EmailAddresses #{add= $_.MainEmailAddress}
Set-AzureADUser -ObjectId $_.Identity -CompanyName $_.Company
}
#close
Remove-PSSession $Session
Please check the below workaround:
CSV file
UserName, Mailform1, Mailform2
aaa test, atest#companyname.com , atest#companyname_Dept.com
bbb test, btest#companyname.com , btest#companyname_Dept.com
ccc test, ctest#companyname.com , ctest#companyname_Dept.com
PowerShell Script
Note: In your code, you are missing the operation add. Either you have to use Add / Remove in your script to perform the related operation.
Import-CSV "C:\Users\Admin\UserEmailAddress.csv" | ForEach
{
# Changing the Main Email address into your required Email.
#Adding Multiple Email addresses (here 2 Email addresses)
Set-Mailbox $_.UserName -EmailAddresses #{add= $_.Mailform1, $_.Mailform2}
}
Suppose you are trying to add only one SMTP address to User follow the below:
CSV File
UserName, Mailform1
aaa test, atest#companyname.com
bbb test, btest#companyname.com
ccc test, ctest#companyname.com
PowerShell Script
Import-CSV "C:\Users\Admin\UserEmailAddress.csv" | ForEach
{
# Changing the Main Email address into your required Email.
Set-Mailbox $_.UserName -EmailAddresses #{add= $_.Mailform1}
}
Refer here for more information

Skype for business Move-CsUser command prompts for sign in after moving 10-15 users and doesn't accept the credential

I am trying to move bulk users(900+) from SfB On-Premise to SfB-Online using Move-CsUser PowerShell Cmdlet. Below is the code snippet:
$INP = Get-Content -Path <txt file path>
$SESSION = New-CsOnlineSession
Import-PsSession $SESSION -AllowClobber
foreach($USER in $INP)
{
Move-CsUser -Identity $USER -Target 'sipfed.online.lync.com' -ProxyPool 'ProxyPool_FQDN' -UseOAuth -Confirm:$False
}
It works fine for 15-20 users and moves them successfully to SfBOnline however, after that it prompts for Office admin credentials again saying "We couldn't sign you in. Please try again" and doesn't accept the credential anymore. Keeps prompting the same.
NOTE:
I have followed all the possibilities from Technet with no luck.
Disabled MFA from the global admin Office account - No luck.
Tried using -UserList parameter to move bulk users - Same issue.
Any help would be much appreciated.

Add 365 License with Powershell Script in task Scheduler

I'm trying to license my users in office365 with a powershell script in tassk scheduler.
First : I have a script to create some users in my domain controller. This script add content (userprincipalname) in a txt file. Example :
- Create user : John Smith
- The script add this in the txt file : john.smith#domain.com
Second : Another script try to license this user. This script are connecting to MSOLService with this cmdlets :
$LOGIN = "svc-365#domain.com"
$MDP = Get-Content "C:\Script\SVC-365.txt" | ConvertTo-SecureString
$Cred = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $LOGIN,$MDP
$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://outlook.office365.com/powershell-liveid/ -Credential $UserCredential -Authentication Basic -AllowRedirection
Connect-MsolService -Credential $UserCredential
Import-PSSession $Session -AllowClobber
$User = Get-Content "C:\Script\CreationMail.txt"
foreach ($i in $User) {
Set-MsolUser -UserPrincipalName $i -UsageLocation "FR"
Set-MsolUserLicense -UserPrincipalName $i -AddLicenses "tenantudl:STANDARDWOFFPACK_FACULTY"
}
This script is perfectly working when I manually execute in powershell ISE, but not working in the task scheduler...
If somebody can help me, I will be grateful to him ! :)
Thanks for help !
Which user runs the script in your task?
With credentials that you have saved as a hash value in a text file it can only be decrypted by the user that made the file.
So if you made that file with your user, but the user that is setup to run the task is not the same, say a service account, it cannot decrypt the password and the login will fail.
As a note, I would highly recommend Microsofts new feature to assign licenses by group membership instead of doing it by scripts as Microsoft changes things an scripts break.
It is in preview right now and require an AD Basic license on your account or higher, you can activate a free trial of the EMS license pack in Azure and and this will be enough to activate the feature.
For TaskScheduler scripts, you need to set it up correctly.
Set the "Program/Scritp" to Powershell.exe
Set the "Add arguments" to -ExecutionPolicy Bypass C:\Temp\AddLicence.ps1
(Optional) If your script requires any params then you will need to add them and your "Add Arguments" field ends up as -ExecutionPolicy Bypass C:\Temp\AddLicence.ps1 -Users C:\temp\users.csv -LicenceType C:\temp\O365.txt
I find the problem ! :D
In my task, it was domain\administrator who run the task but this account havn't the right to connect to office365 and he havn't the admin right on Exchange-online. I was changed this account with another who have the right on 365 and it's WORK !! :D
Thank's for help guys !

Why can I pass credentials to a regular user but not a local administrator?

So basically I've been working forever on a PS remote self help script that originally was thought to be simple: Restart the spooler service, clear the queue, and print a test page on the default printer. Getting there however hasn't been so easy, due to security issues. After some hours, I was able to get my local user test account to accept the credentials of my domain administrator. I thought all was well, until I tried to replicate it on a local administrator's account, in which event access was denied. This is sort of important, because the majority of the accounts we will be deploying the script on are local admins. I suspect it may be a UAC issue, but I have no idea what I should do to work around the problem. Here's what I'm working with currently:
$v = [bool](([System.Security.Principal.WindowsIdentity]::GetCurrent()).groups -match "S-1-5-32-544")
If ($v = "False")
{
$password = "ElPassword" | ConvertTo-SecureString -asPlainText -Force
$username = "Domainname\Username"
$credential = New-Object System.Management.Automation.PSCredential($username,$password)
invoke-command {Stop-Service spooler} -comp $env:ComputerName -cred $credential
Remove-Item C:\Windows\System32\spool\PRINTERS\* -Force
invoke-command {Start-Service spooler} -comp $env:ComputerName -cred $credential
$printer = Get-WmiObject -Query " SELECT * FROM Win32_Printer WHERE Default=$true"
$PrintTestPage = $printer.PrintTestPage() } Else
{ Stop-Service spooler
$printer = Get-WmiObject -Query " SELECT * FROM Win32_Printer WHERE Default=$true"
Start-Service spooler
$PrintTestPage = $printer.PrintTestPage() }
The first thing this does is check if the current PS session is being run as admin; seeing as the users don't actually see the PowerShell window or script, and we recently started using the RMM tool, I'm still trying to figure out under what conditions the tool runs PS elevated - the documentation says that it runs with the credentials of the logged in user, but that doesn't seem to be the case, as an hour with their support team told me that the reason the script wasn't doing it's job on any admin accounts was because it wasn't being elevated. Anyways, after the check, it either passes credentials for the commands or it doesn't. This script seems to handle every scenario but that of a local admin account running PS non elevated. In that event, it simply denies me access where the exact same creds give me access on a regular user account. I'm not sure how to even approach this problem, so any help is appreciated.

Unlocking an AD user with Powershell

I’m new to Powershell and am struggling to make a script work. I’ve read many articles here on Overflow and elsewhere and don’t see what I’m doing wrong. Any help would be appreciated.
I'm trying to create a script that will unlock an AD user remotely while I'm logged-on to may computer as a local admin. Here's my script:
Import-module Activedirectory
New-PSSession -ComputerName <Remote ComputerName> -Credential
<domain admin credential>
Import-Module Activedirectory
Unlock-ADAccount
Read-host “Press any key”
I try to execute this from my computer logged-on as a local admin, but pass domain admin credentials. The script is run as an administrator in Powershell. After I enter my domain password and indicate which user I want to unlock, the message I get is: “Insufficient access rights to perform the operation”.
If I run this code interactively in Powershell, line by line, it will unlock the account. If I run a script asking only to see if the user is locked, it will give me an answer. If I run the above script from my computer logged-on as the domain admin, it will run and unlock the user.
I don’t understand why it will not run when I’m logged-on as local admin, given that I’m passing domain admin credentials. Any help would be appreciated.
You're creating a PSSession, but not using it. Try something like this (untested):
$computer = "test1"
$cred = Get-Credential
$user = Read-Host User to unlock
$sess = New-PSSession -ComputerName $computer -Credential $cred
Invoke-Command -Scriptblock { param($ADuser) Import-Module Activedirectory; Unlock-ADAccount -Identity $ADuser } -ArgumentList $user -Session $sess
Read-host “Press any key”
Although you could create a PSSession, if you have RSAT installed and have access to the ActiveDirectory module there is no need to do that. Instead, just use the credential parameter on each AD cmdlet. For instance, to unlock a user account using alternate credentials, use the following:
Unlock-ADAccount -Identity username -Credential (get-credential)