I need to create new mailboxes via Powershell in Office 365.
I am using this script:
$User = "administrator#blablabla.onmicrosoft.com"
$PWord = ConvertTo-SecureString -AsPlainText -Force -String "P#ssword1"
$Credential = New-Object –TypeName System.Management.Automation.PSCredential –ArgumentList $User, $PWord
$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://outlook.office365.com/powershell-liveid/ -Credential $Credential -Authentication Basic -AllowRedirection
Import-PSSession $Session
Import-CSV new.csv | foreach {
New-Mailbox -UserPrincipalName $_.UserPrincipalName -displayname $_.DisplayName -password (ConvertTo-SecureString $_.password -AsPlainText -Force) -usagelocation "us"
}
Get-PSSession | Remove-PSSession
Details of mailboxes are saved in new.csv file.
See the following example:
UserPrincipalName,DisplayName,password
clark.kent#blablabla.onmicrosoft.com,Clark Kent,P#ssword1
bruce.wayne#blablabla.onmicrosoft.com,Bruce Wayne,P#ssword1
peter.parker#blablabla.onmicrosoft.com,Peter Parker,P#ssword1
When I run this script, I return error:
A parameter cannot be found that matches parameter name 'UserPrincipalName'.
+ CategoryInfo : InvalidArgument: (:) [New-Mailbox],
ParameterBindingException
+ FullyQualifiedErrorId : NamedParameterNotFound,New-Mailbox
+ PSComputerName : outlook.office365.com
Please, what is wrong?
Can you help me?
The UPN Parameter is only available on the Exchange on-premises. Depending on on whether your AD is on-premises or in the cloud, I would suggest creating the AD account first with this parameter and then enable the mailbox.
Or just don't use this parameter.
Correct way to do this is by doing this via MicrosoftOnlineServicesID parameter which seems to replicate UPN.
New-Mailbox -Alias $mailbox.Alias -Name $mailbox.Name -DisplayName $mailbox.DisplayName -ResetPasswordOnNextLogon $true -Password $temporaryPassword -MicrosoftOnlineServicesID $upn -WhatIf
WARNING: After you create a new mailbox, you must go to the Office 365 Admin Center and assign the mailbox a license, or it will
be disabled after the grace period.
What if: Creating mailbox "Anna" with User Principal Name "anna#domain.org.pl" in organizational
unit "EURPR06A004.PROD.OUTLOOK.COM/Microsoft Exchange Hosted Organizations/domain.onmicrosoft.com".
Full story can be found at my blog but all you need is to change UPN to MicrosoftOnlineServicesID and it should work right away.
Try -identity instead of -userprincipalname
Related
EDIT:
I want to retrieve session data from a specific account using
PowerShell. According to this documentation:
https://learn.microsoft.com/en-us/powershell/module/skype/get-csusersession?view=skype-ps
Get-CsUserSession command is able to do this. I am using this
command according to the upper's link example
Get-CsUserSession -User account#companyX.onmicrosoft.com -StartDate "6/1/2018 07:00 PM"
and then I am getting the following error:
A parameter cannot be found that matches parameter name 'StartDate'.
+ CategoryInfo : InvalidArgument: (:) [Get-CsUserSession], ParameterBindingException
+ FullyQualifiedErrorId : NamedParameterNotFound,Microsoft.Rtc.Management.Hosted.Data.GetCsUserSessionCmdlet
+ PSComputerName : admin1e.online.lync.com
What is wrong with that and what is the correct declaration?
I am making a connection to Skype for business service with the following script:
$credential = Get-Credential
Import-Module MSOnline
Connect-MsolService -Credential
$credential Import-Module SkypeOnlineConnector
$lyncSession = New-CsOnlineSession -Credential
$credential Import-PSSession $lyncSession
What I would like to do is to set using a particular static account and password from the PowerShell script (using some sort of declaration variable strings), instead of running this command and have to type the credentials in a separate window. Meaning that I want to avoid using $credential = Get-Credential command. Is this possible?
As stated in documentation you linked (only at the top paragraph though), you have to use StartTime not StartDate. The error you receive is the typical symptom that you either has a typo in parameter name or this parameter doesn't exist for that function.
I'll request to change the example in the docs a bit later, seems like someone who wrote them were mixing up with another cmdlet.
Edit: to store credentials you can export your password like this:
"P#ssword1" | ConvertTo-SecureString -AsPlainText -Force | ConvertFrom-SecureString | Out-File C:\Users\username\password2.txt
And then import like this:
$password = Get-Content -Path "C:\Users\USUARIOPC\password2.txt" | ConvertTo-SecureString -String $password
$credential = New-Object System.Management.Automation.PsCredential("yourlogin#domain.com", $password)
In the meantime, I tried the following query. Probably is not too safe to use a password in a script but for us who want to do it like this is a nice solution.
$username = "account1#companyX.onmicrosoft.com"
$password = "abcdefg"
$secstr = New-Object -TypeName System.Security.SecureString
$password.ToCharArray() | ForEach-Object {$secstr.AppendChar($_)}
$cred = new-object -typename System.Management.Automation.PSCredential -argumentlist $username, $secstr
$credential = $cred
Import-Module MSOnline
Connect-MsolService -Credential $credential
Import-Module SkypeOnlineConnector
$SFBSession = New-CsOnlineSession -Credential $credential
Import-PSSession $SFBSession
I have built a few Powershell functions using Azure Functions, and it is working like a charm.
Now that I have proven the concept I would very much like to refactor my existing functions.
First of all I would like to move the authentication required in my function to some kind of shared function or whatever.
Here is my example function, which return a list of all web apps in my resource group.
# Authenticate with subscription
$subscriptionId = "<SubscriptionId>"
$resourceGroupName = "<ResourceGroupName>";
$tenantId = "<TenantId>"
$applicationId = "<ApplicationId>"
$password = "<Password>"
$userPassword = ConvertTo-SecureString -String $password -AsPlainText -Force
$userCredential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $applicationId, $userPassword
Add-AzureRmAccount -TenantId $tenantid -ServicePrincipal -SubscriptionId $subscriptionId -Credential $userCredential
Get-AzureRmSubscription –SubscriptionId $subscriptionId | Select-AzureRmSubscription
# Get all web apps
$Websites = Get-AzureRmWebApp -ResourceGroupName $resourceGroupName
$Websites = $Websites | select name | ConvertTo-Json -Compress
# Write output
Out-File -Encoding Ascii -FilePath $res -inputObject $Websites
I would very much like to move everything from line 1 to line 10 somewhere else. Is it possible? If yes, can anyone please point me in the right direction here?
Update
Thanks to both Walter and Pragna I combined the two methods like this.
run.ps1
# Authenticate with subscription
Import-Module 'D:\home\site\wwwroot\bin\Authentication.ps1'
# Get all web apps
$Websites = Get-AzureRmWebApp -ResourceGroupName $env:ResourceGroupName
$Websites = $Websites | select name | ConvertTo-Json -Compress
# Write output
Out-File -Encoding Ascii -FilePath $res -inputObject $Websites
Authentication.ps1
$secpasswd = ConvertTo-SecureString $env:Password -AsPlainText -Force;
$userCredential = New-Object System.Management.Automation.PSCredential ($env:ApplicationId, $secpasswd)
Add-AzureRmAccount -TenantId $env:TenantId -ServicePrincipal -SubscriptionId $env:SubscriptionId -Credential $userCredential
Get-AzureRmSubscription –SubscriptionId $env:SubscriptionId | Select-AzureRmSubscription
It is unsafe for you to save your account information in script. I suggest you could store these to App Setting. You could find it Your function app-->Settings-->Application settings-->Manage application settings-->App settings and key-value pairs for the settings SP_USERNAME, SP_PASSWORD, and TENANTID, SubscriptionId(You also could use other values or more key pairs).
Modify your script as below:
# Set Service Principal credentials
# SP_PASSWORD, SP_USERNAME, TENANTID are app settings
$secpasswd = ConvertTo-SecureString $env:SP_PASSWORD -AsPlainText -Force;
$mycreds = New-Object System.Management.Automation.PSCredential ($env:SP_USERNAME, $secpasswd)
Add-AzureRmAccount -ServicePrincipal -Tenant $env:TENANTID -Credential $mycreds;
Get-AzureRmSubscription –SubscriptionId $env:subscriptionId | Select-AzureRmSubscription
When you want to modify your account information, you don't need modify your script, you only need modify app setting. You could modify app setting by using Azure CLI.
Yes. You can import custom powershell modules.
Create a shared directory e.g. bin under D:\home\site\wwwroot
Copy module to the shared directory
Call Import-Module SharedDir\MyModule.psm1 or SharedDir\MyScript.ps1 or SharedDir\MyModule.psd1 or SharedDir\MyLib.dll
Also, here is a sample that might help.
I am trying to run a simple command to hide an email account from the address list using PowerShell. Here is my code so far.
cls
$EmployeeEmail = "user#example.com"
#Need to hide the Mailbox from address list
$MethodName = "Hide Email Account"
$username = "staff"
$password = "accounts"
$secstr = New-Object -TypeName System.Security.SecureString
$password.ToCharArray() | ForEach-Object {$secstr.AppendChar($_)}
$cred = new-object -typename System.Management.Automation.PSCredential -argumentlist $username, $secstr
$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri http://Exchmbca1.example.local/PowerShell/ -Authentication Kerberos -Credential $cred
Import-PSSession $Session
Set-Mailbox -Identity $EmployeeEmail -HiddenFromAddressListsEnabled $true
Remove-PSSession $Session
However, when I run this command I receive the following error message:
The operation couldn't be performed because object 'user#example.com' couldn't be found on 'servername.example'.
I have tried changing the value of the -Identity I pass to the Set-Mailbox cmdlet with 'DOMAIN\username' as well and I receive the same error. I know the account exists because I can do a search using Get-ADUser and find the account with the SAMAccountName. Any help would be much appreciated. Thanks!
In my project, I need Exchange Online Powershell to create an Exchange Service Account.
Here is the code sample:
Set-ExecutionPolicy Unrestricted -Force
$cred = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList 'admin#bdtest.onmicrosoft.com', $(ConvertTo-SecureString -String '123456' -AsPlainText -Force)
$session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri "https://ps.outlook.com/powershell/" -Credential $cred -Authentication Basic -AllowRedirection
Import-PSSession $session
Enable-OrganizationCustomization
$exists=Get-MailUser -Identity 'test1'
if ($exists) {{
remove-mailuser -Identity 'test1' -confirm:$false
}}
New-MailUser -Name 'test1' -DisplayName 'test' -MicrosoftOnlineServicesID 'test1#bdtest.onmicrosoft.com' -Password $(ConvertTo-SecureString -String '123456' -AsPlainText -Force)
New-ManagementRoleAssignment -Role 'ApplicationImpersonation' -User 'test1'
New-ManagementRoleAssignment -Role 'Mailbox Search' -User 'test1'
Remove-PSSession $session
what I want to know is:
when the password is expired ?
How I can set it as never expired?
Setting password to never expire is not possible using Exchange Online cmdlets, you have to use Office365 cmdlets(and therefore MSOnline module, http://technet.microsoft.com/en-us/library/jj151815.aspx).
Add this to the bottom of your script:
Connect-MsolService -Credential $cred
Get-MSOLUser -SearchString test1 | Set-MsolUser -PasswordNeverExpires $true
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"