Using powershell to connect to HTTPS sites - powershell

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")

Related

Cannot export site template

I'm trying to get site template and getting error:
PS C:\Windows\system32> Get-PnPSiteTemplate -Out template.xml
Get-PnPSiteTemplate : GetAccessTokenAsync() called without an ACS token generator. Specify in AuthenticationManager constructor the authentication parameters
At line:1 char:1
Get-PnPSiteTemplate -Out template.xml
CategoryInfo : WriteError: (:) [Get-PnPSiteTemplate], ArgumentException
FullyQualifiedErrorId : EXCEPTION,PnP.PowerShell.Commands.Provisioning.Site.GetSiteTemplate
Version:
pnp.powershell 1.6.0
I had the same issue and after quite some time invested in troubleshooting, I've figured out that the export gets interrupted once it iterates over a list. It is not related to the site you're trying to export because it happened also on other, newly created sites.
It turned out that the problem was that the PNP Module requires Admin Consent since it can manipulate almost all components of O365.
Solution: Connect to the site with the following command:
Connect-PnPOnline -interactive -URL "Your Site Url"
Provide admin consent to PnP and then try to export the site template with:
Get-PnPSiteTemplate -Out "File Location" # Use handlers and other params if needed
If the prompt window doesn't show up, run the following command first:
register-pnpmanagementshellaccess # See notes before running this cmdlet
Note: Admin consent requires additional permissions and SharePoint Admin role is not enough! So either ask a Global Admin to consent for you or ask for additional AD permissions. If I'm not mistaken Application Administrator role should be the right choice.
This seems to have worked for me.
Get-PnPSiteTemplate -out template.xml -ExcludeHandlers Lists,ApplicationLifecycleManagement
It seems the lists and ALM sections need an ACS token generator and that fails with UseWebLogin.
This is what I got on version 1.7.10, but I have used 1.7.0 and 1.5.0 and seen the same issues. I don't know if the older versions have more problematic modules.
Method: I found this resolution by running Set-PnPTraceLog -on -logfile log.txt -Level Debug and Set-PnPTraceLog -off, then reviewing log file to see which module failed.
I may use the Export-PnPListToSiteTemplate and see how that goes in getting list XML for the template file.
I had the same issue with PnP.PowerShell 1.6.0. I was using Connect-PnPOnline command with -UseWebLogin flag because my account had multi factor authentication turned on.
My solution was to disable MFA for my user and connect without the "-UseWebLogin" flag. Then Get-PnPSiteTemplate command worked without any issues.
I'm not sure why this is happening, but I'll use this workaround for now :)

Cannot Uninstall IoT Edge on Windows Server

I need to swap an IoT Edge device on Windows from one IoT Hub to another. I understand that current logic forces me to Uninstall IoT-Edge and install it again.
The problem is I get the following error trying to run this script:
{Invoke-WebRequest -useb aka.ms/iotedge-win} | Invoke-Expression; `
Uninstall-IoTEdge
I get this in return:
Invoke-Native : The term 'cmd' 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:1748 char:28
+ ... ersString = Invoke-Native "$dockerExe ps --all --format ""{{.ID}}""" ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (cmd:String) [Invoke-Native], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException,Invoke-Native
The Powershell is elevated as Admin. Am my missing some PATH variables? Any Ideas?
would you please run below commands in PowerShell window and share the results?
Get-Command "docker.exe"
Write-Host $env:ProgramFiles\iotedge-moby
check if the path exists or not.
do you know which version of iotedge service you installed? if the service is running, you can run "iotedge version" to find it out.
Thanks for the suggestion, but did manage to find workaround by removing docker with the help of this script:
https://success.docker.com/article/how-to-completely-remove-docker-in-windows-10
As fas as IOT Edge version it is 1.0.7 as 1.0.8. does not work in transparent gateway mode with Node-Red MQTT node (MS advised to wait for 1.0.9 where this bug will be fixed).

Fix "Unable to check the status of the firewall" of `Set-WSManQuickConfig`

Why Enable-PSRemoting/Set-WSManQuickConfig can not "check the status of the firewall" running under Administrator on Windows 2012R2, Azure WebRole? How to fix this?
PS D:\Users\***User> enable-psremoting -force
WinRM is already set up to receive requests on this computer.
Set-WSManQuickConfig : <f:WSManFault xmlns:f="http://schemas.microsoft.com/wbem/wsman/1/wsmanfault" Code="2"
Machine="localhost"><f:Message><f:ProviderFault provider="Config provider"
path="%systemroot%\system32\WsmSvc.dll"><f:WSManFault xmlns:f="http://schemas.microsoft.com/wbem/wsman/1/wsmanfault"
Code="2" Machine="RD***CA2"><f:Message>Unable to check the status of the firewall.
</f:Message></f:WSManFault></f:ProviderFault></f:Message></f:WSManFault>
At line:69 char:17
+ Set-WSManQuickConfig -force
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [Set-WSManQuickConfig], InvalidOperationException
+ FullyQualifiedErrorId : WsManError,Microsoft.WSMan.Management.SetWSManQuickConfigCommand
OS Name: Microsoft Windows Server 2012 R2 Datacenter. OS Version: 6.3.9600 N/A Build 9600. Powershell: 4.0
PS.
Yes, there are:
Error PSRemoting using Session and CredSSP. No clear solution
Winrm quick config shows error . Rebooting/reimaging the instance does not help.
https://support.microsoft.com/en-us/kb/2697738. Hotfix (2012 year!) is not installed but then it needs installed each deployment?
https://technet.microsoft.com/en-us/library/hh849694.aspx. Has this message but that is for "client versions"
http://terenceluk.blogspot.ru/2012/05/executing-command-winrm-quickconfig.html Restarting firewall does not help
How to enable powershell remoting in Powershell V3?. No "HKLM:\SYSTEM\Policies\Microsoft\Windows Firewall" to change. restarting firewall service does not help.
Update.
Other valuable refs:
http://www.thomasmaurer.ch/2011/01/quick-powershell-remoting-guide/
http://www.davidaiken.com/2011/01/12/enable-powershell-remoting-on-windows-azure/
Get-Help about_Remote_Troubleshooting
In my case running this helped (manually creates the firewall rule):
netsh advfirewall firewall add rule name="Windows Remote Management (HTTP-In)" dir=in action=allow service=any enable=yes profile=any localport=5985 protocol=tcp
Taken from http://www.davidaiken.com/2011/01/12/enable-powershell-remoting-on-windows-azure/
I tried to enable winrm for ansible testing, nothing helped, the rules were in place. Changing the Windows display language from czech to english fixed my problem.

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

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

Windows Azure Powershell command Get-AzureWebsite results in error String was not recognized as a valid Boolean

I'm trying to manage some of my Azure Services via Powershell, using http://windowsazurewebsitescheatsheet.info/#powershell as a starting point. I was able to download and import my subscription settings just fine (Import-AzurePublishSettingsFile and Select-AzureSubscription)
After choosing my subscription, I'm attempting to run the Get-AzureWebsite command to view all of my websites, and continue onward from there. When I run that command, however, I get the following:
Import-AzurePublishSettingsFile "C:\AzureCredentials.publishsettings"
Select-AzureSubscription "My Azure Subscription"
Get-AzureWebsite
Get-AzureWebsite : String was not recognized as a valid Boolean.
At line:1 char:1
+ Get-AzureWebsite
+ ~~~~~~~~~~~~~~~~
+ CategoryInfo : CloseError: (:) [Get-AzureWebsite], FormatException
+ FullyQualifiedErrorId : Microsoft.WindowsAzure.Commands.Websites.GetAzureWebsiteCommand
Anyone have similar issues? I get this error if I run the command as stated above, or if I specify the name of my website. TIA for any help!
This might be related to a known issue enumerating a sites with SSL bindings
There was new release of Windows Azure Powershell released on 02/12. Please try with the new version.
Please run the command again with -Debug turned on, this will display request and response messages and make it easier to pinpoint the issue.