Error downloading files with DownloadFile in powershell 2 - powershell

I have the need to download files under powershell 2.
Since Invoke-WebRequest is not supported in version 2, I try to use DownloadFile but I always get the same error and I don't know how to fix it.
PS C:\Users\user> [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
:: : Exception setting "SecurityProtocol": "Cannot convert null to type "System.Net.SecurityProtocolType" due to invali
d enumeration values. Specify one of the following enumeration values and try again. The possible enumeration values ar
e "Ssl3, Tls"."
At line:1 char:28
+ [Net.ServicePointManager]:: <<<< SecurityProtocol = [Net.SecurityProtocolType]::Tls12
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : PropertyAssignmentException
PS C:\Users\user> $client = new-object System.Net.WebClient
PS C:\Users\user> $client.DownloadFile("https://web.com/test.txt", "C:\Users\user\Desktop\test.txt")
DownloadFile : Exception calling "DownloadFile" with "2" argument(s): "The underlying connection was closed: An unexpec
ted error occurred on a send."
At line:1 char:21
+ $client.DownloadFile <<<< ("https://web.com/test.txt", "C:\Users\user\Desktop\test.txt")
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : DotNetMethodException
What I can do?

If you are getting an error setting the TLS version, you may want to check which protocols are available:
[Net.SecurityProtocolType]::GetValues( 'Net.SecurityProtocolType' )
However, I don't know how the protocol availability will be affected by using such an old version. Moreover, I don't know how specific protocol settings on a given system affect the availability of protocols either at large or as returned by the above command.
In fact, I would point out the error itself only reflects SSL3 & Tls. On my system when I enter an invalid enumerator the error reports Ssl3,Tls,Tls11,Tls12,Tls13 as choices. While my system is configured to disable everything below Tls12 and has no settings defined for Tls13.
The best assumption I can make is .Net 2.0 which is used with PowerShell 2.0 cannot use Tls12 as it's not present in the enumerators and based on comparison with my system the enums aren't affected by explicit enabling/disabling of protocols.
In any case, I think you have to clear up the first error before you worry about the second. The second error may well be due to the TLS incompatibility. The easiest way to do this would be to upgrade PowerShell (along with the required .Net version). PowerShell 2.0 can coexist with Windows PowerShell 5.1 though you may have to launch with the -Version 2.0 parameter. Also, make sure the engine is installed as a Windows feature. DISCLAIMER: verify all that on your own.
I know the Windows PowerShell 2.0 Engine (PowerShell-V2) was available as a feature at least as late as Windows 2012 R2.
I would also point out that PowerShell 7.x (aka PowerShell Core) can be installed side by side with Windows PowerShell. Potentially this could sidestep the aforementioned complications, allowing you to do run the task at hand...

Related

InvalidCastException when trying to obtain UserPrincipal.Current

I have a PowerShell script which checks the currently signed in user as part of its start-up process. I'm using .Net to do this by adding the assembly:
Add-Type -AssemblyName System.DirectoryServices.AccountManagement
$cUser = [System.DirectoryServices.AccountManagement.UserPrincipal]::Current
For almost everyone this works fine and I get a UserPrincipal object that I can use elsewhere, however there are a couple of users who get the following error when running it:
Unable to cast object of type 'System.DirectoryServices.AccountManagement.GroupPrincipal' to type 'System.DirectoryServices.AccountManagement.UserPrincipal'. At line:2 char:1
+ [System.DirectoryServices.AccountManagement.UserPrincipal]::Current
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : OperationStopped: (:) [], InvalidCastException
+ FullyQualifiedErrorId : System.InvalidCastException
This is on a standard Windows 10 20H2 install and doesn't matter if PowerShell is running elevated or not. I've never seen this call return anything other than a UserPrincipal before, so I would be grateful for any advice: is this something I can deal with in code, or is there some underlying issue with the machines that are returning this exception?
I don't know if this is what you're looking for:
$cUser = Get-ADUser $Env:Username -Properties *
This has the most important attributes that you can use for whatever you want later on. It provides as much attribute as the code you posted that didn't work for some of the user.

Word as COM object has no attributes/ability to set attributes

I'm sorry that this is quite alien to me, but I had a previously working script that functioned like the following:
$wd = new-object -comobject word.application
but when I print the COM object it has empty/blank values for all attributes.
PS C:\Users\XXX> $wd
Application :
Creator :
Parent :
Name :
Documents :
Windows :
ActiveDocument :
ActiveWindow :
Selection :
And it cannot set any or perform any functions
PS C:\Users\XXX> $wd.Visible = $true
Exception setting "Visible": "Unable to cast COM object of type 'Microsoft.Office.Interop.Word.ApplicationClass' to interface type 'Microsoft.Office.Interop.Word._Application'. This
operation failed because the QueryInterface call on the COM component for the interface with IID '{00020970-0000-0000-C000-000000000046}' failed due to the following error: Error loading
type library/DLL. (Exception from HRESULT: 0x80029C4A (TYPE_E_CANTLOADLIBRARY))."
At line:1 char:1
+ $wd.Visible = $true
+ ~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], SetValueInvocationException
+ FullyQualifiedErrorId : ExceptionWhenSetting
I tried browsing related questions but was unable to see if the mistakes are exactly identical. I've run all Windows updates and did a repair installation of Office. (Running Windows 10 and Office 2013)
Sometimes Word/Excel/PPT COM Objects are acting wildly. Thus using these is not recommended for automation purposes by Microsoft itself (sorry but couldn't find the source). But whatever personally I use those all the time :).
System Restore or closing and repoening the Powershell Session actually fixes those problems for me.
Unfortunately I couldn't figured out a programmatic way to handle this yet. So looking forward for further answers. (+1)

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

Exception creating client using AWS SDK

I am currently using the following sequence of commands in a Windows 7 PowerShell window.
Add-Type -Path "C:\Program Files (x86)\AWS SDK for .NET\bin\Net35\AWSSDK.dll"
$secretKeyID="ABCDEFGHIJKLMNOPQRS"
$secretAccessKeyID="LONGKEYBLAHBLAHBLAHBLAHBLABLAH"
$AWSclient=[Amazon.AWSClientFactory]::CreateAmazonS3Client($secretKeyID,$secretAccessKeyID)
However, I get this exception below. Please let me know what Im doing wrong. This is what I see most people using successfully.
Exception calling "CreateAmazonS3Client" with "2" argument(s): "No RegionEndpoint or ServiceURL configured"
At line:1 char:1
+ $oAWSclient=[Amazon.AWSClientFactory]::CreateAmazonS3Client($secretKeyID,$secret ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : AmazonClientException
One thing that I think is a problem is that my bucket is not checked for 'enable website hosting'. Does this need to be set to true? I just want to upload a file to the bucked via powershell script.
Duh... I realized that I need to use the AWS Powershell because it has all the settings built into it. Im not exactly sure how to properly refer to this version of powershell, but it is available after installing the AWS SDK.
Since the error specifically states that you're missing the RegionEndpoint or ServiceURL, you could also just include one of them. Since you're connecting to S3, all you need is to include the RegionEndpoint.
Add-Type -Path "C:\Program Files (x86)\AWS SDK for .NET\bin\Net35\AWSSDK.dll"
$secretKeyID="ABCDEFGHIJKLMNOPQRS"
$secretAccessKeyID="LONGKEYBLAHBLAHBLAHBLAHBLABLAH"
$client = [Amazon.AWSClientFactory]::CreateAmazonS3Client($secretKeyID, $secretAccessKeyID, [Amazon.RegionEndpoint]::USEast1)
(Replace USEast1 with the value configured with your S3 Bucket)

Windows RT Powershell (PermissionDenied) on New-Object

I am trying to instantiate an object in Powershell for Windows RT, but keep getting the following error.
PS > $foo = New-Object System.Security.Cryptography.SHA1Managed
New-Object : Cannot create type. Only core types are supported in this language mode.
At line:1 char:8
+ $foo = New-Object System.Security.Cryptography.SHA1Managed
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : PermissionDenied: (:) [New-Object], PSNotSupportedException
+ FullyQualifiedErrorId : CannotCreateTypeConstrainedLanguage,Microsoft.PowerShell.Commands.NewObjectCommand
I just spent the last thirty minutes engaged in some pretty heavy Google-fu and was unable to find anything even close to a similar problem, let alone an answer. My hope is that I just need to configure something; my fear is that Windows RT ships with a crippled version of Powershell.
Does anyone know which case it is?
Yup, Windows RT ships with a locked down version of PowerShell - it operates in ConstrainedLanguageMode which prevents most interaction (prop setters/method calls) with .NET. It also has a limited command set IIRC.