Базовое соединение закрыто непредвиденная ошибка при передаче powershell

Using Powershell v3’s Invoke-WebRequest and Invoke-RestMethod I have succesfully used the POST method to post a json file to a https website.

The command I’m using is

 $cert=New-Object System.Security.Cryptography.X509Certificates.X509Certificate2("cert.crt")
 Invoke-WebRequest -Uri https://IPADDRESS/resource -Credential $cred -certificate $cert -Body $json -ContentType application/json -Method POST

However when I attempt to use the GET method like:

 Invoke-WebRequest -Uri https://IPADDRESS/resource -Credential $cred -certificate $cert -Method GET

The following error is returned

 Invoke-RestMethod : The underlying connection was closed: An unexpected error occurred on a send.
 At line:8 char:11
 + $output = Invoke-RestMethod -Uri https://IPADDRESS/resource -Credential $cred
 +           ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo          : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest)      [Invoke-RestMethod], WebException
+ FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand

I have attempted using the following code to ignore SSL cert, but I’m not sure if its actually doing anything.

 [System.Net.ServicePointManager]::ServerCertificateValidationCallback = {$true}

What might be going wrong here and how to fix it?

desertnaut's user avatar

desertnaut

57.7k27 gold badges140 silver badges167 bronze badges

asked Jul 27, 2012 at 23:39

floyd's user avatar

3

This work-around worked for me:
http://connect.microsoft.com/PowerShell/feedback/details/419466/new-webserviceproxy-needs-force-parameter-to-ignore-ssl-errors

Basically, in your PowerShell script:

add-type @"
    using System.Net;
    using System.Security.Cryptography.X509Certificates;
    public class TrustAllCertsPolicy : ICertificatePolicy {
        public bool CheckValidationResult(
            ServicePoint srvPoint, X509Certificate certificate,
            WebRequest request, int certificateProblem) {
            return true;
        }
    }
"@
[System.Net.ServicePointManager]::CertificatePolicy = New-Object TrustAllCertsPolicy

$result = Invoke-WebRequest -Uri "https://IpAddress/resource"

answered Apr 5, 2013 at 19:20

Lee Grissom's user avatar

Lee GrissomLee Grissom

9,7256 gold badges37 silver badges47 bronze badges

6

Lee’s answer is great, but I also had issues with which protocols the web server supported.
After also adding the following lines, I could get the https request through. As pointed out in this answer https://stackoverflow.com/a/36266735

$AllProtocols = [System.Net.SecurityProtocolType]'Ssl3,Tls,Tls11,Tls12'
[System.Net.ServicePointManager]::SecurityProtocol = $AllProtocols

My full solution with Lee’s code.

add-type @"
using System.Net;
using System.Security.Cryptography.X509Certificates;
public class TrustAllCertsPolicy : ICertificatePolicy {
    public bool CheckValidationResult(
        ServicePoint srvPoint, X509Certificate certificate,
        WebRequest request, int certificateProblem) {
        return true;
    }
}
"@
$AllProtocols = [System.Net.SecurityProtocolType]'Ssl3,Tls,Tls11,Tls12'
[System.Net.ServicePointManager]::SecurityProtocol = $AllProtocols
[System.Net.ServicePointManager]::CertificatePolicy = New-Object TrustAllCertsPolicy

answered Sep 16, 2017 at 13:43

AndOs's user avatar

AndOsAndOs

1,3249 silver badges6 bronze badges

10

An alternative implementation in pure powershell (without Add-Type of c# source):

#requires -Version 5
#requires -PSEdition Desktop

class TrustAllCertsPolicy : System.Net.ICertificatePolicy {
    [bool] CheckValidationResult([System.Net.ServicePoint] $a,
                                 [System.Security.Cryptography.X509Certificates.X509Certificate] $b,
                                 [System.Net.WebRequest] $c,
                                 [int] $d) {
        return $true
    }
}
[System.Net.ServicePointManager]::CertificatePolicy = [TrustAllCertsPolicy]::new()

answered Mar 19, 2019 at 16:59

Maximilian Burszley's user avatar

Invoke-WebRequest «DomainName» -SkipCertificateCheck

You can use -SkipCertificateCheck Parameter to achieve this as a one-liner command ( THIS PARAMETER IS ONLY SUPPORTED ON CORE PSEDITION )

answered May 19, 2020 at 8:56

Amar Helloween's user avatar

2

Did you try using System.Net.WebClient?

$url = 'https://IPADDRESS/resource'
$wc = New-Object System.Net.WebClient
$wc.Credentials = New-Object System.Net.NetworkCredential("username","password")
$wc.DownloadString($url)

Qantas 94 Heavy's user avatar

answered Jul 31, 2012 at 12:51

Sunny Chakraborty's user avatar

6

The following worked worked for me (and uses the latest non deprecated means to interact with the SSL Certs/callback functionality), and doesn’t attempt to load the same code multiple times within the same powershell session:

if (-not ([System.Management.Automation.PSTypeName]'ServerCertificateValidationCallback').Type)
{
$certCallback=@"
    using System;
    using System.Net;
    using System.Net.Security;
    using System.Security.Cryptography.X509Certificates;
    public class ServerCertificateValidationCallback
    {
        public static void Ignore()
        {
            if(ServicePointManager.ServerCertificateValidationCallback ==null)
            {
                ServicePointManager.ServerCertificateValidationCallback += 
                    delegate
                    (
                        Object obj, 
                        X509Certificate certificate, 
                        X509Chain chain, 
                        SslPolicyErrors errors
                    )
                    {
                        return true;
                    };
            }
        }
    }
"@
    Add-Type $certCallback
 }
[ServerCertificateValidationCallback]::Ignore();

This was adapted from the following article
https://d-fens.ch/2013/12/20/nobrainer-ssl-connection-error-when-using-powershell/

answered Aug 2, 2016 at 19:33

Arthur Strutzenberg's user avatar

I found that when I used the this callback function to ignore SSL certificates [System.Net.ServicePointManager]::ServerCertificateValidationCallback = {$true}

I always got the error message Invoke-WebRequest : The underlying connection was closed: An unexpected error occurred on a send. which sounds like the results you are having.

I found this forum post which lead me to the function below. I run this once inside the scope of my other code and it works for me.

function Ignore-SSLCertificates
{
    $Provider = New-Object Microsoft.CSharp.CSharpCodeProvider
    $Compiler = $Provider.CreateCompiler()
    $Params = New-Object System.CodeDom.Compiler.CompilerParameters
    $Params.GenerateExecutable = $false
    $Params.GenerateInMemory = $true
    $Params.IncludeDebugInformation = $false
    $Params.ReferencedAssemblies.Add("System.DLL") > $null
    $TASource=@'
        namespace Local.ToolkitExtensions.Net.CertificatePolicy
        {
            public class TrustAll : System.Net.ICertificatePolicy
            {
                public bool CheckValidationResult(System.Net.ServicePoint sp,System.Security.Cryptography.X509Certificates.X509Certificate cert, System.Net.WebRequest req, int problem)
                {
                    return true;
                }
            }
        }
'@ 
    $TAResults=$Provider.CompileAssemblyFromSource($Params,$TASource)
    $TAAssembly=$TAResults.CompiledAssembly
    ## We create an instance of TrustAll and attach it to the ServicePointManager
    $TrustAll = $TAAssembly.CreateInstance("Local.ToolkitExtensions.Net.CertificatePolicy.TrustAll")
    [System.Net.ServicePointManager]::CertificatePolicy = $TrustAll
}

answered Mar 26, 2013 at 0:50

Aaron D's user avatar

Aaron DAaron D

5,8171 gold badge36 silver badges51 bronze badges

I tried searching for documentation on the EM7 OpenSource REST API. No luck so far.

http://blog.sciencelogic.com/sciencelogic-em7-the-next-generation/05/2011

There’s a lot of talk about OpenSource REST API, but no link to the actual API or any documentation.
Maybe I was impatient.

Here are few things you can try out

$a = Invoke-RestMethod -Uri https://IPADDRESS/resource -Credential $cred -certificate $cert 
$a.Results | ConvertFrom-Json

Try this to see if you can filter out the columns that you are getting from the API

$a.Results | ft

or, you can try using this also

$b = Invoke-WebRequest -Uri https://IPADDRESS/resource -Credential $cred -certificate $cert 
$b.Content | ConvertFrom-Json

Curl Style Headers

$b.Headers

I tested the IRM / IWR with the twitter JSON api.

$a = Invoke-RestMethod http://search.twitter.com/search.json?q=PowerShell 

desertnaut's user avatar

desertnaut

57.7k27 gold badges140 silver badges167 bronze badges

answered Aug 1, 2012 at 3:21

Sunny Chakraborty's user avatar

1

These registry settings affect .NET Framework 4+ and therefore PowerShell. Set them and restart any PowerShell sessions to use latest TLS, no reboot needed.

Set-ItemProperty -Path 'HKLM:\SOFTWARE\Wow6432Node\Microsoft\.NetFramework\v4.0.30319' -Name 'SchUseStrongCrypto' -Value '1' -Type DWord
Set-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\.NetFramework\v4.0.30319' -Name 'SchUseStrongCrypto' -Value '1' -Type DWord 

See https://learn.microsoft.com/en-us/dotnet/framework/network-programming/tls#schusestrongcrypto

answered Sep 5, 2018 at 22:10

Jeremy Cook's user avatar

Jeremy CookJeremy Cook

20.9k9 gold badges71 silver badges78 bronze badges

1

Using a vpn and changing your location from there works completely fine.
I wasn’t able to access raw.githubusercontent.com as in my country, my isp has blocked that url, I tried using a vpn and now it works very well.

answered May 21 at 6:20

Simply Game Developer's user avatar

1

  1. Run this command

New-SelfSignedCertificate -certstorelocation cert:\localmachine\my -dnsname {your-site-hostname}

in powershell using admin rights, This will generate all certificates in Personal directory

  1. To get rid of Privacy error, select these certificates, right click → Copy. And paste in Trusted Root Certification Authority/Certificates.
  2. Last step is to select correct bindings in IIS. Go to IIS website, select Bindings, Select SNI checkbox and set the individual certificates for each website.

Make sure website hostname and certificate dns-name should exactly match

answered May 26, 2017 at 14:37

Mohit Dharmadhikari's user avatar

  • Remove From My Forums
  • Вопрос

  • Всем доброго дня! Помогите с проблемой

    $Url = "http://site/file.exe"
    $Path = "D:\1.exe" 
    $WebClient = New-Object System.Net.WebClient
    $WebClient.DownloadFile($url,$path)

    при выполнении

    Исключение при вызове «DownloadFile» с «2» аргументами: «Исключение во время запроса WebClient.»
    строка:4 знак:1
    + $webclient.DownloadFile($fileURL,$fileName)
    + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
        + FullyQualifiedErrorId : WebException

    что не так? Help?

Ответы

  • Проверьте путь, указанный для сохранения файла. Попробуйте скачать файл в другое место.

    • Помечено в качестве ответа

      14 октября 2013 г. 9:37

What should have been just another quick PowerShell script performing a WebRequest to get some data, turned into a debugging session when both the Invoke-RestMethod and Invoke-WebRequest PowerShell commands were returning; The underlying connection was closed: An unexpected error occurred on a send.

Invoke-RestMethod

Here is the PowerShell Invoke-RestMethod response that returns: The underlying connection was closed: An unexpected error occurred on a send.

Invoke-RestMethod : The underlying connection was closed: An unexpected error occurred on a send.
At line:1 char:15
+ ... postdata2 = Invoke-RestMethod -Uri $post.URL -Method Get -UserAgent $ ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-RestMethod], WebException
+ FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand

Invoke-WebRequest

Here is the PowerShell Invoke-WebRequest response that returns: The underlying connection was closed: An unexpected error occurred on a send.

Invoke-WebRequest : The underlying connection was closed: An unexpected error occurred on a send.
At line:3 char:21
+ ... $postdata = Invoke-WebRequest -Uri $post.URL -Method Get -UserAgent $ ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-WebRequest], WebException
+ FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeWebRequestCommand

Due to PowerShell defaults, it’s not unusual to have issues with TLS. The ambiguous nature of this error did however make me jump to the conclusion that I probably just needed to enforce TLS 1.2. This can be done using this PowerShell one-liner:

[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12

However, in this situation that wasn’t the fix. Thinking it was still TLS related I checked out the SSL Certificate for the URI I was making my webrequests against. Looking at the certificate showed it was valid.

Powershell - An unexpected error occurred on a send - Certificate is Valid.PNG

Solution

After a lot of searching I was able to work around the problem using scenarios from (here and here), however they weren’t ideal.

The resolution and solution I’m using to resolve the problem is to allow TLS, TLS 1.1 and TLS 1.2.

Insert the following line before invoking your PowerShell WebRequest using either Invoke-RestMethod or Invoke-WebRequest.

[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls -bor [Net.SecurityProtocolType]::Tls11 -bor [Net.SecurityProtocolType]::Tls12

Summary

Hopefully this helps others experiencing this error, and allows me to quickly find it again next time I encounter this issue.

Also checkout my PowerShell Snippets Vol 1  and Vol 2 for other simple resolutions to ambiguous errors and tasks.

The underlying connection was closed: an unexpected error occurred on a send.

To resolve the PowerShell “underlying connection was closed” error, in your PowerShell script enable TLS:

Add the following line before your Invoke-RestMethod or Invoke-WebRequest call;

  1. [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls -bor
    [Net.SecurityProtocolType]::Tls11 -bor [Net.SecurityProtocolType]::Tls12

Applies To : PowerShell

What should have been just another quick PowerShell script performing a WebRequest to get some data, turned into a debugging session when both the Invoke-RestMethod and Invoke-WebRequest PowerShell commands were returning; The underlying connection was closed: An unexpected error occurred on a send.

Invoke-RestMethod

Here is the PowerShell Invoke-RestMethod response that returns: The underlying connection was closed: An unexpected error occurred on a send.

Invoke-RestMethod : The underlying connection was closed: An unexpected error occurred on a send.
At line:1 char:15
+ ... postdata2 = Invoke-RestMethod -Uri $post.URL -Method Get -UserAgent $ ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-RestMethod], WebException
+ FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand

Invoke-WebRequest

Here is the PowerShell Invoke-WebRequest response that returns: The underlying connection was closed: An unexpected error occurred on a send.

Invoke-WebRequest : The underlying connection was closed: An unexpected error occurred on a send.
At line:3 char:21
+ ... $postdata = Invoke-WebRequest -Uri $post.URL -Method Get -UserAgent $ ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-WebRequest], WebException
+ FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeWebRequestCommand

Due to PowerShell defaults, it’s not unusual to have issues with TLS. The ambiguous nature of this error did however make me jump to the conclusion that I probably just needed to enforce TLS 1.2. This can be done using this PowerShell one-liner:

[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12

However, in this situation that wasn’t the fix. Thinking it was still TLS related I checked out the SSL Certificate for the URI I was making my webrequests against. Looking at the certificate showed it was valid.

Powershell - An unexpected error occurred on a send - Certificate is Valid.PNG

Solution

After a lot of searching I was able to work around the problem using scenarios from (here and here), however they weren’t ideal.

The resolution and solution I’m using to resolve the problem is to allow TLS, TLS 1.1 and TLS 1.2.

Insert the following line before invoking your PowerShell WebRequest using either Invoke-RestMethod or Invoke-WebRequest.

[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls -bor [Net.SecurityProtocolType]::Tls11 -bor [Net.SecurityProtocolType]::Tls12

Summary

Hopefully this helps others experiencing this error, and allows me to quickly find it again next time I encounter this issue.

Also checkout my PowerShell Snippets Vol 1  and Vol 2 for other simple resolutions to ambiguous errors and tasks.

The underlying connection was closed: an unexpected error occurred on a send.

To resolve the PowerShell “underlying connection was closed” error, in your PowerShell script enable TLS:

Add the following line before your Invoke-RestMethod or Invoke-WebRequest call;

  1. [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls -bor
    [Net.SecurityProtocolType]::Tls11 -bor [Net.SecurityProtocolType]::Tls12

Applies To : PowerShell

I am trying to connect to an external api website. I don’t know details around how REST/JSON works, but I want to use powershell to download a csv file via GET method. I could successfully connect via CURL, but with powershell I cannot, and am exhausted.

CURL:

curl.exe -v -H «Accept: application/json» -u APIKEY: «https://»

Powershell:

Invoke-RestMethod -Uri ‘https://’ -Headers @{«AUTHORIZATION»=»Basic «} -Method Get

I always receive following error:

the underlying connection was closed an unexpected error occurred on a send and the underlying connection was closed an unexpected error occurred on a receive

I tried using following script for certificate:

add-type @»
using System.Net;
using System.Security.Cryptography.X509Certificates;
public class TrustAllCertsPolicy : ICertificatePolicy {
public bool CheckValidationResult(
ServicePoint srvPoint, X509Certificate certificate,
WebRequest request, int certificateProblem) {
return true;
}
}
«@
[System.Net.ServicePointManager]::CertificatePolicy = New-Object TrustAllCertsPolicy

$result = Invoke-WebRequest -Uri «https://IpAddress/resource»

Source: http://stackoverflow.com/questions/11696944/powershell-v3-invoke-webrequest-https-error

still no luck.

Can someone help me understand what I am doing wrong?

Update# 2:

Basic is followed by Base64Encoded API KEY. This is what I see when I use the API Web, the one website provides:

{
«Accept»: «application/json»,
«Authorization»: «Basic Base64Encode»,
«Content-Length»: 0,
«x-forwarded-for»: «Source IP»
}

I upgraded to v4

PS C:> $PSVersionTable.PSVersion

Major Minor Build Revision
—– —– —– ——–
4 0 -1 -1

and also used:

[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12

since TLS1.2 is the requirement, still same error:

Invoke-RestMethod : The underlying connection was closed: An unexpected error occurred on a receive.
At line:1 char:1
+ Invoke-RestMethod -Method Get -Uri ‘https:////// …
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-RestMethod], We
eption
+ FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand

If I don’t use https, then it says:

Unable to connect to the remote server

I have an existing REST API that accept x-www-form-urlencoded. The API need parameter apikey, and tested successfully in Postman as shown below.

enter image description here

However I need to invoke this API using Powershell.Below is my code :

$params = @{"apikey"="abcd1234"}
Invoke-WebRequest -Uri http://localhost:3030/api/v1/usergroupsync -Method POST -Body $params
#also tried below, no avail.
Invoke-RestMethod -Uri http://localhost:3030/api/v1/usergroupsync -Method POST -Body $params

However I encountered this error :

Invoke-WebRequest : The underlying connection was closed: An unexpected error occured on a receive At line:14 char:1
+ Invoke-WebRequest -Uri http://localhost:3030/api/v1/usergroupsync -Method POST -...
+==============================================================================
  + CategoryInfo : InvalidOperations: (System.Net.HttpWebRequest:HTTTpWebRequest) [Invoke-WebRequest], WebException
  + FullyQualifiedErrorId : WebcmdletWebResponseException,Microsoft.Powershell.Commands.InvokeWebRequest

If I remove -Body, there is no error, and Response was as expected «API Key is not valid» which means my REST API validate correctly.
enter image description here

So I suspect the reason if my issue is on the body? Any idea on how to solve this issue?

PS Version is 4.0.0

PS C:> $PSVersionTable.PSVersion

Major  Minor  Build  Revision
-----  -----  -----  --------
 4      0      -1     -1
  • #1

Привет всем, разбираюсь с telegram bot API, решил набросать основу на powershell. Но в самом начале ошибка:

Код:

PS C:bot> $token = "тут мой токен"
PS C:bot> $URL_get = "https://api.telegram.org/bot$token/getUpdates"
PS C:bot> $URL_set = "https://api.telegram.org/bot$token/sendMessage"
PS C:bot> Invoke-RestMethod -Uri $URL_get

Ошибка вот такая

Invoke-RestMethod : Базовое соединение закрыто: Непредвиденная ошибка при передаче.
строка:1 знак:1
+ Invoke-RestMethod -Uri $URL_get
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-RestMethod], WebExc
eption
+ FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand

Подскажите из за чего ??

Последнее редактирование модератором: 23.04.2020

  • #2

телеграм же запрещен, если из России запускаете, вот вы и не можете соединиться. Можно попробовать через прокси какой нибудь

  • #3

Привет всем, разбираюсь с telegram bot API, решил набросать основу на powershell. Но в самом начале ошибка:

Код:

PS C:bot> $token = "тут мой токен"
PS C:bot> $URL_get = "https://api.telegram.org/bot$token/getUpdates"
PS C:bot> $URL_set = "https://api.telegram.org/bot$token/sendMessage"
PS C:bot> Invoke-RestMethod -Uri $URL_get

Ошибка вот такая

Подскажите из за чего ??

попробуйте подключаться через прокси.

Surf_rider

  • #4

Привет всем, разбираюсь с telegram bot API, решил набросать основу на powershell. Но в самом начале ошибка:

Код:

PS C:bot> $token = "тут мой токен"
PS C:bot> $URL_get = "https://api.telegram.org/bot$token/getUpdates"
PS C:bot> $URL_set = "https://api.telegram.org/bot$token/sendMessage"
PS C:bot> Invoke-RestMethod -Uri $URL_get

Ошибка вот такая

Подскажите из за чего ??

телеграм заблочен в РФ.
Попробуйте поискать бесплатный VPN, например TunnelBear или прокси

Последнее редактирование: 24.04.2020

  • #5

жаль, а есть аналоги телеграм ботов ?

  • #6

жаль, а есть аналоги телеграм ботов ?

Microsoft Bot Framework

Hi everyone,

To Introduce myself : Working as a Power BI Developer with PBI Admin access. 

My Powershell script stoped working suddenly and prompting me an error saying the underlying connection was closed. This was all working fine few days back.

EricShahi_1-1665227264165.png

Here is a part of my script that calls REST API to export the reprot in pdf format. 

Login-PowerBI

$groupid = «Hidden»
$Reportid = «Hidden»
$Folder = «c:temp»
$Body = «{`”format`”:`”pdf`”}»
$filename = $Folder + «PowerBIMetrics.pdf»

$StatusCheck=0

# Get token
$token = Get-PowerBIAccessToken -AsString
##write-host $token

# Building Rest API header with authorization token
$authHeader = @{
«Authorization»= $token
«Content-Type» = «application/json»
}

$url1 = «https://api.powerbi.com/v1.0/myorg/groups/$groupid/reports/$Reportid/ExportTo»

Invoke-RestMethod -Method Post -uri $url1 -Headers $authHeader -body $Body

I have tried to look for solution and many of them (Power BI community/ DBA) is saying I need to add extra line  of code below before I execute the Invoke-ResMethod command line,

[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12

Unfortunately, I’m getting same error message.

Thank you.

Eric

I am pretty new to PowerShell and am trying to use REST methods for an application which require OAuth2.0 Authentication.

I have written the following using this https://msdn.microsoft.com/en-us/library/hh454950.aspx as a reference:

$ClientID = 'david_web'
$client_Secret = 'Secret_123'

$Uri = "https://target_server/api/token"

$Body = "grant_type=password=$ClientID&username=$client_Secret"

$admAuth=Invoke-RestMethod -Uri $Uri -Body $Body -Method Post

$HeaderValue = "Bearer " + $admauth

$uri = "https://target_server/api/v1.0/discovery";

$result = Invoke-RestMethod -Uri $uri -Headers @{Authorization = $HeaderValue} 

$result.string.'#text'

When I run this I get:

Invoke-RestMethod : The underlying connection was closed: An unexpected error
occurred on a send.

If I try the following from Linux:

curl -k -i -X POST -d 'grant_type=password&username=david_web&password=Secret_123' https://target_server/api/token

It works but I have to include the -k option. How do I do the same on PowerShell?

Edit:

Running just this:

$ClientID = 'david_web'
$client_Secret = 'Secret_123'
$Uri = "https://target_server/api/token"
$Body = 'grant_type=password&username=$ClientID&password=$client_Secr‌​et'    
$admAuth = Invoke-RestMethod -Method Post -Uri $Uri -Body $Body

Returns:

[ERROR] Invokenvoke-RestMethod : The underlying connection was closed: An unexpected error
[ERROR] occurred on a send.
[ERROR] At C:datavisual studio 2015ProjectsPSDiscoveryRESTGetToken.ps1:34 [ERROR] char:12
[ERROR] + $admAuth = Invoke-RestMethod -Method Post -Uri $Uri -Body $Body
[ERROR] + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
[ERROR] + CategoryInfo : InvalidOperation: (System.Net.HttpWebRequest:Htt
[ERROR] pWebRequest) [Invoke-RestMethod], WebException
[ERROR] + FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShe
[ERROR] ll.Commands.InvokeRestMethodCommand

I am pretty new to PowerShell and am trying to use REST methods for an application which require OAuth2.0 Authentication.

I have written the following using this https://msdn.microsoft.com/en-us/library/hh454950.aspx as a reference:

$ClientID = 'david_web'
$client_Secret = 'Secret_123'

$Uri = "https://target_server/api/token"

$Body = "grant_type=password=$ClientID&username=$client_Secret"

$admAuth=Invoke-RestMethod -Uri $Uri -Body $Body -Method Post

$HeaderValue = "Bearer " + $admauth

$uri = "https://target_server/api/v1.0/discovery";

$result = Invoke-RestMethod -Uri $uri -Headers @{Authorization = $HeaderValue} 

$result.string.'#text'

When I run this I get:

Invoke-RestMethod : The underlying connection was closed: An unexpected error
occurred on a send.

If I try the following from Linux:

curl -k -i -X POST -d 'grant_type=password&username=david_web&password=Secret_123' https://target_server/api/token

It works but I have to include the -k option. How do I do the same on PowerShell?

Edit:

Running just this:

$ClientID = 'david_web'
$client_Secret = 'Secret_123'
$Uri = "https://target_server/api/token"
$Body = 'grant_type=password&username=$ClientID&password=$client_Secr‌​et'    
$admAuth = Invoke-RestMethod -Method Post -Uri $Uri -Body $Body

Returns:

[ERROR] Invokenvoke-RestMethod : The underlying connection was closed: An unexpected error
[ERROR] occurred on a send.
[ERROR] At C:datavisual studio 2015ProjectsPSDiscoveryRESTGetToken.ps1:34 [ERROR] char:12
[ERROR] + $admAuth = Invoke-RestMethod -Method Post -Uri $Uri -Body $Body
[ERROR] + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
[ERROR] + CategoryInfo : InvalidOperation: (System.Net.HttpWebRequest:Htt
[ERROR] pWebRequest) [Invoke-RestMethod], WebException
[ERROR] + FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShe
[ERROR] ll.Commands.InvokeRestMethodCommand

0 / 0 / 0

Регистрация: 14.05.2018

Сообщений: 214

1

03.12.2020, 13:12. Показов 9257. Ответов 12


Студворк — интернет-сервис помощи студентам

Здравствуйте! Пробую установить chocolately через powershell:

PS C:\Users\Тарас> Set-ExecutionPolicy Bypass -Scope Process -Force; iex ((New-Object System.Net.WebClient).DownloadStri
ng(‘https://chocolatey.org/install.ps1’))

И ошибка:

Исключение при вызове «DownloadString» с «1» аргументами: «Базовое соединение закрыто: Непредвиденная ошибка при переда
че.»
строка:1 знак:104
+ Set-ExecutionPolicy Bypass -Scope Process -Force; iex ((New-Object System.Net.WebClient).DownloadString <<<< (‘https:
//chocolatey.org/install.ps1′))
+ CategoryInfo : NotSpecified: ( [], MethodInvocationException
+ FullyQualifiedErrorId : DotNetMethodException

Что делаю не так?

Очень срочно, подскажите как установить chocolately

Добавлено через 48 минут
Может кто-то подскажет правильные команди для установки chocolately?



0



alhaos

1743 / 438 / 131

Регистрация: 20.02.2019

Сообщений: 2,286

Записей в блоге: 40

03.12.2020, 14:15

2

оригинально…

так попробуйте

PowerShell
1
iex ((Invoke-WebRequest https://chocolatey.org/install.ps1).Content)



0



0 / 0 / 0

Регистрация: 14.05.2018

Сообщений: 214

03.12.2020, 15:15

 [ТС]

3

alhaos, вот весь код:

PS C:\Users\Тарас> Get-ExecutionPolicy
AllSigned
PS C:\Users\Тарас> Set-ExecutionPolicy AllSigned

Изменение политики выполнения
Политика выполнения обеспечивает защиту компьютера от ненадежных скриптов. Изменение политики выполнения может
подвергнуть компьютер риску нарушения системы безопасности, как описано в разделе справки, вызываемом командой
about_Execution_Policies. Изменить политику выполнения?
[Y] Да — Y [N] Нет — N [S] Приостановить — S [?] Справка (значением по умолчанию является «Y»): Y
PS C:\Users\Тарас> iex ((Invoke-WebRequest https://chocolatey.org/install.ps1).Content)
Имя «Invoke-WebRequest» не распознано как имя командлета, функции, файла скрипта или выполняемой программы. Проверьте п
равильность написания имени, а также наличие и правильность пути, после чего повторите попытку.
строка:1 знак:24
+ iex ((Invoke-WebRequest <<<< https://chocolatey.org/install.ps1).Content)
+ CategoryInfo : ObjectNotFound: (Invoke-WebRequest:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException

Не распознает. Подскажите, пожалуйста, что не так



0



1743 / 438 / 131

Регистрация: 20.02.2019

Сообщений: 2,286

Записей в блоге: 40

03.12.2020, 15:28

4

x3
у меня работает.

Код

Windows PowerShell
(C) Корпорация Майкрософт (Microsoft Corporation). Все права защищены.
                                                                                                                        Попробуйте новую кроссплатформенную оболочку PowerShell (https://aka.ms/pscore6)                                                                                                                                                                PS C:\Users\alHaos> iex ((Invoke-WebRequest https://chocolatey.org/install.ps1).Content)                                Getting latest version of the Chocolatey package for download.
Getting Chocolatey from https://chocolatey.org/api/v2/package/chocolatey/0.10.15.
Downloading 7-Zip commandline tool prior to extraction.
Extracting C:\Users\alHaos\AppData\Local\Temp\chocolatey\chocInstall\chocolatey.zip to C:\Users\alHaos\AppData\Local\Temp\chocolatey\chocInstall...
Installing chocolatey on this machine

Не удается проверить издателя. Вы действительно хотите запустить эту программу?
Файл C:\Users\alHaos\AppData\Local\Temp\chocolatey\chocInstall\tools\chocolateyInstall.ps1 публикуется CN="Chocolatey
Software, Inc.", O="Chocolatey Software, Inc.", L=Topeka, S=Kansas, C=US и не является доверенным для данной системы.
Выполняйте сценарии только от доверенных издателей.
[V] Никогда не запускать - V  [D] Не запускать - D  [R] Запустить однажды - R  [A] Всегда запускать - A  [?] Справка
(значением по умолчанию является "D"):



0



1670 / 212 / 62

Регистрация: 03.06.2020

Сообщений: 552

03.12.2020, 15:35

5

Цитата
Сообщение от Taras99
Посмотреть сообщение

Не распознает

Какая версия powershell?

Set-ExecutionPolicy выставите RemoteSigned. От Администратора, и перезапустите powershell.

Добавлено через 7 секунд

Цитата
Сообщение от Taras99
Посмотреть сообщение

Не распознает

Какая версия powershell?

Set-ExecutionPolicy выставите RemoteSigned. От Администратора, и перезапустите powershell.



0



1743 / 438 / 131

Регистрация: 20.02.2019

Сообщений: 2,286

Записей в блоге: 40

03.12.2020, 15:38

6

Цитата
Сообщение от lesser
Посмотреть сообщение

Какая версия powershell?

скорее всего…

The Invoke-WebRequest cmdlet sends HTTP and HTTPS requests to a web page or web service. It parses the response and returns collections of links, images, and other significant HTML elements.

This cmdlet was introduced in PowerShell 3.0.



0



0 / 0 / 0

Регистрация: 14.05.2018

Сообщений: 214

03.12.2020, 15:48

 [ТС]

8

alhaos, как проверить какая версия?



0



lesser

1670 / 212 / 62

Регистрация: 03.06.2020

Сообщений: 552

03.12.2020, 15:58

9

Цитата
Сообщение от Taras99
Посмотреть сообщение

как проверить какая версия?

PowerShell
1
2
3
$Host.Version.ToString()
$PSVersionTable.PSVersion
(Get-Host).Version.ToString()



0



0 / 0 / 0

Регистрация: 14.05.2018

Сообщений: 214

03.12.2020, 17:33

 [ТС]

10

alhaos, версия программы:

PS C:\Users\Тарас> (Get-Host).Version.ToString()
2.0
PS C:\Users\Тарас>



0



1743 / 438 / 131

Регистрация: 20.02.2019

Сообщений: 2,286

Записей в блоге: 40

03.12.2020, 17:46

11

Taras99, обновиться проблема?, жди может кто ответит как через Net.WebClient делать, я пока не могу, разбираться надо.



0



㊙️

2154 / 237 / 57

Регистрация: 10.08.2018

Сообщений: 562

03.12.2020, 17:56

12

Лучший ответ Сообщение было отмечено Taras99 как решение

Решение

Цитата
Сообщение от Taras99
Посмотреть сообщение

версия программы:2.0

Еще раз:

Цитата
Сообщение от Fors1k
Посмотреть сообщение



1



0 / 0 / 0

Регистрация: 14.05.2018

Сообщений: 214

04.12.2020, 02:02

 [ТС]

13

Fors1k, спасибо большое!

Не подскажите еще, пожалуйста, в какой раздел задать вопрос по установке vagrant?
При виполнении команды vagrant up есть ошибка:

D:\vagrant>vagrant up
Bringing machine ‘default’ up with ‘hyperv’ provider…
==> default: Verifying Hyper-V is enabled…
The Hyper-V cmdlets for PowerShell are not available! Vagrant
requires these to control Hyper-V. Please enable them in the
«Windows Features» control panel and try again.

D:\vagrant>

Изначально просто была проблема с версией powershell(не проходила команда vagrant int)
Был би очень благодарен!



0



IT_Exp

Эксперт

87844 / 49110 / 22898

Регистрация: 17.06.2006

Сообщений: 92,604

04.12.2020, 02:02

Помогаю со студенческими работами здесь

Установка винды, жесткий диск разбит на двое и мне нужно поставить что бы установка была на F, а не на С
Здравствуйте, у меня жесткий диск разит на двое и мне нужно поставить что бы установка была на F,…

Установка — Установка Windows XP через DOS
Проблема не в установке. Буду краток я коверкою ОС ХР для универсальной установки .WIM файла есть…

Установка новой Windows 7 поверх старой Windows 7 без форматрирования диска (не обновление, а новая установка)
Приветствую!
Уважаемые,подскажите.Возникла проблема с виндой,в подробности вдаваться не буду,сам…

Установка — Установка 7й поверх 10й
В общем форумчане есть вопрос приспичило прям
1) стоит win 10 x64 с начала инсайда
2) приспичило…

Установка питания, Установка частоты
Помогите пожалуйста!

Установка драйвера NVidia зависает на «Установка Аудиодрайвер HD»
Каждый раз, как я устанавливаю драйвера NVidia, установка зависает на &quot;Установка Аудиодрайвер HD&quot;!…

Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:

13

Понравилась статья? Поделить с друзьями:
  • Бакси ошибка е03 что означает как исправить
  • Бакси код ошибки е113
  • Бакси ошибка е03 при включении горячей воды котел
  • Базовое соединение закрыто непредвиденная ошибка при передаче тарков
  • Бакси е06 ошибка коды