Import-module: Could not find a part of the path - powershell

I am trying to connect to Exchange Online using PowerShell (As per this documentation) to add distribution group members.
However I am getting the following error:
Import-Module : Could not find a part of the path
'C:\Users\[my user account]\AppData\Local\Temp\tmp_hhw3s30w.xwu\tmp_hhw3s30w.xwu.format.ps1xml'.
At line:3 char:17
+ ... Import-Module -Name $name -Alias * -Function * -Prefix $p ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (:String) [Import-Module], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException,Microsoft.PowerShell.Commands.ImportModuleCommand
My code is as follows:
$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://outlook.office365.com/powershell-liveid/ -Credential $adCreds -Authentication Basic -AllowRedirection
Import-PSSession $Session -DisableNameChecking -AllowClobber
Connect-MsolService -Credential $adCreds
My code has worked in the past on my machine, so I am struggling to work out why it is failing now.
Any help would be massively appreciated.

Another thing to try is closing and reopening PowerShell.
For me, I had deleted everything in my local temp folder earlier in the session. It seems PowerShell was using some of what was deleted.
When I reopened PowerShell, it apparently recreated the temp files/directories it needed, and Import-Module worked again.

I know this is an old thread but I had the same issue today. The way I fixed it was to update the module that imports modules, PowerShellGet
To check your current module version, enter: Get-Module -Name PowerShellGet
If you're still on version 1.x.x.x, update it with: Install-Module -Name PowerShellGet -Force -AllowClobber
You may need to close and reopen PowerShell. Be sure to check the version again and compare it with what's available at https://www.powershellgallery.com/packages/PowerShellGet/2.2.5

Related

How to use Connect ExchangeOnline -DelegatedOrganization

I'm trying to build a script where i'm using delegated admin rights. And what I have working is this.
$ConnectionUri = "https://ps.outlook.com/powershell-liveid?DelegatedOrg=$TenantDefaultDomainName"
$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri $ConnectionUri -Credential $Office365Credentials -Authentication Basic -AllowRedirection
Import-PSSession $Session -AllowClobber
And this is great and connects just fine but my impression is that it's the old way of doing it as some cmdlets just plain don't work with delegation. An example being that I wanted to get the name of the calendar of a user and tried to do so using
Get-MailboxFolderStatistics -Identity $user -FolderScope Calendar
But I get an error on proxy command saying delegated user should be null. So instead I wanted to try using the new cmdlet but could barely find any information about delegation, following the reference here: https://learn.microsoft.com/en-us/powershell/module/exchange/connect-exchangeonline?view=exchange-ps
I came up with this syntax but it doesn't work at all.
Connect-ExchangeOnline -DelegatedOrganization $TenantDefaultDomainName -Credential $MyOffice365PartnerCredentials
Here's the error i'm getting.
New-ExoPSSession : One or more errors occurred.
At C:\Program Files\WindowsPowerShell\Modules\ExchangeOnlineManagement\2.0.4\netFramework\ExchangeOnlineManagement.psm1:475 char
:30
+ ... PSSession = New-ExoPSSession -ExchangeEnvironmentName $ExchangeEnviro ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [New-ExoPSSession], AggregateException
+ FullyQualifiedErrorId : System.AggregateException,Microsoft.Exchange.Management.ExoPowershellSnapin.NewExoPSSession
I opened an issue on GitHub seeing as this couldn't be the intended behaviour and #chrisda came to my rescue with the response
"this is a shot in the dark, but try using the -UserPrincipalName parameter with Connect-ExchangeOnline:"
Connect-ExchangeOnline -DelegatedOrganization $TenantDefaultDomainName -UserPrincipalName <MyOffice365PartnerUPN>
Mysteriously this works and while using connect-exchangeonline you can use all the normal commands like get-mailboxfolderstatistics that don't work with the old partner method I mentioned first in my question. Hope this helps someone other than me, there is no reference for any of this in the MS documentation or any other place on the internet that I could find.
Reference: https://github.com/MicrosoftDocs/office-docs-powershell/issues/7458
I had this error when there was MFA enabled on the account.

Issue with executing Powershell commands

I'm trying to execute the following commands in Microsoft Powershell console (with Administrator right):
Set-ExecutionPolicy RemoteSigned -Scope CurrentUser
Import-Module MicrosoftTeams
$userCredential = Get-Credential
$sfbSession = New-CsOnlineSession -Credential $userCredential
Import-PSSession $sfbSession
The first three commands are executed without any issue but when I try to execute $sfbSession = New-CsOnlineSession -Credential $userCredential I'm getting the following error:
New-CsOnlineSession : The term 'New-CsOnlineSession' 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.
At line:1 char:15
+ $sfbSession = New-CsOnlineSession -Credential $userCredential
+ ~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (New-CsOnlineSession:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
I have tried to look on various online forums but it's not solving my issue. On Microsoft's website they say that we have to use MicrosoftTeams module instead of SkypeOnlineConnector module but it's not working in my case. I tried various steps but all in vain. I hope someone got an idea how to solve this issue.
Thanks.
Regards,
Seeya

Use Connect-SPOService with Powershell 6 (core version)

I'm trying to connect to a sharepoint environment and I want to do that with Powershell version 6. Why? Eventually, I want to put the PS commands in a .net core 3 application. And as far as I know I cannot use PS5.1 in .net core.
It is about this powershell script:
Import-Module -Force -name Microsoft.Online.SharePoint.PowerShell;
Import-Module -Force -name Microsoft.Online.SharePoint.PowerShell -DisableNameChecking;
$username = 'admin#shootme.com';
$password = 'right now';
$cred = New-Object -TypeName System.Management.Automation.PSCredential -argumentlist $userName, $(convertto-securestring $Password -asplaintext -force);
Connect-SPOService -Url https://shootme.sharepoint.com -Credential $cred;
When I try this in the default PS 5.1 it just works fine. When I try this with PS 6.2.3, I get an error:
Connect-SPOService : The remote server returned an error: (400) Bad Request.
At line:1 char:1
+ Connect-SPOService -Url https://shootme.sharepoint.com -Credent ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [Connect-SPOService], WebException
+ FullyQualifiedErrorId : System.Net.WebException,Microsoft.Online.SharePoint.PowerShell.ConnectSPOService
Does the newer Powershell have different syntax orso, of what am I doing wrong?
Also, maybe there is a way to run scripts in ps 5.1 when running them in .net core?
Have you tried connecting manually by removing the credentials portion and letting it prompt you for a login and test if that resolves successfully?
Edit: I do know you can also call powershell from a .bat like so:
powershell -version 2 .\xyz.ps1
But not knowing what you're going for exactly makes it tough to suggest if that's even a viable option.

New-PSSession :Connecting to remote server outlook.office365.com failed :The parameter is incorrect

I am trying to run the following command on a server(running on Windows Server 2012 R2) in order to import the exchange online PowerShell(I am using the PowerShell ISE with version 5 of PowerShell) commands such as "Search-UnifiedAuditLog" but whenever I run the command I receive an error. My code works while on my local machine(Windows 7 with PowerShell V4) but when I remote connect onto the server to try and run the command it doesn't work.
I am aiming to have a script including this command run as a scheduled task which is why it needs run on the server. I've tried to run this command on several user accounts on the server and still get the same issue. Running the command using the same user accounts as before but using my local machine does not result in an error.
I have tried to set the execution policy to RemoteSigned using the following command but this has had no effect.
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser -Force
My current code looks like;
$ExchangeCredentials = Get-StoredCredential -Target Credentials
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser -Force
$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://outlook.office365.com/powershell-liveid/ -Credential $ExchangeCredentials -Authentication Basic -AllowRedirection
Import-PSSession $Session -DisableNameChecking -AllowClobber
The full error I receive is;
New-PSSession : [outlook.office365.com] Connecting to remote server outlook.office365.com failed with the following error message : The parameter is incorrect. For more information, see the
about_Remote_Troubleshooting Help topic.
At line:1 char:12
+ $Session = New-PSSession -ConfigurationName Microsoft.Exchange -Conne ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : OpenError: (System.Manageme....RemoteRunspace:RemoteRunspace) [New-PSSession], PSRemotingTransportException
+ FullyQualifiedErrorId : 87,PSSessionOpenFailed
I'd expect this command to run fine like on my local machine. I've not been able to find anyone else with this same issue.
Based on the error message, New-PSSession is causing the issue. As all the other parameters look correct, I would check what you are passing to the Credential parameter.
Does Get-StoredCredential -Target Credentials obtain a correct PSCredential object?

Invoking-Command for Exchange in Powershell - block is not allowed in a Data section

What I'm trying to do is run this script:
$WPFcmdCreateNewUser.Add_Click({
$ScriptBlockContent = {
param ($first,
$last,
$upn,
$ou,
$password
)
$encryptedpass = ConvertTo-SecureString -AsPlainText $password -Force
New-RemoteMailbox -Name $name -OnPremisesOrganizationalUnit $ou -UserPrincipalName $upn -FirstName $first -LastName $last -Password $encryptedpass -ResetPasswordOnNextLogon $false
}
$ex = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri http://SERVERNAME/PowerShell/
Invoke-Command -Session $ex -ScriptBlock $ScriptBlockContent -ArgumentList ($WPFtxtNewFirstName.Text, $WPFtxtNewLastName.Text, $WPFtxtNewAlias.Text, $WPFcboNewOU.SelectedItem.Content, $WPFtxtNewPassword.Text)
})
But it's giving me the error:
ERROR: A Begin statement block, Process statement block, or parameter statement is not allowed in a Data section.
ERROR: + CategoryInfo : ParserError: (:) [], ParseException
ERROR: + FullyQualifiedErrorId : InvalidScriptBlockInDataSection
ERROR: + PSComputerName : SERVERNAME
I'm running the whole command from a button click in a XAML Powershell GUI. I googled alot trying to solve the problem as I usually do but no luck :(
Any help would be GREATLY appreciated.
It looks like Exchange uses restricted language mode for remote sessions and you can't execute scriptblocks in your session.
As a security feature, the language mode is obviously controlled at
the server (Exchange), so if you want to enable execution of
scriptblocks you need to interactively logon (RDP or console) to
Exchange and create a new session configuration via
Register-PSSessionConfiguration. You may then connect to Exchange
using this session configuration via New-PSSession -ConfigurationName
and you will then be able to execute scriptblocks by passing this
session instance to Invoke-Command -Session.
Reference:
Remote powershell scriptblock execution question
Bit of an old bump here, but seeing as it is rather high on Google search I figured I could add how I fixed this issue:
$DomainCredential = (Get-Credential)
$fqdn = "<The fully qualified domain name of the target server>"
#Creates a session to the Exchange Remote Management Shell so that we can run Exchange commands. Use https:// if you have a proper setup with certificates. ( Mine was in test env )
$ConfigSession = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri http://$fqdn/powershell `
-Credential $DomainCredential -Authentication Kerberos
#Imports the module that exists in the session, in this case, Exchange Management -AllowClobber gives the imported commands presedence.
Import-Module (Import-PSSession $ConfigSession -AllowClobber)
This imports the Exchange Commands as you would in a local session. The Exchange commands will still be executed on the remote server. Remember to close the session when done.