office 365 bulk add shared mailbox members via powershell - powershell

I have already created the shared mailbox in o365.
Now I need to bulk import members to these shared mailboxes.
How to do it in powershell ?
I want to do something like this
$users = import-csv -Path "C:\path\members.csv" -Delimiter ";"
Foreach ($user in $users){
Add-mailboxpermission -identity "name of the shared mail box" -user $user -accessrights FullAccess
}
any thoughts ?

Connecting to Office365 would be a good first step:
$AdminUsername = "admin#your-domain.onmicrosoft.com"
$AdminPassword = "YourPassword"
$AdminSecurePassword = ConvertTo-SecureString -String "$AdminPassword" -AsPlainText -Force
$AdminCredential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $AdminUsername,$AdminSecurePassword
$ExchangeSession = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri "https://outlook.office365.com/powershell-liveid/" -Credential $Admincredential -Authentication "Basic" -AllowRedirection
Import-PSSession $ExchangeSession
After you have a session you can play with the functions and add some logic:
$access = "FullAccess"
$mailbox = Get-Mailbox -Identity YourMailbox
$identity = $mailbox.UserPrincipalName
$permissions = Get-MailboxPermission -identity $identity
$users = Import-Csv -Path "C:\path\members.csv" -Delimiter ";"
foreach($user in $users){
try{
$setPermissions = Add-MailboxPermission -Identity $identity -User $user -AccessRights $access
Write-Host "Successfully added permissions for $user" -ForegroundColor Green
}catch{
Write-Host "Failed to add permissions for $user" -ForegroundColor Red
}
}
Remember to add users based on UserPrincipalName

Related

how can i add credentials in New-PSSession? everytime i face the login-prompt (powershell)

im trying to schedule a powershellscript which changes the calender permissions of users within the group "kalender_rechten" to limited details. however im facing the login prompt on new-pssesion. how can i add the $credObject into New-PSSession, without the loginprompt?
#Start transcript
Start-Transcript -Path C:\temp\Set-DefCalPermissions.log -Append
#get credentials to authenticate
$username = "test.onmicrosoft.com"
$pwdTxt = Get-Content "C:\test\test\pw.txt"
$securePwd = $pwdTxt | ConvertTo-SecureString
$credObject = New-Object System.Management.Automation.PSCredential -ArgumentList
$username, $securePwd
#authenticate admin office365
get-credential $credObject
#create session Office365
$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri
https://outlook.office365.com/powershell-liveid/ -Credential $credObject -Authentication
Basic –AllowRedirection
$credObject
#import Office365/exchange commands to PowerShell console
Import-PSSession $Session
# Get all user mailboxes
$Users = Get-DistributionGroupMember -Identity "Kalender_rechten"
# Permissions
$Permission = "LimitedDetails"
# Calendar name languages
$FolderCalendars = #("Agenda", "Calendar", "Calendrier", "Kalender")
# Loop through each user
foreach ($User in $Users) {
# Get calendar in every user mailbox
$Calendars = (Get-MailboxFolderStatistics $User.Identity -FolderScope Calendar)
# Loop through each user calendar
foreach ($Calendar in $Calendars) {
$CalendarName = $Kalender_rechten
# Check if calendar exist
if ($FolderCalendars -Contains $CalendarName) {
$Cal = $User.Identity.ToString() + ":\$CalendarName"
$CurrentMailFolderPermission = Get-MailboxFolderPermission -Identity $Cal - User Default
# Set calendar permission / Remove -WhatIf parameter after testing
Set-MailboxFolderPermission -Identity $Cal -User Default -AccessRights
$Permission -WarningAction:SilentlyContinue -WhatIf
# Write output
if ($CurrentMailFolderPermission.AccessRights -eq "$Permission") {
Write-Host $User.Identity already has the permission
$CurrentMailFolderPermission.AccessRights -ForegroundColor Yellow
}
else {
Write-Host $User.Identity added permissions $Permission -ForegroundColor Green
}
}
}
}
Stop-Transcript

Get SharePoint online Term set and create term if does not exist in PowerShell

My term store hierarchy in SharePoint online admin:
Organisation
Org Units
Department
Test Facilities Management
Location
Test location
I would like to search for 'Test Facilities Management' only in 'Department' and create it under 'Department' if it does not exist.
I have the below PowerShell script below to check and create a term in SharePoint Online. But I would like to check only in 'Department' for the term. I am not having any success. Any help is greatly appreciated.
$TermGroupName = "Organisation"
$TermSetName = "Org Units"
$TermName="Test Facilities Management"
If(-Not(Get-PnPTerm -Identity $TermName -TermSet $TermSetName -TermGroup $TermGroupName -Recursive -ErrorAction SilentlyContinue))
{
#Create new Term
New-PnPTerm -Name $TermName -TermSet $TermSetName -TermGroup $TermGroupName
}
It seems that you want to create a subterm.
My test code for your reference:
$TermGroupName = "testMetaData"#Group
$TermSetName = "test"#term group
$TermName="test1"#term set
$subTermName="subTerm"#subterm
$username = "amos#contoso.onmicrosoft.com"
$password = "Password"
$cred = New-Object -TypeName System.Management.Automation.PSCredential -argumentlist $userName, $(convertto-securestring $Password -asplaintext -force)
Connect-PnPOnline -Url https://contoso.sharepoint.com/sites/dev -Credentials $cred
$ctx = Get-PnPContext
$term=Get-PnPTerm -Identity $TermName -TermSet $TermSetName -TermGroup $TermGroupName -Recursive -ErrorAction SilentlyContinue
$subterm=Get-PnPTerm -Identity $subTermName -TermSet $TermSetName -TermGroup $TermGroupName -Recursive -ErrorAction SilentlyContinue
if($subterm.Name -eq $null){
$guid=New-Guid
$term.CreateTerm($subTermName, 1033, $guid)
$ctx.Load($term)
$ctx.ExecuteQuery()
}

PowerShell Script - Create Group if not exists

Simple PowerShell script to create a computer group in AD. If the group exists, print already exists else create new. But something is wrong and its not creating a new group.
Import-Module ActiveDirectory
Import-Module Centrify.DirectControl.PowerShell
Clear-Variable -Name "Result"
Clear-Variable -Name "JSONOutput"
Clear-Variable -Name "ErrorMessage"
Clear-History
$username='<>';
$password='<>';
$computerGroup = 'Sample-New-Role';
# ************* SET CREDENTIALS *************************************
$Password = ConvertTo-SecureString $password -AsPlainText -Force
$global:Cred = New-Object System.Management.Automation.PSCredential($username,$Password)
Set-CdmCredential -Domain (Get-WmiObject Win32_ComputerSystem).Domain -Credential $Cred
$global:DomainController = Get-ADDomain -Current LocalComputer
Set-CdmPreferredServer -Domain (Get-WmiObject Win32_ComputerSystem).Domain -Server $global:DomainController.InfrastructureMaster
$global:OUPath = Get-ADOrganizationalUnit -Filter 'Name -like "Role Groups-Computer"'
# ************************ Create Zone ******************************
try{
if(Get-ADGroup -filter {Name -eq $computerGroup} -ErrorAction Continue)
{
$Result = "Already_Exists"
} else
{
New-ADGroup -Name $computerGroup -GroupScope Global -GroupCategory Security -Path $global:OUPath -Credential $Cred
$Result = 'Success'
}
}
catch{
$ErrorMessage = $_.Exception
}
# ************************* Result *********************************
$JSONOutput = #{"result"=$Result;"error"=$ErrorMessage} | ConvertTo-Json -Compress
Write-Output $JSONOutput
Output: If Group already exist then just create new else print 'Already_Exists'
It works fine if group already exists but failed and error out when new group. Instead of an error, it should create the group. Anything wrong with the condition?
{"error":{"Message":"Cannot find an object with identity: \u002709328-Sample-New-Role\u0027 ....
Import-Module ActiveDirectory
Import-Module Centrify.DirectControl.PowerShell
Clear-Variable -Name "Result"
Clear-Variable -Name "JSONOutput"
Clear-Variable -Name "ErrorMessage"
Clear-History
$username='<>';
$password='<>';
$computerGroup = 'Sample-New-Role';
# ************* SET CREDENTIALS *************************************
$Password = ConvertTo-SecureString $password -AsPlainText -Force
$global:Cred = New-Object System.Management.Automation.PSCredential($username,$Password)
Set-CdmCredential -Domain (Get-WmiObject Win32_ComputerSystem).Domain -Credential $Cred
$global:DomainController = Get-ADDomain -Current LocalComputer
Set-CdmPreferredServer -Domain (Get-WmiObject Win32_ComputerSystem).Domain -Server $global:DomainController.InfrastructureMaster
$global:OUPath = Get-ADOrganizationalUnit -Filter 'Name -like "Role Groups-Computer"'
# ************************ Create Zone ******************************
try{
if(Get-ADGroup -filter {Name -eq $computerGroup} -ErrorAction Continue)
{
$Result = "Already_Exists"
} else
{
New-ADGroup -Name $computerGroup -GroupScope Global -GroupCategory Security -Path $global:OUPath -Credential $Cred
$Result = 'Success'
}
}
catch{
$ErrorMessage = $_.Exception
}
# ************************* Result *********************************
$JSONOutput = #{"result"=$Result;"error"=$ErrorMessage} | ConvertTo-Json -Compress
Write-Output $JSONOutput

PowerShell Script Runs Locally, but Errors on Remote

I have a PowerShell script I am writing to create new users in our domain, as well as email address. The script works when I run it directly on Exchange. However, if I try to do it from my local PC either with Enter-PSSession or Invoke-Command I get the error:
The term 'Get-ADUser' is not recognized as the name of a cmdlet...
Running that same command from the local machine does work. And running that command on the remote machine works, just not if I run the script remotely.
Here is my script:
$cred = Get-Credential
$first_name = Read-Host -Prompt "What is the new user's first name?"
$last_name = Read-Host -Prompt "What is the new user's last name?"
$copy_from = Read-Host -Prompt "Copy from other user (leave blank if not)?"
$password = Read-Host -Prompt "New user's password?"
$ss_password = ConvertTo-SecureString -String $password -AsPlainText -Force
$new_user_name = $last_name.Substring(0,3) + $first_name.Substring(0,2)
$new_user_name = $new_user_name.ToLower()
Write-Host "Creating user $new_user_name..." -ForegroundColor Green
if ([string]::IsNullOrEmpty($copy_from))
{
Write-Host "Setting up new user (not copying...)" -ForegroundColor Yellow
New-ADUser -Name "$first_name $last_name" -AccountPassword $ss_password -SamAccountName $new_user_name -PassThru | Enable-ADAccount
}
else
{
$copy_from_user = Get-ADUser -Identity $copy_from
Write-Host "Copying user from: " $copy_from_user.Name -ForegroundColor Yellow
$ou = $copy_from_user.DistinguishedName -replace '^cn=.+?(?<!\\),'
New-ADUser -Name "$first_name $last_name" -AccountPassword $ss_password -Path $ou -SamAccountName $new_user_name -PassThru | Enable-ADAccount
$new_user = Get-ADUser -Identity $new_user_name
#Time to copy their group memberships
Get-ADUser -Identity $copy_from -Properties memberof | Select-Object -ExpandProperty memberof | Add-ADGroupMember -Members $new_user_name
}
$pn = $new_user_name + "#INDY"
Set-ADUser -Identity $new_user_name -GivenName $first_name -Surname $last_name -UserPrincipalName $pn
#Now create email
$email_select = Read-Host -Prompt "Select email domain (1. Woodmizer; 2. Lastec; 3. Brightstone)"
if ($email_select -eq 2)
{
$domain = "#lastec.com"
}
elseif ($email_select -eq 3)
{
$domain = "#brightstoneabrasives.com"
}
else
{
$domain = "#woodmizer.com"
}
$email_address1 = $first_name.Substring(0,1) + $last_name + $domain
Write-Host "Creating mailbox $email_address1..." -ForegroundColor Green
Enable-Mailbox -Identity $new_user_name -Database "Mailbox Database 1188513962"
Start-Sleep -s 10
Get-Mailbox -Identity $new_user_name | Set-Mailbox -EmailAddresses #{add="$email_address1"} -EMailAddressPolicyEnabled $false
Get-Mailbox -Identity $new_user_name | Set-Mailbox -PrimarySmtpAddress $email_address1 -EmailAddressPolicyEnabled $false
Write-Host "Finished." -ForegroundColor Green
If you want this script to run on machines that don't have the Active Directory module, you can simply add this to the top of your script to import the cmdlets via session..
$cred = Get-Credential "DOMAIN\adminuser"
$ADsession = New-PSSession -ComputerName DOMAINCONTROLLERNAME -Credential $cred
Import-Module -PSSession $ADsession ActiveDirectory
I also notice you're trying to run Exchange cmdlets..
$exchSession = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri "http://EXCHANGESERVER/PowerShell/" -Authentication Kerberos
Import-PSSession $exchSession
It looks like the ActiveDirectory module is not installed on that machine, you can install the MSFT RSAT tools to get it.
Try the following, It works!! {I tried after giving the Authentication type}
$pass = ConvertTo-SecureString -AsPlainText 'PASSWORD' -Force
$MySecureCreds = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList 'USERNAME',$pass
$s=New-PSSession SERVERNAME -Credential $MySecureCreds -Authentication Credssp
Invoke-Command -Session $s -scriptblock {
Get-CsUser User
}

O365 bulk license

I am using this powershell script below to license bulk users in office365 by .csv file. The script will only work if the .csv file header is:
UserPrincipalName
example#jackson.k12.ms.us
But our .csv is formatted: "Alias","UPN"
"myrobinson","myrobinson#jackson.k12.ms.us"
I want to know how to recode this script so it works with our .csv file?
$path= Import-Csv -Path "\\11.10.38.142\Users\myrobinson\NewUsers.csv"
foreach ($item in $path){
$MSOLUserName= $item.UserPrincipalName
$password = ConvertTo-SecureString "support#Jpsd" -AsPlainText –Force
$credential = New-Object System.Management.Automation.PsCredential("admin#jpsd.onmicrosoft.com",$password)
$cred = Get-Credential -cred $credential
Import-Module MSOnline
Connect-Msolservice -cred $cred
$AccountSkuId = "jpsd:STANDARDWOFFPACK_FACULTY"
$UsageLocation = "US"
$LicenseOptions = New-MsolLicenseOptions -AccountSkuId $AccountSkuId
Set-MsolUser -UserPrincipalName $MSOLUserName -UsageLocation $UsageLocation
Set-MsolUserLicense -UserPrincipalName $MSOLUserName -AddLicenses
$AccountSkuId -LicenseOptions $LicenseOptions
}
Just replace $item.UserPrincipalName with $item.UPN.