Invoke-WebRequest with PScredentials - powershell

I'm trying to retrieve a file from an external HTTPS site. My code below works a treat in POSH 3.0, but in POSH 4.0, not so much. The message I get is below. Anyone experiencing the same issue, know how to resolve this or a workaround?
Invoke-WebRequest :
Authentication Required.
You must be authenticated to access this URL.
URL: https://www.mywebsite.com
User name:
At line:4 char:1
+ Invoke-WebRequest -Uri https://www.mywebsite.com/report.pdf ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-WebRequest], WebException
+ FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeWebRequestCommand
$pw = ConvertTo-Securestring -AsPlainText -Force -String "myPWD"
$cred = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList ("myUser",$pw)
Invoke-WebRequest -Uri https://www.mywebsite.com/report.pdf -Credential $cred -OutFile C:\report.pdf

So I found that even though I could access the website and retrieve my content with my browser, the McAfee Web Gateway was preventing Powershell from doing the same thing. Once we whitelisted the URL, BOOM, no problems. Thanks everyone for the additional ideas in helping me troubleshoot this!

Related

downloading a web page with powershell using a x.509 certificate

I am having a problem with PowerShell on Windows 10 trying to download a file from a site that uses an X.509 certificate to authenticate the client. I have this certificate installed in my certificate store in IE and I also have exported the PFX file. Here's what I have tried:
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::ssl3 and also tls12
trying to get the certificate using System.Security.Cryptography.X509Certificates.X509Certificates2
trying to set the credentials via Get-Credential and then passing it
I've used the Invoke-WebRequest command as well as System.Net.WebClient trying to get this to work. The error message I'm getting is as follows:
PS P:\PSScripts> P:\PSScripts\DownloadSslHtml.ps1
VERBOSE: GET https://somewebsite.com/GetReports.do?reportTypeId=1234
with 0-byte payload
Invoke-WebRequest : The request was aborted: Could not create SSL/TLS secure channel.
At P:\PSScripts\DownloadSslHtml.ps1:20 char:1
+ Invoke-WebRequest -Uri $url -UserAgent ([Microsoft.PowerShell.Command ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-
WebRequest], WebException + FullyQualifiedErrorId :
WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeWebRequestCommand
Now I have seen a lot of people with this "SSL/TLS secure channel" error and they fixed it by specifying the encryption method as TLS12 or SSL3, neither of which is working for me. I'm confused how to proceed. Any thoughts? The website is using TLS1.2 AES with 256 bit encryption ECDH 256 bit exchange.
EDIT: Here's my powershell code:
$url = "https://somewebsite.com/GetReports.do?reportTypeId=1234"
$outputFile = "P:/DownloadedData/file.html"
$PFXPath = "P:/Properties/Config/mycert.pfx"
$PFXPassword = "cert_password"
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::tls12
$cert = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2
$cert.Import($PFXPath,$PFXPassword,'DefaultKeySet')
Invoke-WebRequest -Uri $url -UserAgent ([Microsoft.PowerShell.Commands.PSUserAgent]::InternetExplorer) -Certificate $cert -OutFile $outputFile -Verbose
I changed this line:
$cert.Import($PFXPath,$PFXPassword,'DefaultKeySet')
to this:
$cert.Import($PFXPath,$PFXPassword,'UserKeySet')
And now it works!

Use Connect-SPOService with Powershell 6 (core version)

I'm trying to connect to a sharepoint environment and I want to do that with Powershell version 6. Why? Eventually, I want to put the PS commands in a .net core 3 application. And as far as I know I cannot use PS5.1 in .net core.
It is about this powershell script:
Import-Module -Force -name Microsoft.Online.SharePoint.PowerShell;
Import-Module -Force -name Microsoft.Online.SharePoint.PowerShell -DisableNameChecking;
$username = 'admin#shootme.com';
$password = 'right now';
$cred = New-Object -TypeName System.Management.Automation.PSCredential -argumentlist $userName, $(convertto-securestring $Password -asplaintext -force);
Connect-SPOService -Url https://shootme.sharepoint.com -Credential $cred;
When I try this in the default PS 5.1 it just works fine. When I try this with PS 6.2.3, I get an error:
Connect-SPOService : The remote server returned an error: (400) Bad Request.
At line:1 char:1
+ Connect-SPOService -Url https://shootme.sharepoint.com -Credent ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [Connect-SPOService], WebException
+ FullyQualifiedErrorId : System.Net.WebException,Microsoft.Online.SharePoint.PowerShell.ConnectSPOService
Does the newer Powershell have different syntax orso, of what am I doing wrong?
Also, maybe there is a way to run scripts in ps 5.1 when running them in .net core?
Have you tried connecting manually by removing the credentials portion and letting it prompt you for a login and test if that resolves successfully?
Edit: I do know you can also call powershell from a .bat like so:
powershell -version 2 .\xyz.ps1
But not knowing what you're going for exactly makes it tough to suggest if that's even a viable option.

Copy-Item to networkpath: incorrect user name or password

I have a PowerShell v1 script, that is triggerd by a PLC. It should copy a file from the desktop of the embedded PC to a network path.
If I run the script manually it works just fine, but if the script is triggered by the PLC I will get the following error:
+ CategoryInfo : NotSpecified: (:) [Copy-Item], IOException
+ FullyQualifiedErrorId : System.IO.IOException,Microsoft.PowerShell.Commands.CopyItemCommand
copy-item : The user name or password is incorrect.
Any tips, why I get this error, would be very much appreciated!
Thanks for your help #TheIncorrigible1 after reading your comment I found the problem!
The problem was, that the script started by the plc runs with another user than the manually started script.
So the workaround is to first start powershell with the correct credentials with another script. For example like so:
$usr = 'XXX'
$paswrd = 'XXX'
$securePassword = ConvertTo-SecureString $paswrd -AsPlainText -Force
$credential = New-Object System.Management.Automation.PSCredential $usr, $securePassword
$args = "/path to your script"
Start-Process powershell.exe -Credential $credential -ArgumentList ("-file $args")
downside... password in plain text...

Running Set-AzureRmAppServicePlan from Automation script (RunBook)

I'm trying to run Set-AzureRmAppServicePlan from automation runbook but getting
Set-AzureRmAppServicePlan : Run Login-AzureRmAccount to login. At
line:20 char:1
+ Set-AzureRmAppServicePlan -ResourceGroupName "...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [Set-AzureRMAppServicePlan], PSInvalidOperationException
+ FullyQualifiedErrorId : InvalidOperation,Microsoft.Azure.Commands.WebApps.Cmdlets.AppServicePlans.SetAzureAppServicePlanCmdlet
Note that actual runbook authentication using Automation Credential is successful.
And I can run this script from local powershell using
Login-AzureRmAccount
Add-AzureRmAccount
Set-AzureRmAppServicePlan...
Is it possible at all to run this from automation without interactive login?
Thanks
Pavel
figure it out.. pretty simple instead of
Add-AzureAccount - which is used in sample runbook Get-AzureVMTutorial created automatically
need to use
Add-AzureRmAccount
for use with Azure Resource Manager cmdlet requests like
Set-AzureRmAppServicePlan
Leaving question / answer here.. might still help someone
If you are not using MFA, pls see the following cmds, replace 'yourPassword', 'yourUserName', 'yourEnvironment', 'yourSubscriptionId', 'yourTenantId' with your own message and put it to your script then you can login without interactive page.
$userPassword = ConvertTo-SecureString -String "yourPassword" -AsPlainText -Force
$psCred = new-object -typename System.Management.Automation.PSCredential -argumentlist 'yourUserName', $userPassword
$credential = Get-Credential -Credential $psCred
add-azureRmAccount -EnvironmentName 'yourEnvironment' -credential $credential -subscriptionId 'yourSubscriptionId' -tenant 'yourTenantId'

Calling batch with user creds not working in powershell

I have a powershell script that contains the following
$username = 'username'
$password = 'password'
$cred = New-Object System.Management.Automation.PSCredential -ArgumentList #($username,(ConvertTo-SecureString -String $password -AsPlainText -Force))
start-process -FilePath $deploymentAppPath -Credential $cred
Yet when I execute this I get the following error.
start-process <<<< -FilePath $deploymentAppPath -Credential $cred
+ CategoryInfo : InvalidOperation: (:) [Start-Process], InvalidOperationException
+ FullyQualifiedErrorId : InvalidOperationException,Microsoft.PowerShell.Commands.StartProcessCommand
While I don't think it is probably obvious, my end goal here is to call the batch file with the user credentials that I specify.
I would start by removing the use of securestring. Some things just don't seem to work with it in my experiences.
It appears that your process is local, so you're not transmitting the u/p over the wire. Is the securestring really neccessary (considering that the u/p is in the script and available to whoever has perms to the script)?
I believe you do not have the right version of windows powershell to use the start-process command. I ran this and it worked other than the obvious -FilePath error that I did not set. Where as you seem to be getting the basic 'command does not exist' exception. To check your version number use the get-host cmdlet. Run get-host | select version and if it outputs 1.0 to console you should go Here to get a 2.0 version.