powershell Accepting self-signed certificates using ServerCertificateValidationCallback - powershell

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

Related

FTP File upload powershell

WebClient.UploadFile: $client = New-Object System.Net.WebClient $client.Credentials = New-Object System.Net.NetworkCredential("user", "password") $client.UploadFile("ftp://ftp:50000/test.zip", "C:\HML-V-DC.zip")
When using this script on one computer I am able to upload a file directly to my FTP serve without any issues
But when running this on another machine in another location I get an error "You cannot call a null-valued expression"
Powershell version on computer that is not working: PSVersion 5.1.14393.3866
Powershell version on computer that is working: PSVersion 5.1.19041.610
You cannot call a method on a null-valued expression.
At line:1 char:1
WebClient.UploadFile: $client = New-Object System.Net.WebClient $clie ...
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
Was hoping someone with some quick insight may be able to help me understand what I am missing here.
Thank you
Remove "WebClient.UploadFile: " from the line
$client = New-Object System.Net.WebClient

Error connecting to Exchange 2019 EWS with 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

how to fix DownloadFile error in powershell in windows10 [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I ran cmd as administrator and input:
start powershell
when open the powershell, I input:
$client = new-object System.Net.WebClient
$client.DownloadFile("https://www.cse.ust.hk/msbd5003/data/fruits.txt","D:\IT\fruits.txt")
here is the error information:
Exception calling "DownloadFile" with "2" argument(s): "The underlying connection was closed: An unexpected error occurred on a send."
At line:1 char:1
+ $client.DownloadFile("https://www.cse.ust.hk/msbd5003/data/fruits.txt ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : WebException
I tried adding $ client.Credentials = Get-Credential while it did not work.
My guess would be that since you're connecting through https you may need to set a more secure schannel protocol to communicate with the site you're trying to download from.
add this line indicating security protocol before your webclient request
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
$client = new-object System.Net.WebClient
$client.DownloadFile("https://www.cse.ust.hk/msbd5003/data/fruits.txt","D:\IT\fruits.txt")
Alternately, if you are only running this script from one machine, you can set .NET to use secure protocols by default.
You can read more about it at https://learn.microsoft.com/en-us/dotnet/framework/network-programming/tls
Key - HKEY_LOCAL_MACHINE\SOFTWARE\[Wow6432Node\]Microsoft\.NETFramework\<VERSION>
Name - SchUseStrongCrypto
Value - 1
Also, the native PowerShell cmdlet invoke-webrequest may simplify your request.
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
Invoke-WebRequest -Uri "https://www.cse.ust.hk/msbd5003/data/fruits.txt" -OutFile "D:\IT\fruits.txt"

powershell could not create ssl/tsl secure

I'm using a powershell script to download and execute a file, but since some time I go I get a could not create ssl/tsl secure channel.
$down = New-Object System.Net.WebClient;
$url = 'url';
$file = 'file';
$down.DownloadFile($url,$file);
$exec = New-Object -com shell.application;
$exec.shellexecute($file);
exit;
TLS 1.2 should be enabled to get it working. In PowerShell you can find out which protocols your system supports by running this code:
[Enum]::GetNames([Net.SecurityProtocolType]) -contains 'Tls12'
If the result is True then your system supports TLS 1.2. You can find out which protocols are being used by running:
[System.Net.ServicePointManager]::SecurityProtocol.HasFlag([Net.SecurityProtocolType]::Tls12)
If the result is True then TLS 1.2 is being used . However, you can add TLS 1.2 explicitly by using:
[Net.ServicePointManager]::SecurityProtocol = [Net.ServicePointManager]::SecurityProtocol -bor [Net.SecurityProtocolType]::Tls12
This should solve these problems.
It may be that the site you are connection to requires TLS 1.2, whereas powershell uses TLS 1.0 by default (if I remember correctly)
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
$down = New-Object System.Net.WebClient
$url = 'https://github.com/mpdairy/posh.git'
$file = 'C:\ExistingDirectory\test.git'
$down.DownloadFile($url,$file)
$exec = New-Object -com shell.application
$exec.shellexecute($file)
exit
Without using Tls 1.2, I get this error:
Exception calling "DownloadFile" with "2" argument(s): "The request was aborted: Could not create SSL/TLS
secure channel."
At line:1 char:1
+ $down.DownloadFile($url,$file)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : WebException
I ran into the same error trying to install Wiki.js in Windows server. The issue was the ps1 script included TLS 1.1 as a fallback. The steps below can be changed for any other powershell install
To fix this;
I downloaded the install.ps1 file from installation instructions on Wiki.js installation
iex ((New-Object System.Net.WebClient).DownloadString('https://wiki.js.org/install.ps1'))
Removed "tls11, tls" from the first line
From:
[Net.ServicePointManager]::SecurityProtocol = "tls12, tls11, tls"
To:
[Net.ServicePointManager]::SecurityProtocol = "tls12"
Saved the file in a local directory and changed directory (CD) into
the local directory Ran the command
"iex .\install.ps1"
It's all good now.
Refer this sample code. I written this couple of years when Terraform moved to TLS.
$source=<folder where file suppose to be present>
Write-Verbose -Verbose "Downloading Terraform Required"
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::TLS12
$wc = New-Object System.Net.WebClient
if ((test-path "${source}\terraform.zip") -eq $false) {
$wc.downloadfile("https://releases.hashicorp.com/terraform/0.11.2/terraform_0.11.2_windows_amd64.zip","${source}\terraform.zip")
}
Add-Type -assembly "system.io.compression.filesystem"
[io.compression.zipFile]::ExtractToDirectory("$source\terraform.zip", $destination)
I had the same problem just before and how I fixed it is by changing the link. Make sure the page you're trying to download is a RAW file, for example -
https://raw.githubusercontent.com/TTT2866/Batch-username-generator/master/username_generator.bat
and not
https://github.com/TTT2866/Batch-username-generator/blob/master/username_generator.bat
Note the "raw" in the first link

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.