Error connecting to Exchange 2019 EWS with PowerShell - powershell

I migrated from Exchange 2016 to 2019. I have a PowerShell script I use to connect into exchange using EWS to access the inbox of a user. It keeps failing on connect. I tried to see if there is anything different from 2016 to 2019 but am coming up empty. Here is the code I was using to connect to 2016
Add-Type -Path "C:\Program Files\Microsoft\Exchange\Web Services\2.2\Microsoft.Exchange.WebServices.dll"
$User_Domain = "domain"
$Password = "user_pass"
$EWS = New-Object Microsoft.Exchange.WebServices.Data.ExchangeService -ArgumentList "Exchange2013"
$EWS.Url = "https://mail19.server.com/EWS/Exchange.asmx"
$Username = "username"
$EWS.Credentials = New-Object System.Net.NetworkCredential -ArgumentList $Username, $Password, $User_Domain
$inbox = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($EWS,[Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::Inbox)
When I run the last line I get this error:
Exception calling "Bind" with "2" argument(s): "The request failed. The underlying connection was closed: An unexpected error occurred on a send."
At line:1 char:1
+ $inbox = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($EWS,[Mic ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : ServiceRequestException
This worked fine on my old 2016 exchange server. I am wondering if there is something on exchange I need to tweak or if the code needs tweaked to be able to work with exchange 2019. I am able to access the EWS url and log in with the username/password.

Ok after scouring the internet it seems to be an issue with Exchange 2019 enforcing TLS1.2. I added the following line to the powershell script and the error goes away
[System.Net.ServicePointManager]::SecurityProtocol = [System.Net.SecurityProtocolType]::Tls12;
Hopefully that helps someone else

Related

How to make normal user remote to Windows 2016 by powershell?

I'm trying following powershell script to remowe to windows 2016.
$password = ConvertTo-SecureString "Password" -AsPlainText -Force
$cred= New-Object System.Management.Automation.PSCredential ("username", $password )
enter-pssession -computername 192.168.xxx.xxx -credential $cred
When login with user that has "Adminstrators" permission, it works just fine, but when login with user that only has "Users" permission, it gets access is denied error.
So, What should I do to make "Users" to login with powershell?
OK, I follow the guide below
https://www.sevecek.com/EnglishPages/Lists/Posts/Post.aspx?List=f6e49214-a43d-4fa5-9537-fb46eabe0cb8&ID=4&Web=6dbd0194-ad16-4838-ad08-7f33e3009473
And I can remote Windows Server 2016 with normal user.
But when I tried following script, the exception happens again.
[192.168.XXX.XXX]: PS C:\Users\TestUser\Documents> ([ADSI] "WinNT://localhost/TestUser,user").ChangePassword("#EDC4rfv", "1qaz#WSX")
And the error message is
Exception calling "ChangePassword" with "2" argument(s): "Access is denied.
"
At line:1 char:1
+ ([ADSI] "WinNT://localhost/TestUser,user").ChangePassword("#EDC4rfv", " ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : CatchFromBaseAdapterMethodInvokeTI
Does that mean even normal user can remote to Windows Server 2016, they still can't run commands?
To use PowerShell remoting(default endpoint "Microsoft.PowerShell"), the user should be part of Administrators group in remote machine.
You can tackle this by creating an Endpoint and giving the normal user permission to access it on the remote machine.
More about it is in below link.
https://blogs.technet.microsoft.com/heyscriptingguy/2014/03/31/introduction-to-powershell-endpoints/

powershell Accepting self-signed certificates using ServerCertificateValidationCallback

I cannot seem to get this to work using Powershell 5.1. The device is a Cisco MX800 CE9.3.
$url = "https://10.1.135.20/getxml?location=/Status"
[Net.ServicePointManager]::ServerCertificateValidationCallback={$true}
$webclient = New-Object System.Net.Webclient
$credCache = New-Object System.Net.CredentialCache
$creds = New-Object System.Net.NetworkCredential($user,$pwd)
$credCache.Add($url, "Basic", $creds)
$webclient.Credentials = $credCache
$webpage = $webclient.DownloadString($url)
Running this script using http returns XML as expected, but using https returns the error below
Exception calling "DownloadString" with "1" argument(s): "The underlying connection was closed: An unexpected error occurred on a send."
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : WebException
In the case above, after searching for answers, I dug in and did packet captures.
One packet capture with powershell talking to the server and one packet capture with a web browser talking to the server.
The PS Client Hello was using TLS1.0
The Web browsers Client Hello was using TLS1.2
So, in PS I added this to the code and I was able to use https against the server.
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12

Access denied while running Windows Update using Powershell's Invoke-Command

I've been trying to setup a Powershell module that would remotely call Windows/Microsoft update on a server using Invoke-Command, then process the updates, and send everything back to the calling server so it can send an email report.
My issue comes when I try and call the downloader: Powershell seems to be requesting Elevated rights on the remote computer.
Here is a snippet of what I'm trying to run and fail:
Invoke-Command -ComputerName $Server -Credential $Credentials -ScriptBlock {
$UpdateSession = New-Object -ComObject "Microsoft.Update.Session"
Write-Progress -Activity "Updating" -Status "Checking for new updates"
$Criteria = "IsInstalled=0 and Type='Software'"
$Updates = $UpdateSession.CreateUpdateSearcher().Search($Criteria).updates
$Downloader = $UpdateSession.CreateUpdateDownloader()
$Downloader.Updates = $Updates
}
I know the issue isn't with remoting, as the first 4 commands work fine.
The $Credentials variable points to pre-defined credentials, which are Local Admin on the remote server.
When the script gets to the 5th line, $Downloader = $UpdateSession.CreateUpdateDownloader(), I get this error from Powershell:
Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))
+ CategoryInfo : OperationStopped: (:) [], UnauthorizedAccessException
+ FullyQualifiedErrorId : System.UnauthorizedAccessException
+ PSComputerName : SERVER.sidlee.inc
What could be causing this exactly ?
Thanks in advance for the help!
As i just hit the same wall, and Google isn't of much help either, here is what i could dig up.
For the record, i am pretty much doing the same thing (using custom PS code to check remote systems for Windows Updates) but using WinRM over Python instead of Invoke-Command and also got stuck on Microsoft.Update.Searcher.Search() throwing a E_ACCESSDENIED error.
The UnauthorizedAccessException is indeed not related to Powershell but the underlying API.
I suspect Microsoft started cutting off impersonation in remote session in some recent update (Powershell v5?) as this was (and still is) working just fine on older Windows versions (e.g. Server 2012 with Powershell v3 or 2012 R2 with v4)
To get around this you will need to authenticate (on the remote server) prior to executing your stuff with a PSCredential object.
So Remote Auth -> Local Auth -> Run stuff for example using Start-Process -Credential ...
e.g.
$pass = ConvertTo-SecureString "PA$$W0RD" -AsPlainText -Force
$creds = New-Object System.Management.Automation.PSCredential "User", $pass
Start-Process -Credential $creds powershell -ArgumentList "-Command & { ... whatever you want to do ... }"
Keep in mind that this poses a security risk as your password will be parsed in clear text, so don't do this over an
unencrypted channel!

Error uploading file to FTP Server

I'm trying to use FTP to upload a file to an FTP server. I found the following script online, but I can't get it to work.
$UserName = 'username'
$Password = 'password'
$LocalFilePath = 'c:\FolderName\x.txt'
$RemoteFileName = 'x.txt'
$ServerName = 'my.ftpserver.co.uk'
$webclient = New-Object System.Net.WebClient
$webclient.Credentials = New-Object System.Net.NetworkCredential($UserName, $Password)
#Connect to FTP
$uri = New-Object System.Uri(“ftp://$ServerName/$RemoteFileName”)
write-host $uri
#upload as file
$webclient.UploadFile($uri, $LocalFilePath)
But when I run this I get the following error:
Exception calling "UploadFile" with "2" argument(s): "An exception occurred during a WebClient request."
At line:21 char:22
+ $webclient.UploadFile <<<< ($uri, $LocalFilePath)
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : DotNetMethodException
Can anyone point me in the right direction?
I can connect using Filezilla etc from my PC, so it's not blocked by the firewall or anything,
Tested your script and it runs fine, only way I'm able to reproduce your error is if I point $LocalFilePath to a file that doesn't exist. Could you try:
Test-Path($LocalFilePath)
And see if it returns True?
From your comment and the code I see in the question the issue could just be the fact that you have smart quotes in there. It would be a product of your coding editor or the source of copying and paste that code into your environment. You need to watch out for these things. Assuming the paths are correctly formed perhaps that is just your issue.
Smart Quotes
$uri = New-Object System.Uri(“ftp://$ServerName/$RemoteFileName”)
Proper double quotes
$uri = New-Object System.Uri("ftp://$ServerName/$RemoteFileName")
The quotes in the second example are the ones you should use.

Remote Powershell Access denied for certain dll's execution for Sharepoint 2013

I am attempting to automate a sharepoint 2013 deployment via remote powershell from the build server. Everything executes as expected except when having anything to do with some class in sharepoint dll's such as (Microsoft.SharePoint.Publishing, Microsoft.SharePoint.Publishing.Navigation.WebNavigationSettings)
If I run the same script locally under the same credentials it runs fine.
I have considered the below:
The user has full admin right on both machines
Disabled UAC on the remote server
Followed the required Remote Powershell steps in thig post (http://social.technet.microsoft.com/Forums/sharepoint/en-US/09b60466-5432-48c9-aedd-1af343e957de/user-cannot-be-found-when-using-invokecommand-newspsite-on-sharepoint)
I set powershell to run as admin by defualt via the registry (New-Item -Path "Registry::HKEY_CLASSES_ROOT\Microsoft.PowershellScript.1\Shell\runas\command" -Force -Name '' -Value '"c:\windows\system32\windowspowershell\v1.0\powershell.exe" -noexit "%1"')
Script Code:
#Set the radio buttons value
$settings = New-Object Microsoft.SharePoint.Publishing.Navigation.WebNavigationSettings (,$rootWeb)
$settings.GlobalNavigation.Source = [Microsoft.SharePoint.Publishing.Navigation.StandardNavigationSource]::PortalProvider
#Set the radio buttons value
$settings.CurrentNavigation.Source = [Microsoft.SharePoint.Publishing.Navigation.StandardNavigationSource]::PortalProvider
write-host "I am here.........................."
$settings.Update()
#Set the Publishing Web
$SPPubWeb = [Microsoft.SharePoint.Publishing.PublishingWeb]::GetPublishingWeb($rootWeb)
#Global Navigation Settings
$SPPubWeb.Navigation.InheritGlobal = $false
$SPPubWeb.Navigation.GlobalIncludePages = $false
The Remote Powershell output is as below:
I am here..........................
Exception calling "Update" with "0" argument(s): "Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))"
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : UnauthorizedAccessException
+ PSComputerName : Contoso-DEVSP
Exception setting "GlobalIncludePages": "Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))"
+ CategoryInfo : NotSpecified: (:) [], SetValueInvocationException
+ FullyQualifiedErrorId : ExceptionWhenSetting
+ PSComputerName : Contoso-DEVSP
Many thanks in advance
You need to check CredSSP authentication. Remote PowerShell execution with SharePoint fails as the second hop translates the credentials to system credentials. If the task involves querying or updating DB server, it will fail as SYSTEM account will not have access the remote PowerShell on SQL Server. You need to enable CredSSP.
Check this blog post I wrote a while ago. This is not specific to SharePoint but it should apply to your scenario as well.
http://www.ravichaganti.com/blog/?p=1230