Export Powershell output to user desktop (User desktop varies) - powershell

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")

Related

PowerShell Alias when connected to a remote Exchange Server

I am trying to create a script to connect to my exchange server remotely and create some alias for commonly used commands.
I connect to exchange using:
$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri http://<ServerFQDN>/PowerShell/ -Authentication Kerberos -Credential $UserCredential
Import-PSSession $Session -DisableNameChecking
If I add to the bottom of this script:
New-Alias -Name "GR" -Value Get-Recipient
I see no error message, but no alias is created. If I run my script to connect to Exchange, and then run the New-Alias command in the terminal, the alias creates as expected.
I assume I am missing something fundamental regarding Sessions or scope, and any help gratefully received.

Why does importing my custom modul show the whole script code?

The Problem:
I have a big custom modul with tons of functions. I import it via my profile.ps1 file like this:
import-module "\\server\path\Filename.psm1"
This worked perfectly in the past.
But since today I added in new code to my profile.ps1 code.
What I changed was that I create a 2nd session to Office 365.
The whole ps1 file looks like this now:
# Log Files
Start-Transcript
# Session leeren
Get-PSSession | Remove-PSSession
#Session auf onPrem
$onpremSession = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri http://onPremServer/powershell
Import-PSSession $onpremSession -Prefix onPremises
#Session auf Cloud
$cloudSession = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://outlook.office365.com/powershell-liveid/ -Credential "$env:USERNAME#mycompany.com" -Authentication Basic -AllowRedirection
Import-PSSession $cloudSession -Prefix Cloud
#Modul Import von allen Scripts
import-module "\\server\path\Filename.psm1"
# Show available CMDlets
get-commands
So since today when I start my powershell using this profile.ps, powershell loads in, creates the session and then when it jumps to the import-module line it shows the whole code from my custom modul.
Screenshot:
Why? I already tried to add a -Verbose:$false but that doesn't change anything.
How can I get rid of the whole script block it shows from the custom modul?
I solved it by saving the import-PsSession output into a variable like this: $s = Import-PSSession $onpremSession -Prefix onPremises
This gets rid of the output.

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/

How to modify main address of MS Office 365 group

Hello I need to modify the main mail address of an Office 365 group.
How can I change 1st part and domain:
Example:
I need to change admin#contoso.com to group#contoso.fr
How can I do this ?
I was looking for the same thing, and it's now possible (from january 2019!).
I found these commands who perfectly works:
Connect to PowerShell (with admin rights)
Allow Remote Signed scripts:
Set-ExecutionPolicy RemoteSigned
Log with O365 admin user:
$UserCredential = Get-Credential
Create new session:
$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://outlook.office365.com/powershell-liveid/ -Credential $UserCredential -Authentication Basic -AllowRedirection
Import session:
Import-PSSession $Session
Set the new address:
Set-UnifiedGroup -Identity admin#contoso.com -PrimarySmtpAddress group#contoso.fr
That perfectly works for me, even if you're trying to send from external email.
Don't forget to return to the default execution policy:
Set-ExecutionPolicy Default
Enjoy it :)

Import-PSSession fails in script, works in shell

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)