Powershell Invoke-RestMethod "Unable to connect to the remote server" - powershell

I write a very simple powershell script to post a json string to server. I have a strange issue when I execute the script.
The server is inside our intranet, the firewall is disable for all intranet server.
I tried to execute the script in different places:
Powershell window in my own computer (windows 7, powershel 5)
Powershell ISE in my computer
start powershell.exe in a command prompt in my own computer
start powershell.exe in a third party command prompt application in my own computer
Powershell window in a citrix seesion (windows 10, powershel 5)
start powershell.exe in a command prompt in a citrix seesion
I checked all of 6 places have ExecutionPolicy "RemoteSigned",
But, I can only successfully execute the script in last 3 places,
In first 3 place, I get an error
Invoke-RestMethod : Unable to connect to the remote server
At F:\Temp\test.ps1:46 char:9
+ $resp = Invoke-RestMethod -Method POST -Body $result ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [Invoke-RestMethod],
WebException
+ FullyQualifiedErrorId : System.Net.WebException,Microsoft.PowerShell.Com
mands.InvokeRestMethodCommand
Besides, I also tried Invoke-WebRequest, I got same error message.
Any idea why this is happen? What should I do with it?

I solved same problem by disabling / commenting out proxy settings in the machine.config file which I enabled to intercept network calls from my .Net application in Fiddler.
Please note that you need to restart your computer after you make change in machine.config file. And also make sure you run editor as Administrator to edit config file.
Path:
C:\Windows\Microsoft.NET\Framework64\v4.0.30319\Config\machine.config
Configuration Element:
configuration -> system.net -> defaultProxy

I had similar issue few days back and I resolved it by applying the proxy settings in the "Invoke-WebRequest" call.
Something like this;
Invoke-WebRequest -URI $url -Proxy 'http://10.10.7.11:80' -ProxyCredential $creds

Related

Why do I get a "Get-WindowSize" not implemented error when using the PowerShell call Get-Service on a remote machine?

I have a Windows 10 host machine that connects to a Hyper-V Windows 10 VM hosted on the same box.
I've been following along the Pluralsight PowerShell tutorial.
I'm trying to get the services available on a remote computer.
I can start a session on the remote computer with the following command:
Enter-PSSession -ComputerName Client1 -Credential username
Once the session has started and I am connected, I attempt to call Get-Service to identify the services on the client computer.
[Client1]: PS C:\Users\username\Documents>Get-Service
When I run the above command, I get the following error message:
Remote host method get_WindowSize is not implemented.
+ CategoryInfo : ResourceUnavailable: (:) [out-lineoutput], PSRemotingDataStructureException
+ FullyQualifiedErrorId : System.Management.Automation.Remoting.PSRemotingDataStructureException,Microsoft.PowerShell.Commands.OutLineOutputCommand
I am running the same version of PowerShell on the host and client machines (5.1.18362.145).
I assume that somehow this is an issue on the client machine?
[Client1]: PS C:\Users\username\Documents>Get-Service | out-string
That should work, maybe a bug with PowerShell or new version of Windows 10
Other link : https://social.technet.microsoft.com/Forums/en-US/67142783-2acd-4d54-aef2-8d89d71457c5/powershell-remoting-broken-in-windows-10-1903?forum=winserverTS
"Remote host method get_WindowSize is not implemented."
This happens to all Remoting Sessions started With Powershell_ISE on the Client-Side.
The workaround with Out-String sucks, it destroys the Result-Object of that call.
Best fix so far is either using not ISE or embed your remote Procedure in a Script and call it with Powershell.exe
Really annoying...and not fixed by now.
Workaround Example: Instead of using enter-pssession and then asking for a result of running services, you could use: $YourServices=Invoke-command -ComputerName <computername> -ScriptBlock {get-service}. Then you have all Service-Stats in your Object $YourServices.

WebDAV and Powershell and Windows - weird error and behaviour

We have a WebDAV site that runs on IIS. From PowerShell we try to download a folder info
Get-ChildItem \\webserver#SSL\davwwwroot\webdav\Folder1\Folder2 -Name
It says
'\\webserver#SSL\davwwwroot\webdav\Folder1\Folder2' because it does not exist.
At GetWebDAVFolderContents.ps1:33 char:10
+ $items = Get-ChildItem $url -Name
+ ~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (\\webserver#SSL\...der1\Folder2:String) [Get-ChildItem], ItemNotFoundException
+ FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.GetChildItemCommand
The folder does exist. The very strange things: we start the File Explorer on that client PC, enter an URL like https://inside.mycompany.com/it/site which is a WebDAV site on our company's SharePoint site, then it asks for a login. After successful login to this site, the PowerShell script begins to work, drops no error anymore, and can download the Folder1\Folder2 info from our WebDAV site.
Why? How can I avoid to manually enter a login information to another site to get this script work? Is it because our WebDAV site is not correctly configured under the IIS?
It happens that a local service named "WebClient" is needed to be started. By default it is "manually" start with "trigger". It seems that the powershell way it won't trigger the service start, but the explorer thing will. As it remains started the powershell script suddenly works. The solution is to change the service start to automated, and 'till now it works.

Powershell script fails during remote execution but works locally

I am attempting to execute the code below. The errors are self-explanatory but only occur when run remotely. When run locally, all the code works and I can verify that they have the desired effect by pulling content from a web server that requires Tls12 and receiving an error when I have not changed the security protocol.
$tls12 = [Enum]::ToObject([Net.SecurityProtocolType], 3072)
[Net.ServicePointManager]::SecurityProtocol = $tls12
When run on the server, they execute flawlessly. When run remotely via Invoke-Command I receive this error.
Exception setting "SecurityProtocol": "The requested security protocol
is not supported."
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : PropertyAssignmentException
+ PSComputerName : servername
Alternatively, this line of code which is fundamentally the same.
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
This also works when run on the server directly but results in this error when run remotely.
Exception setting "SecurityProtocol": "Cannot convert null to type
"System.Net.SecurityProtocolType" due to invalid enumeration values. Specify one of the following enumeration values and
try again. The possible enumeration values are "Ssl3, Tls"."
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : PropertyAssignmentException
+ PSComputerName : servername
The remote server Windows Server 2008 R2 and is running powershell 2.0. The latest Framework version installed is 4.5 release 378389. The machine I am executing from is Windows 10 running powershell 5.0 and Framework 4.6.2 in case it matters.
This is the code I am using to execute it remotely.
$webSession = New-PsSession -ComputerName servername
$cmd = {
#$tls12 = [Enum]::ToObject([Net.SecurityProtocolType], 3072)
#[Net.ServicePointManager]::SecurityProtocol = $tls12
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
}
Invoke-Command -ScriptBlock $cmd -Session $webSession
remove-pssession $webSession
If anyone has an idea or suggestion, I would greatly appreciate the help.
[Note: The remainder of this answer SHOULD be true, but ISN'T: Even though the Tls12 value is not defined in an interactive PSv2 session, it can be assigned and takes effect using the OP's workaround, [Net.ServicePointManager]::SecurityProtocol = [Enum]::ToObject([Net.SecurityProtocolType], 3072); by contrast, trying the same thing via PS remoting, using Invoke-Command -ComputerName fails for him. Upgrading PowerShell on the target machine may still be the answer, but this answer offers no explanation of the behavior.]
As Sambardo notes in a comment on the question, the symptom implies that the remote target machine doesn't support the Tls12 value:
PSv2 invariably uses a 2.0 version of the .NET framework, where TLS 1.2 is not supported - irrespective of the presence of newer .NET frameworks on a given machine.
If you run [enum]::GetNames([Net.SecurityProtocolType]) on a machine with PSv2 , you'll see that only the following values are supported:
# PSv2
> [enum]::GetNames([Net.SecurityProtocolType])
Ssl3
Tls
So the answer is to upgrade PowerShell on the remote machine.
As an aside: PowerShell's great flexibility around type conversions allows you to simply use string representations of [enum] values; e.g., the following 2 statements are equivalent:
[Net.ServicePointManager]::SecurityProtocol = 'Tls'
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls

Using powershell to connect to HTTPS sites

I have been provided a new Server 2012 box to setup.
I'm trying to use powershell to install chocolatey
iex ((New-Object System.Net.WebClient).DownloadString('https://chocolatey.org/install.ps1'))
and getting the error
Exception calling "DownloadString" with "1" argument(s): "The underlying connection was closed: An unexpected error
occurred on a receive."
At line:1 char:1
+ iex ((New-Object System.Net.WebClient).DownloadString('https://chocolatey.org/in ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : WebException
I can visit that URL in the browser.
At first I thought this was something to do with Chocolatey but then I realised that
(New-Object System.Net.WebClient).DownloadString('http://google.com'))
can download the html content
but
((New-Object System.Net.WebClient).DownloadString('https://google.com'))
fails with the same error
The underlying connection was closed: An unexpected error occurred on a receive.
The box:
is windows server 2012 build 9600
doesn't use a proxy
has the firewall turned off
I feel sure I'm doing something silly but can't see what...
--- Update ---
Based on this answer
I followed these steps:
```
1.In Control Panel, click Administrative Tools, and then double-click Local Security Policy.
2.In Local Security Settings, expand Local Policies, and then click Security Options.
3.Under Policy in the right pane, double-click System cryptography: Use FIPS compliant algorithms for encryption, hashing, and signing, and then click Enabled.
Ran gpupdate /force
```
After that the chocolatey install script can be downloaded but then fails with:
STDOUT: FIPS Mode detected - run 'choco feature enable -n useFipsCompliantChecksums'
to use Chocolatey.
When FIPS Mode is enabled, Chocolatey requires useFipsCompliantChecksums feature also be enabled.
STDERR:
---- End output of C:\ProgramData\chocolatey/bin/choco.exe list -l -r ----
Ran C:\ProgramData\chocolatey/bin/choco.exe list -l -r returned 1
Still feels like the GPO change shouldn't be necessary
It turns out this was as a result of TLS 1.0 being disabled in our server images in order to comply with PCI DSS 3.1.
Rolling back that change to the image resolved the powershell issue.
In the short term we can run
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 before using System.Net.WebClient but I'd like to find a way to enforce that at a machine level too...
I logged this with Chocolatey and they resolved the issue \o/
try this :
$WBC = New-Object System.Net.WebClient
$WBC.DownloadString("https://google.com")

How to Specify the Password to repadmin.exe via Remote PowerShell Session

I have some issues with repadmin.exe utility
I have the following setup:
Windows Server 2012R2 with ADDS installed running inside of VMWare VM
Windows 8.1 Pro (host for VMware, my home desktop). My host is NOT a part of the domain
I do the following:
Open PowerShell ISE on my Windows 8.1 and establish remote connection to my DC (PowerShell ISE -> File -> New Remote PowerShell Tab)
Once I`m connected remotely to DC I run the following command
repadmin.exe /syncall
and get the following error:
CALLBACK MESSAGE: Error contacting server ad864315-1f78-4266-a7c2-2d6f9cde2f15._msdcs.arvo.local (network error): 5 (0x5):
Access is denied.
CALLBACK MESSAGE: Error contacting server a5904e4b-dff2-4b75-b856-45593a48d84e._msdcs.arvo.local (network error): 5 (0x5):
Access is denied.
SyncAll exited with fatal Win32 error: 8440 (0x20f8):
The naming context specified for this replication operation is invalid.
I found here http://technet.microsoft.com/de-de/library/cc811552%28v=ws.10%29.aspx that is is possible to specify username and password for repadmin using /u: and /pw: keys. Besides it is possible to pass the password using 2 methods - either specify it explicitly in command line or put * (asterisks) and I will be prompted to enter the password. The second option is more preferable.
So I can do ether this way (specify the password in command line):
repadmin.exe /u:domain_name\user_name /pw:p#ssw0rd /syncall
or use asterisks and enter password after this command:
repadmin.exe /u:domain_name\user_name /pw:* /syncall
Asterisks works locally in PowerShell on the server, but if I run it using Remote PowerShell Session, I get the following error:
repadmin : Password: Failed to query the console mode.
+ CategoryInfo : NotSpecified: (Password: Faile...e console mode.:String) [], RemoteException
+ FullyQualifiedErrorId : NativeCommandError
Is there any workaround? I would not specify the password clearly in command line as it is not secure.
Thanks!
You might try something like this inside the remote PowerShell session:
$MyCreds = Get-Credential
Start-Process -FilePath repadmin.exe -ArgumentList "/syncall" -Credential $MyCreds
That way, you could leverage the security of PowerShell's credential management and just run the process under an account that has access to perform the replication.