How to fix DLL LoaderExceptions in PowerShell - powershell

I'm trying to load a .dll of itext7, but if I use this
Add-Type -Path "D:\Eigene\Packages\itext7.7.1.5\lib\net40\itext.kernel.dll"
I get the following exception (translated from german):
Add-Type : Add-Type : Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information.
In Zeile:2 Zeichen:1
+ Add-Type -Path "D:\Eigene\Packages\itext7.7.1.5\lib\net40\itext.kerne ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [Add-Type], ReflectionTypeLoadException
+ FullyQualifiedErrorId : System.Reflection.ReflectionTypeLoadException,Microsoft.PowerShell.Commands.AddTypeCommand
When I use:
try { Add-Type -Path "D:\Eigene\Packages\itext7.7.1.5\lib\net40\itext.kernel.dll" }
catch { $_.Exception.LoaderExceptions }
It says (also translated from german):
The File or Assembly "BouncyCastle.Crypto, Version=1.8.1.0,
Culture=neutral, PublicKeyToken=0e99375e54769942" or a dependency of
it was not found. The system can not find the specified file.
How can I fix this?
EDIT:
I found a BouncyCastle dll on my system that it also downloaded when I installed the itext7 package but it also doesn't work, if I load "D:\Eigene\Packages\Portable.BouncyCastle.1.8.5\lib\net40\BouncyCastle.Crypto.dll" before i load the itext.kernel.dll.

Your assembly is looking for a different version than you have.
I'm not sure if you can do an assembly binding in powershell like you could with an application where you could bind an older assembly to a new one example:
https://learn.microsoft.com/en-us/dotnet/framework/deployment/configuring-assembly-binding-redirection
Your error is asking you to load the dll of version 1.8.1.0 with the public token of: PublicKeyToken=0e99375e54769942
Generally the assembly publisher isn't changing their public token although it is technically possible bouncy castle could so you likely don't need to specify that.
Anyway you need to find the older version (seems like you have 1.8.5). It is likely these are compatible, but best / safest bet is to use the same assembly the one you are loading needs.
You may find some help here if you need to do binding redirection to the newer assembly: Powershell - Assembly binding redirect NOT found in application configuration file

Related

How to load StackExchange.Redis.dll into powershell?

I'm trying to create a powershell script to clear a redis cache, it's in Azure but I don't think that's relevant. I've seen 2 examples which I'm trying to copy where people have loaded StackExchange.Redis.dll into their script: https://www.powershellgallery.com/packages/Saritasa.Redis/1.2.0/Content/Saritasa.Redis.psm1 and Clearing Azure Redis Cache using PowerShell during deployment.
I've downloaded the current StackExchange.Redis.dll from nuget.org. I've tried to load it on 2 servers, one with .Net 4.61 installed, the other with .Net 4.8. I get the same problem on both.
If I try to use [System.Reflection.Assembly]::LoadFrom I get as below:
PS E:\redis\stackexchange.redis.2.2.88\lib\net461> dir
Directory: E:\redis\stackexchange.redis.2.2.88\lib\net461
Mode LastWriteTime Length Name
---- ------------- ------ ----
-a--- 05/11/2021 00:42 637440 StackExchange.Redis.dll
-a--- 05/11/2021 00:42 705989 StackExchange.Redis.xml
PS E:\redis\stackexchange.redis.2.2.88\lib\net461> [System.Reflection.Assembly]::LoadFrom("E:\redis\stackexchange.redis.
2.2.88\lib\net461\StackExchange.Redis.dll")
GAC Version Location
--- ------- --------
False v4.0.30319 E:\redis\stackexchange.redis.2.2.88\lib\net461\StackExchange.Redis.dll
PS E:\redis\stackexchange.redis.2.2.88\lib\net461> [StackExchange.Redis.ConnectionMultiplexer]::Connect($myConnectionStr
ing)
Unable to find type [StackExchange.Redis.ConnectionMultiplexer]: make sure that the assembly containing this type is
loaded.
At line:1 char:1
+ [StackExchange.Redis.ConnectionMultiplexer]::Connect($myConnectionString)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (StackExchange.R...tionMultiplexer:TypeName) [], RuntimeException
+ FullyQualifiedErrorId : TypeNotFound
PS E:\redis\stackexchange.redis.2.2.88\lib\net461>
If I try to use Add-Type I get:
PS E:\redis\stackexchange.redis.2.2.88\lib\net461> Add-Type -AssemblyName .\StackExchange.Redis.dll
Add-Type : Could not load file or assembly '.\\StackExchange.Redis.dll' or one of its dependencies. The given assembly
name or codebase was invalid. (Exception from HRESULT: 0x80131047)
At line:1 char:1
+ Add-Type -AssemblyName .\StackExchange.Redis.dll
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [Add-Type], FileLoadException
+ FullyQualifiedErrorId : System.IO.FileLoadException,Microsoft.PowerShell.Commands.AddTypeCommand
PS E:\redis\stackexchange.redis.2.2.88\lib\net461>
I've looked through the dependencies in nuget.org, I saw one non-Microsoft one called Pipelines.Sockets.Unofficial which I also downloaded and got the same thing. There's a whole hierarchy of other dependencies which I think are all part of .Net, surely I haven't got to download them all if .Net is installed on the server? Thanks for any help, I've been trying all day!
I'll put some things I learned above my code in case someone as inexperienced as me reads this. These points aren't in any order:
To download a nuget package for use by powershell, the easiest way is to use the Install-Package cmdlet, for example:
Install-Package -Name System.IO.Pipelines -ProviderName NuGet -SkipDependencies -Destination C:\Stackexchange.Redis-packages -RequiredVersion 5.0.1
Note that -SkipDependencies is needed because without it Install-Package gave me an error message about a circular dependency, described in https://endjin.com/blog/2020/12/how-to-consume-a-nuget-package-in-powershell. You have to download the dependencies yourself!
The alternative is: in nuget.org click the download link to download the .nupkg file, rename it to .zip, extract the files, then in File Explorer right-click the dll file, click Properties, Unblock.
I thought this app was great for showing the DLL dependencies of a DLL, it shows the whole heirarchy of dependencies and if they're found or not https://github.com/lucasg/Dependencies
To get the assembly versions of dll files in powershell:
Get-ChildItem -Filter *.dll -Recurse | Select-Object Name,#{n='FileVersion';e={$_.VersionInfo.FileVersion}},#{n='AssemblyVersion';e={[Reflection.AssemblyName]::GetAssemblyName($_.FullName).Version}}
from Get file version and assembly version of DLL files in the current directory and all sub directories
When loading DLLs, Add-Type behaves differently from [System.Reflection.Assembly]::LoadFrom(). Add-Type seems to load dependencies which can be useful. If Add-Type -Literalpath <dllFileName> fails with an error message “Add-Type : Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more
information” you can get the DLL it was looking for with $error[0].Exception.GetBaseException().LoaderExceptions https://www.reddit.com/r/PowerShell/comments/7a4vw6/addtype_how_do_i_retrieve_the_loaderexceptions/
To get round the situation where DLLs in the heirarchy have a dependency on different versions of the same DLL (which seems to be very common) this guy's solution is simply fantastic. I couldn't find any alternative and it seems to work perfectly https://www.azurefromthetrenches.com/powershell-binding-redirects-and-visual-studio-team-services/
The DLLs I used
I ended up with these DLL files in a folder:
Name FileVersion AssemblyVersion
---- ----------- ---------------
Microsoft.Bcl.AsyncInterfaces.dll 6.0.21.52210 6.0.0.0
Pipelines.Sockets.Unofficial.dll 2.2.0.45337 1.0.0.0
StackExchange.Redis.dll 2.2.88.56325 2.0.0.0
System.Buffers.dll 4.6.28619.01 4.0.3.0
System.IO.Pipelines.dll 5.0.120.57516 5.0.0.1
System.Memory.dll 4.6.28619.01 4.0.1.1
System.Numerics.Vectors.dll 4.6.26515.06 4.1.4.0
System.Runtime.CompilerServices.Unsafe.dll 6.0.21.52210 6.0.0.0
System.Threading.Channels.dll 6.0.21.52210 6.0.0.0
System.Threading.Tasks.Extensions.dll 4.6.28619.01 4.2.0.1
The code It's not finished, but shows the Stackexhange.Redis DLL loaded and used.
# Code to load the DLLs needed for Stackexchange.Redis.dll and clear the cache
# Basically copied from https://www.azurefromthetrenches.com/powershell-binding-redirects-and-visual-studio-team-services/
$DllPath = 'C:\Stackexchange.Redis-packages\combined DLLS'
$redisHostName = '<my cache name here>.redis.cache.windows.net'
$redisConnectionString = '<my cache name here>.redis.cache.windows.net:6380,password=<my cache password here>,ssl=True,abortConnect=False'
# Load DLL assemblies into memory, required by the event handler below
$SystemBuffersDll = [System.Reflection.Assembly]::LoadFrom("$DllPath\System.Buffers.dll")
$SystemRuntimeCompilerServicesUnsafeDll = [System.Reflection.Assembly]::LoadFrom("$DllPath\System.Runtime.CompilerServices.Unsafe.dll")
$SystemMemoryDll = [System.Reflection.Assembly]::LoadFrom("$DllPath\System.Memory.dll")
$SystemSystemThreadingTasksExtensionsDll = [System.Reflection.Assembly]::LoadFrom("$DllPath\System.Threading.Tasks.Extensions.dll")
$SystemIoPipelinesDll = [System.Reflection.Assembly]::LoadFrom("$DllPath\System.IO.Pipelines.dll")
$MicrosoftBclAsyncInterfacesDll = [System.Reflection.Assembly]::LoadFrom("$DllPath\Microsoft.Bcl.AsyncInterfaces.dll")
$PipelinesSocketsUnofficialDll = [System.Reflection.Assembly]::LoadFrom("$DllPath\Pipelines.Sockets.Unofficial.dll")
$SystemThreadingChannelsDll = [System.Reflection.Assembly]::LoadFrom("$DllPath\System.Threading.Channels.dll")
# Event handler to be run when the AssemblyResolve event occurs
$onAssemblyResolveEventHandler = [System.ResolveEventHandler] {
param($sender, $e)
Write-Verbose "Assembly resolve event for $($e.Name)"
$dllName = $e.Name.Split(',')[0]
switch ($dllName) {
'System.Buffers' {return $SystemBuffersDll}
'System.Runtime.CompilerServices.Unsafe' {return $SystemRuntimeCompilerServicesUnsafeDll}
'System.Memory' {return $SystemMemoryDll}
'System.Threading.Tasks.Extensions' {return $SystemSystemThreadingTasksExtensionsDll}
'Microsoft.Bcl.AsyncInterfaces' {return $MicrosoftBclAsyncInterfacesDll}
'Pipelines.Sockets.Unofficial' {return $PipelinesSocketsUnofficialDll}
'System.Threading.Channels' {return $SystemThreadingChannelsDll}
'System.Numerics.Vectors' {return $SystemNumericsVectorsDll}
'System.IO.Pipelines' {return $SystemIoPipelinesDll}
}
foreach($assembly in [System.AppDomain]::CurrentDomain.GetAssemblies()) {
if ($assembly.FullName -eq $e.Name) {
return $assembly
}
}
return $null
}
# Set up the handler above to be triggered when the AssemblyResolve event occurs
[System.AppDomain]::CurrentDomain.add_AssemblyResolve($onAssemblyResolveEventHandler)
# Load StackExchange.Redis.dll, prefer Add-Type because it seems to include dependencies, LoadFrom doesn't so might get an error later
Add-Type -LiteralPath "$DllPath\StackExchange.Redis.dll"
$redis = [StackExchange.Redis.ConnectionMultiplexer]::Connect("$redisConnectionString, allowAdmin=true")
$redisServer = $redis.GetServer($redisHostName, 6380)
# $rs.FlushAllDatabases(async=true)
$redisServer.FlushAllDatabases()
# Detach the event handler (not detaching can lead to stack overflow issues when closing PS)
[System.AppDomain]::CurrentDomain.remove_AssemblyResolve($onAssemblyResolveEventHandler)

How can I use the unmanaged UI Automation API from PowerShell

The UI Automation API for Windows is available from two DLLs.
One is a managed DLL, which is C:\Program Files\Reference Assemblies\Microsoft\Framework\v3.0\UIAutomationClient.dll.
The other is an unmanaged DLL, which is C:\Windows\System32\UIAutomationCore.dll.
According to this post, the unmanaged API is superior to the managed API in terms of the number of visible elements, so I would like to use the unmanaged API.
I have tried three approaches, but all of them failed.
Would you tell me the correct approach?
Approach #1: New-Object -ComObject
$uia = New-Object -ComObject <ProgID of CUIAutomation>
$root = $uia.GetRootElement()
Failed because New-Object requires ProgID but CUIAutomation does not have ProgID.
Approach #2: Instantiation from CLSID
The CLSID of CUIAutomation is ff48dba4-60ef-4201-aa87-54103eef594e, then,
$type = [Type]::GetTypeFromCLSID("ff48dba4-60ef-4201-aa87-54103eef594e")
$uia = [Activator]::CreateInstance($type)
$root = $uia.GetRootElement()
but failed with the following error message.
I still do not know why.
Method invocation failed because [System.__ComObject] does not contain a method named 'GetRootElement'.
At line:1 char:1
+ $root = $uia.GetRootElement()
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : MethodNotFound
Approach #3: Add-Type
Add-Type -Path "C:\Windows\System32\UIAutomationCore.dll"
$uia = New-Object UIAutomationClient.CUIAutomation
$root = $uia.GetRootElement()
Failed because Add-Type expects managed DLLs.
Error message:
Add-Type : Could not load file or assembly 'file:///C:\Windows\System32\UIAutomationCore.dll' or one of its dependencies. The module was expected to contain an assembly manifest. At line:1 char:1
+ Add-Type -Path "C:\Windows\System32\UIAutomationCore.dll"
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [Add-Type], BadImageFormatException
+ FullyQualifiedErrorId : System.BadImageFormatException,Microsoft.PowerShell.Commands.AddTypeCommand
Edit (2018-06-12)
I tried another approach. (and failed)
Approach #4: Interop DLL
I do not really understand what exactly the Interop DLL is, but this post says the Interop DLL helped OP anyway.
I installed Visual Studio and generated Interop.UIAutomationClient.dll by following the procedures of the post.
Add-Type -Path "Interop.UIAutomationClient.dll"
$uia = New-Object UIAutomationClient.CUIAutomationClass
$root = $uia.GetRootElement()
$children = $root.FindAll([UIAutomationClient.TreeScope]::TreeScope_Children, $uia.CreateTrueCondition())
I succeeded in obtaining $root, but failed at the line of $children with the following error message.
Method invocation failed because [System.__ComObject] does not contain a method named 'FindAll'.
At line:1 char:1
+ $children = $root.FindAll([UIAutomationClient.TreeScope]::TreeScope_C ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : MethodNotFound
I still do not know why.
What about this?:
Add-Type -AssemblyName 'UIAutomationClient'
$ae = [System.Windows.Automation.AutomationElement]
$cTrue = [System.Windows.Automation.PropertyCondition]::TrueCondition
$root = $ae::RootElement
$winNames = $root.FindAll("Children", $cTrue).current.name
I have not yet resolved the problem, but finally found an alternative, that is C# Interactive.
I will leave this question for PowerShell users, but, if you can use C# Interactive as an alternative of PowerShell, the following section may help you.
Approach #5: C# Interactive
Install Visual Studio.
Generate Interop.UIAutomationClient.dll by following the procedures of this post.
Run the following script on csi.exe.
#r "Interop.UIAutomationClient.dll"
var uia = new UIAutomationClient.CUIAutomation();
var root = uia.GetRootElement();
var children = root.FindAll(UIAutomationClient.TreeScope.TreeScope_Children, uia.CreateTrueCondition());
FYI, C# Interactive works if only the following files exist in the same folder (i.e., you can use C# Interactive anywhere just by bringing the following files from the development environment).
C:\Program Files (x86)\MSBuild\14.0\Bin\csi.exe
C:\Program Files (x86)\MSBuild\14.0\Bin\csi.rsp
C:\Program Files (x86)\MSBuild\14.0\Bin\Microsoft.CodeAnalysis.CSharp.dll
C:\Program Files (x86)\MSBuild\14.0\Bin\Microsoft.CodeAnalysis.CSharp.Scripting.dll
C:\Program Files (x86)\MSBuild\14.0\Bin\Microsoft.CodeAnalysis.dll
C:\Program Files (x86)\MSBuild\14.0\Bin\Microsoft.CodeAnalysis.Scripting.dll
C:\Program Files (x86)\MSBuild\14.0\Bin\System.AppContext.dll
C:\Program Files (x86)\MSBuild\14.0\Bin\System.Collections.Immutable.dll
C:\Program Files (x86)\MSBuild\14.0\Bin\System.Diagnostics.StackTrace.dll
C:\Program Files (x86)\MSBuild\14.0\Bin\System.IO.FileSystem.dll
C:\Program Files (x86)\MSBuild\14.0\Bin\System.Reflection.Metadata.dll
Approach 2 you should get to the interface of
IID_IUIAutomation = "{30CBE57D-D9D0-452A-AB13-7AC5AC4825EE}"
CLSID_UIAutomationClient = "{944DE083-8FB8-45CF-BCB7-C477ACB2F897}"
;CoClasses
CLSID_CUIAutomation = "{FF48DBA4-60EF-4201-AA87-54103EEF594E}"
MS Doc states
Remarks
Every UI Automation client application must obtain this interface to a CUIAutomation object in order to gain access to the functionality of UI Automation.
The following example function creates a CUIAutomation object and obtains the
IUIAutomation interface.
IUIAutomation *g_pAutomation;
BOOL InitializeUIAutomation()
{
CoInitialize(NULL);
HRESULT hr = CoCreateInstance(__uuidof(CUIAutomation), NULL, CLSCTX_INPROC_SERVER,
__uuidof(IUIAutomation), (void**)&g_pAutomation);
return (SUCCEEDED(hr));
}
I was not able to get it working in PS but maybe this answers helps partly in the right direction (I have it working in AutoIt but that works differently, you can find it with AutoIt IUIAutomation on google)
$objCUI=[System.Runtime.InteropServices.Marshal]::GetTypeFromCLSID("30CBE57D-D9D0-452A-AB13-7AC5AC4825EE")
or
$Type = [Type]::GetTypeFromCLSID('30CBE57D-D9D0-452A-AB13-7AC5AC4825EE')
$objCUI = [System.Activator]::CreateInstance($Type)
both run but when I come to
$rootEl = $objCUI.GetType().InvokeMember(
"GetRootElement",
"InvokeMethod",
$Null,
$objCUI,
#()
)
I get errors

Could not install module dependencies needed by the configuration (DSC)

I am trying out the new Desired state configuration stuff and trying to work with a new class resource. I have installed the pre-production preview of WMF 5.0 on all servers involved in the process.
I have a Http pull server setup where I have deployed my class resource to.
The target nodes are configured to get their resources from this server which they seem to be doing.
However when I try to push a configuration out to the target nodes that use this class resource I get the following error
Checksum for module DeploymentClass_1.0 doesn't match. Could not install module dependencies needed by the configuration.
+ CategoryInfo : InvalidResult: (root/Microsoft/...gurationManager:String) [], CimException
+ FullyQualifiedErrorId : WebDownloadManagerModuleMismatchChecksum,Microsoft.PowerShell.DesiredStateConfiguration.Commands.GetDscModuleCommand
+ PSComputerName : DDsTest002
I am not sure what the dependencies are that it needs as pretty much the same code wrapped up in the old powershell way of creating a custom resource works fine. Any ideas on how to identify the missing dependencies? Once identified any ideas on how I would make these automatically available to an nodes that require the resources without going and installing a bunch of stuff on each target node that needs them?
Answer Edit - With thanks to Dan1el42
Here is the modified code to generate the checksum that fixed this for me. As Dan suggested just adding the -Force flag to New-DscChecksum command did the trick.
$modulePath='M:\Modules\DeploymentClass'
#get module Version
$content=Get-Content $modulePath\DeploymentClass.psd1
$version=$content[14].Split("'")[1]
$version
$archiveFQN = 'C:\Program Files\WindowsPowerShell\DscService\Modules\DeploymentClass_' + $version + '.zip'
$archiveFQN
Compress-Archive -Path $modulePath -DestinationPath $archiveFQN -Force
New-DscChecksum $archiveFQN -Force
Looks like the checksum file DeploymentClass_1.0.zip.checksum does not match your DeploymentClass_1.0.zip. Please run New-DscChecksum again with the -Force switch.

Using PowerShell to create Entity Framework DbContext

I'm trying to create powershell management scripts for my EF6 based website, but I'm struggling to create a DbContext to access my entities.
Following PowerShell App.Config, I'm doing the following to load my dll, set the config file for the current app domain and instantiate my DbContext.
Add-Type -AssemblyName System.Configuration
[appdomain]::CurrentDomain.SetData("APP_CONFIG_FILE", "path.to.web.config")
[Reflection.Assembly]::LoadFrom("MyProject.Dll")
$ctx = New-Object MyProject.MyDbContext
$ctx
I'm able to load the dll, and can inspect that it finds the MyProject.MyDbContext class, and it seems to be able to create the object as well, but upon executing the last statement I get a TargetInvocationException
format-default : Exception has been thrown by the target of an invocation.
+ CategoryInfo : NotSpecified: (:) [format-default], TargetInvocationException
+ FullyQualifiedErrorId : System.Reflection.TargetInvocationException,Microsoft.PowerShell.Commands.FormatDefaultCommand
I've tried catching the TargetInvocationException, but it seems to escape my try-catch somehow.
Any ideas?
It turns out that PowerShell.exe uses .NET v2.0 by default. Following cmo999's answer (note that it's not the accepted answer on that question), it's possible to run powershell.exe under v4.0 by modifying powershell.exe.config.

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)