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/
Related
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.
I'm new to Powershell scripting and I'm working on a user management Powershell script, but I have run into a strange error.
The following code works when I run it from the shell, but not when it is run from a script:
$UserCredential = Get-Credential
$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionURI http://servername/Powershell/ -Authentication Kerberos -Credential $UserCredential -AllowRedirection
Import-PSSession $Session
When I run it in a script with a Param() block on the first line, it fails with the following error:
Import-PSSession: Cannot bind argument to parameter 'Path' becuase it is an empty string.
I can get the Import-PSSession to work if I remove my Param() block, but I'm not sure how to accept command-line arguments for my script otherwise. How can I keep the Param() block (or more generally, accept command-line arguments) and still be able to import the PS session?
I'm using Powershell v2 on a Windows 2008 R2 server trying to connect to a 2010 Exchange server.
Update:
I have a script named ManageUser.ps1 that I run from a Powershell prompt like
.\ManageUser.ps1 -disableUser -username someuser
The script starts like this:
Param(
[switch]$disableUser,
[string]$username
)
$UserCredential = Get-Credential
$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionURI http://servername/Powershell/ -Authentication Kerberos -Credential $UserCredential -AllowRedirection
Import-PSSession $Session
#more stuff past here...
It is failing on the Import-PSSession command. But, if I remove the whole Param(...), the session import works. I hope this is enough for you to understand it!
Your script works fine on it's own and also when called from within another script:
& 'C:\Scripts\ManageUser.ps1' -disableUser -username "foo"
Get-Mailbox -resultsize 5 | ConvertTo-Csv -NoTypeInformation | Out-File C:\Scripts\mytest.csv
Subsequent runs will get the import error/warning due to not having -allowclobber as mentioned by #SamuelWarren...
In your case (at least when initially writing the question long ago) the error was due to another variable that you haven't mentioned here. It's likely you fixed that after the first run, and then subsequent tests were showing the AllowClobber error.
Also worth noting (for anybody who comes across this in the future) to check the path of the file you are calling. Just because you try to use a relative path .\myfile.ps1 doesn't mean that PowerShell is currently looking in the right directory.
Check: $psscriptroot
Or Split-Path -Path $($global:MyInvocation.MyCommand.Path)
I'm a global admin for our 365 environment and I'm having an issue with the Set-UserPhoto command in powershell. If I run it for my own username, it works just fine but if I run it using anyone else's username, it errors. Is there some kind of access I need to give myself to make this work? I'm a domain admin and global administrator in 365 so I should be able to do anything.
Connected through PowerShell 3.0 using the following:
$UserCredential = Get-Credential
$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://outlook.office365.com/powershell-liveid/?proxyMethod=RPS -Credential $UserCredential -Authentication Basic -AllowRedirection
Import-PSSession $Session
Command I'm running:
Set-UserPhoto –Identity username -PictureData ([System.IO.File]::ReadAllBytes("C:\userpics\username.jpg"))
Works fine for my username, for any other username I get this:
Error on proxy command 'Set-UserPhoto -Identity:'username' -PictureData: Tons of numbers here that scrolls for quite a while -Confirm:$False' to server BN3PR0201MB1027.namprd02.prod.outlook.com: Server version 15.01.0534.0000, Proxy method
RPS:
The WinRM client cannot process the request. The connection string should be of the form
[://][:][/] where transport is one of "http" or "https". Transport, port and suffix are
optional. The host may be a hostname or an IP address. For IPv6 addresses, enclose the address in brackets - e.g.
"http://[1::2]:80/wsman". Change the connection string and try the request again. .
+ CategoryInfo : NotSpecified: (:) [Set-UserPhoto], CmdletProxyException
+ FullyQualifiedErrorId : Microsoft.Exchange.Configuration.CmdletProxyException,Microsoft.Exchange.Management.Reci
pientTasks.SetUserPhoto
+ PSComputerName : outlook.office365.com
just ran into the exact same problem.
the solution was to run Microsoft Azure Active Directory Module for Windows PowerShell 'as administrator' (Elevated)
as seen here https://www.blackforce.co.uk/2016/09/23/set-userphoto-error-proxy-command
If you are in hybrid mode and thumbnailPhoto property is synched, you can only change the user photo in your local Active Directory and not in Office 365 Exchange PowerShell session.
If you are not in hybrid mode you can try this sample code instead:
Set-UserPhoto "username" -PictureData ([Byte[]] $(Get-Content -Path "C:\userpics\username.jpg" -Encoding Byte -ReadCount 0)) -Confirm:$false
I had the same issue, and solved it from another post (I don't remember which one).
In the connection string:
$LiveCred = Get-Credential
$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri **https://outlook.office365.com/powershell-liveid/?proxymethod=rps** -Credential $LiveCred -Authentication Basic -AllowRedirection
Import-PSSession $Session
i am running a powershell to export Exchange online user data in a TXT file where i have mentioned C:\Users\%userprofile%\Desktop\Getdata.txt as a location but this script runs on different computer where we have different users so i want to export the data to the desktop of the user directly
Script is as such
Start-Transcript
$UserCredential = Get-Credential
$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://outlook.office365.com/powershell-liveid/ -Credential $UserCredential -Authentication Basic -AllowRedirection
Import-PSSession $Session
get-mailbox |FT >C:\Users\%userprofile%\Desktop\Getdata.txt
Stop-Transcrip
I am still not able to export data to the desktop. I cant export data on C:\ directly as users donot have permission on any local disks.Can this be possible keeping the powershell intact till get-mailbox.
If you're looking for the current user's Desktop path you can get that with:
[environment]::GetFolderPath('Desktop')
So for your code:
|FT > (join-path ([environment]::GetFolderPath('Desktop')) "GetData.txt")
My function is simple, it connects you to an Office365 account:
Function Connect-O365 {
[CmdletBinding()]
Param()
$url = "https://ps.outlook.com/powershell"
$O365Credential = Get-Credential -Message "Enter your Office 365 Credentials"
$O365Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri $url -Credential $O365Credential -Authentication Basic -AllowRedirection
Import-PSSession -Session $O365Session -Prefix O365
}
When running from a custom module, the commands from the imported session are not imported, no message is returned back with any errors or anything.
However, if i copy/paste the same function to my powershell profile, or direct to the console, it works perfectly fine, the commands are successfully imported from the session.
Thoughts?
EDIT: My Module I am adding this function to is a simple .psm1 file with only two other unrelated functions in it, nothing too complex either.
modified the last line in my function to:
Import-Module (Import-PSSession -Session $O365Session) -Global -Prefix O365
This resolved my issue, it was that the module was not importing on my Import-Session