Add 365 License with Powershell Script in task Scheduler - powershell

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 !

Related

Set-OrganizationConfing not recognised, even though I can Get-OrganizationConfig

I'm trying to set the 'Focused Inbox' to disabled for the whole organisation. I've found lots of scripts and tutorials online, most of which point toward using the Exchange Online Session in PowerShell.
e.g.:
https://learn.microsoft.com/en-us/office365/admin/setup/configure-focused-inbox?view=o365-worldwide
https://learn.microsoft.com/en-au/powershell/exchange/exchange-online/connect-to-exchange-online-powershell/connect-to-exchange-online-powershell?view=exchange-ps
My PS script is as follows:
# Set up Credential
$UserCredential = Get-Credential
# Create the Exchange Online session
$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://outlook.office365.com/powershell-liveid/ -Credential $UserCredential -Authentication Basic -AllowRedirection
# Import the cmdlets into this session
Import-PSSession $Session -DisableNameChecking
# Get a list of the organisation's current settings
Get-OrganizationConfig
# Now set the 'Focused Inbox' option to 'off' for everyone
Set-OrganizationConfig -FocusedInboxOn $false
# Must remove the session to avoid clogging and clutter
Remove-PSSession $Session
The 'Get-OrganizationConfig' command returns a full list of the current config:
However, when I execute the 'Set-OrganizationConfig' command, it fails with the following message:
Set-OrganizationConfig : The term 'Set-OrganizationConfig' 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.
My presumption is that it's a permissions issue, however, I can see all the organisation's config, and it's the cmdlet that's missing.
What is the problem?
I am:
Running PS as 'Adminstrator'
Using the 'SharePointAdmin' administrator account for the credentials
This was a permissions issue.
Create the $Session using an account that has Global Admin privileges in your O365 Tenant and you'll see that the 'Set-...' cmdlets automatically get downloaded and inserted into your session.

Get user's skype status with skype online connector on powershell

I'm working on a little script that outputs the current Skype for Business Status of a user.
Available, Busy, Do Not Disturb. etc.
I already experimented a bit and can output a lot of information. The Script works fine but I can't find a status entry.
This is my code so far:
$userCredential = Get-Credential
$sfbSession = New-CsOnlineSession -Credential $userCredential
Import-Module SkypeOnlineConnector
Import-PSSession $sfbSession #connection opens
Get-CsOnlineUser -Identity "buttercup#sup.onmicrosoft.com"
$currentSession = Get-PSSession
Remove-PSSession -Session $currentSession #connection closes
Am I searching on the wrong spot?
If there is any more information I should provide please ask, I hope we can solve this.
For everyone wondering, I solved this problem.
Instead of using the Skype Online Connector, I use the Skype Lync 2013 SDK.
With this simple code, I can achieve what I wanted.
$client = [Microsoft.Lync.Model.LyncClient]::GetClient()
$contact = $client.ContactManager.GetContactByUri("spiderman#marvel.com")
$availabilityId = $contact.GetContactInformation("Availability")
$activity = $contact.GetContactInformation("Activity")
Write-Output ([Microsoft.Lync.Model.ContactAvailability]$availabilityId)
Note that this in this example, there is no need to enter any credentials, because GetClient() already gets the credentials of your open Skype for Business Service.

Remote powershell sessions can only be established with interactively entered credentials?

I'm trying to automate a powershell script which gathers data from O365. I've got a special limited user setup with the privileges required on O365 and also with local logon allowed on the server so that I can "run-as" that user (which I do for all the scripts below. I have verified different, expected errors when running as other users).
The script works fine interactively when credentials are set like this and the session opened:
$cred = Get-Credential
$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://ps.outlook.com/powershell -Credential $cred -Authentication Basic –AllowRedirection
However, if I create the credentials file for automation with:
Get-Credential | Export-Clixml -Path C:\batch\${env:USERNAME}_cred.xml
And then access from the script via:
$cred = Import-Clixml -Path C:\batch\${env:USERNAME}_cred.xml
$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://ps.outlook.com/powershell -Credential $cred -Authentication Basic –AllowRedirection
The credential file load appears to succeed. I then get "Access Denied" on the session open, and then of course the rest of the script fails due to the session being null. I'm cutting and pasting the password in all cases (plus have tried many, MANY times including hand typing) so I don't think it's a simple typo issue. Seems more like something I'm fundamentally misunderstanding about powershell. Ultimately I'd like to not just have the credentials automated, but also have it run from task scheduler if there's any special settings above and beyond that I also need.
I don't see anything wrong from your code from PowerShell perspective. I have tested the way you are creating credentials within a company domain and I was able to create new session by importing credential XML file that was created by exporting the credentials the way you did. I then assume it might be MS Exchange related.
I can suggest alternatives for you to try:
# First we need to get the encrypted password:
$TempCred = Get-Credential
# provide credentials to the prompt
# now the encryption to be saved in a file
$TempCred.Password | ConvertFrom-SecureString | Set-Content C:\mypass.txt
This was the encrypted version of your password is saved as a text.
In your automation script you can now do this:
$username = "yourusername"
$password = Get-Content C:\mypass.txt | ConvertTo-SecureString
$cred = New-Object System.Management.Automation.PsCredential($username, $password)
$session = New-PSSession -Credential $cred .....
I am not sure if this works in your case, it worked in my company domain. Once again it worked for me the XML version too. I am just providing alternatives to try if you are not keen to find out as to why the XML way did not work.
I was able to get this working, in my environment at least, by including a call to Import-PSSession:
$Credential = Import-Clixml -Path D:\Modules\O365Credentials.xml
$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://outlook.office365.com/powershell-liveid/ -Credential $Credential -Authentication Basic -AllowRedirection
Import-PSSession $Session -DisableNameChecking
Get-Mailbox
Does the account in question have MFA enabled? If so, you might try this.
This script:
Downloads Exchange Online Remote PowerShell Module
Installs Exchange Online PowerShell Module
Connects Exchange Online PowerShell using MFA
Or, you can perform these manually. More information, including a detailed walk-through, is available here:
https://o365reports.com/2019/04/17/connect-exchange-online-using-mfa/

Add-AzureAccount -credential not working as I'd hoped

4 days ago (on 4th August 2014) there was a new release of Azure Powershell that included a new -Credential parameter on the Add-AzureAccount cmdlet. I'm trying to use it but I'm clearly doing something wrong.
First I store my password in a file:
read-host -assecurestring | convertfrom-securestring | out-file C:\temp\securestring.txt
Then try and use it in Add-AzureAccount
$password = cat C:\temp\securestring.txt | convertto-securestring
$username = "dhdom1\jamiet" #yes, this is the correct username
$mycred = new-object -typename System.Management.Automation.PSCredential -argumentlist $username,$password
Add-AzureAccount -credential $mycred
The call to Add-AzureAccount fails:
Add-AzureAccount : user_realm_discovery_failed: User realm discovery
failed: The remote server returned an error: (404) Not Found.
I know that "dhdom1\jamiet" is the correct account. Anyone any idea why this might be failing? TIA
You should use the organizational account you use to log in to the Azure Portal with. So, it might look like jamiet#yourorganizationalaccountname.com, or something like that.
open azure powershell window
type Add-AzureAccount then enter
a login screen will be popuped to him then enter this credential outlook
by this, this credentials are stored in this PowerShell window, then run all other scripts from this specific window.

Executing Powershell script as different User in Exchange 2007 Powershell

My scenario looks like this:
Java opens a Powershell in which Exchange Powershell Command/Scripts should be executed as a different user and the output should be displayed in the Powershell windows that Java opened (so Java can read the output).
So: Normal Powershell --> Add Exchange functionality --> Execute Script/Command as different user
To add Exchange functionality to the normal Powershell I use either
add-pssnapin Microsoft.Exchange.Management.PowerShell.Admin or start Powershell like this C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -PSConsoleFile "C:\Program Files\Microsoft\Exchange Server\bin\exshell.psc1" -command ". 'PathToScript/script1.ps1'"
The problem is the execution as a different user:
runAs (or other tools like PSEXEC or minirunAs) is not working because it opens a new window so the output is not shown in the powershell window opened by Java (an therefore cant be read by Java) and is not suitable for automation
I tried 2 different ways to do it with Powershell:
Way 1:
$username = 'domain\user'
$password = 'Pa$$w0rd'
$cred = New-Object System.Management.Automation.PSCredential -ArgumentList #($username,(ConvertTo-SecureString -String $password -AsPlainText -Force))
Invoke-Command -Credential $cred -ComputerName localhost -FilePath PathToScript/script1.ps1
But i get the following Error:
An Active Directory error 0x80072020 occurred while searching for domain controllers in domain MYDOMAIN: An operations error occurred.
+ CategoryInfo : NotSpecified: (0:Int32) [Get-MailboxStatistics], ADTransientException
A simple whoami works this way an prints the user specified in $username but according to this link it looks like that this is not possible with Exchange command (but I dont know how reliable the source is): http://thwack.solarwinds.com/thread/40524
Way 2 (as suggested here http://social.technet.microsoft.com/Forums/en-US/ITCG/thread/f805cbe0-bca9-401a-a381-a7f5520244d2):
$computerName = "localhost"
$username = 'domain\user'
$password = 'Pa$$w0rd'
$cred = New-Object System.Management.Automation.PSCredential -ArgumentList #($username,(ConvertTo-SecureString -String $password -AsPlainText -Force))
$session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri http://$computerName/powershell -Credential $cred
Import-PSSession $session
But the problem here is that the URI http://$computerName/powershell does not exist (I get WinRM 502 exception) and I dont know how to get a Powershell Virtual Directory on a Server where just the Exchange 2007 Management Tools are installed.
So my questions are: Is there another way to do this? What am I doing wrong in Way 1 & 2 (more how can I add the Powershell VD with Way 2)? Is it possible at all?
I run Java (7 x64) on a WinSrv2012 with Exchange 2007 Management Tools installed. The Exchange Server runs on version 2007. The script is Get-MailboxStatistics -server ExSrv.
This bothers me for nearly a week now so I highly appreciate any help.
I just found out that executing Remote Powershell Commands/Skripts is not supported with Exchange 2007 (http://howexchangeworks.com/2009/11/exchange-2007-sp2-supports-powershell.html). So I need to wait until the upgrade to 2013.
Some workarounds: http://social.technet.microsoft.com/Forums/en-US/exchangesvrgeneral/thread/4596035a-cede-4541-8b8e-e2e9bf1b40dc
Or: http://peerfect.blogspot.co.at/2012/10/re-blog-of-my-exchange-remote.html