Issue accessing GCP secrets manager using dotnet 5 - c#

I am using Google.Cloud.SecretManager.V1 in my .NET 5 aspnet core application. I am containerizing application to run as linux container on GCP Cloud run. I get following exception while creating SecretManagerServiceClient
//call SDK
SecretManagerServiceClient client = SecretManagerServiceClient.Create();
System.DllNotFoundException: Unable to load shared library 'libdl.so' or one of its dependencies. In order to help diagnose loading problems, consider setting the LD_DEBUG environment variable: liblibdl.so: cannot open shared object file: No such file or directory
at Grpc.Core.Internal.UnmanagedLibrary.Linux.dlopen(String filename, Int32 flags)
at Grpc.Core.Internal.UnmanagedLibrary.LoadLibraryPosix(Func`3 dlopenFunc, Func`1 dlerrorFunc, String libraryPath, String& errorMsg)
at Grpc.Core.Internal.UnmanagedLibrary.PlatformSpecificLoadLibrary(String libraryPath, String& errorMsg)
at Grpc.Core.Internal.UnmanagedLibrary..ctor(String[] libraryPathAlternatives)
at Grpc.Core.Internal.NativeExtension.LoadUnmanagedLibrary()
at Grpc.Core.Internal.NativeExtension.LoadNativeMethods()
at Grpc.Core.Internal.NativeExtension..ctor()
at Grpc.Core.Internal.NativeExtension.Get()
at Grpc.Core.Internal.NativeMethods.Get()
at Grpc.Core.GrpcEnvironment.GrpcNativeInit()
at Grpc.Core.GrpcEnvironment..ctor()
at Grpc.Core.GrpcEnvironment.AddRef()
at Grpc.Core.Channel..ctor(String target, ChannelCredentials credentials, IEnumerable`1 options)
at Google.Api.Gax.Grpc.GrpcCore.GrpcCoreAdapter.CreateChannelImpl(String endpoint, ChannelCredentials credentials, GrpcChannelOptions options)
at Google.Api.Gax.Grpc.GrpcAdapter.CreateChannel(String endpoint, ChannelCredentials credentials, GrpcChannelOptions options)
at Google.Api.Gax.Grpc.ChannelPool.GetChannel(GrpcAdapter grpcAdapter, String endpoint, GrpcChannelOptions channelOptions, ChannelCredentials credentials)
at Google.Api.Gax.Grpc.ChannelPool.GetChannel(GrpcAdapter grpcAdapter, String endpoint, GrpcChannelOptions channelOptions)
at Google.Api.Gax.Grpc.ClientBuilderBase`1.CreateCallInvoker()
at Google.Cloud.SecretManager.V1.SecretManagerServiceClientBuilder.BuildImpl()
at Google.Cloud.SecretManager.V1.SecretManagerServiceClientBuilder.Build()
at Google.Cloud.SecretManager.V1.SecretManagerServiceClient.Create()
Same code works fine if I use aspnetcore 3.1 image. NET 5 is supposed to be upgrade of .NET core 3.1 and backward compatible. So, I am curious and what could be done to make this code work on .NET 5

I posted this answer to make a solution from the comment section more visible.
As it was suggested by #John Hanley and confirmed by #SmartCoder this issue was solved by adding to the Docker file lines below:
RUN apt-get update -y
RUN apt-get install -y libc6-dev

Related

Cannot run remote Powershell command in .NET Core: no supported WSMan client library was found

I am trying to execute a remote command in .NET Core using Powershell. This is how I am trying to connect to Powershell:
var username = "dwaldkjesfcdw";
SecureString password = new SecureString();
string pwd = "fsdfdsdsfvds"; /* Not Secure! */
pwd.ToCharArray().ToList().ForEach(password.AppendChar);
/* and now : seal the deal */
password.MakeReadOnly();
var credentials = new PSCredential(username, password);
var remoteComputer = new Uri(String.Format("{0}://{1}:3311/wsman", "HTTP", "11.11.111.111"));
var connection = new WSManConnectionInfo(remoteComputer, null, credentials);
var runspace = RunspaceFactory.CreateRunspace(connection);
runspace.Open();
var powershell = PowerShell.Create();
powershell.Runspace = runspace;
powershell.AddScript("$env:ComputerName");
var result = powershell.Invoke();
However, this line...
var runspace = RunspaceFactory.CreateRunspace(connection);
...throws this exception...
System.Management.Automation.Remoting.PSRemotingTransportException: This parameter set requires WSMan, and no supported WSMan client library was found. WSMan is either not installed or unavailable for this system. ---> System.DllNotFoundException: Unable to load shared library 'libpsrpclient' or one of its dependencies. In order to help diagnose loading problems, consider setting the DYLD_PRINT_LIBRARIES environment variable: dlopen(liblibpsrpclient, 1): image not found
at System.Management.Automation.Remoting.Client.WSManNativeApi.WSManInitialize(Int32 flags, IntPtr& wsManAPIHandle)
at System.Management.Automation.Remoting.Client.WSManClientSessionTransportManager.WSManAPIDataCommon..ctor()
--- End of inner exception stack trace ---
at System.Management.Automation.Remoting.Client.WSManClientSessionTransportManager.WSManAPIDataCommon..ctor()
at System.Management.Automation.Remoting.Client.WSManClientSessionTransportManager..ctor(Guid runspacePoolInstanceId, WSManConnectionInfo connectionInfo, PSRemotingCryptoHelper cryptoHelper, String sessionName)
at System.Management.Automation.Runspaces.WSManConnectionInfo.CreateClientSessionTransportManager(Guid instanceId, String sessionName, PSRemotingCryptoHelper cryptoHelper)
at System.Management.Automation.Remoting.ClientRemoteSessionDSHandlerImpl..ctor(ClientRemoteSession session, PSRemotingCryptoHelper cryptoHelper, RunspaceConnectionInfo connectionInfo, URIDirectionReported uriRedirectionHandler)
at System.Management.Automation.Remoting.ClientRemoteSessionImpl..ctor(RemoteRunspacePoolInternal rsPool, URIDirectionReported uriRedirectionHandler)
at System.Management.Automation.Internal.ClientRunspacePoolDataStructureHandler.CreateClientRemoteSession(RemoteRunspacePoolInternal rsPoolInternal)
at System.Management.Automation.Internal.ClientRunspacePoolDataStructureHandler..ctor(RemoteRunspacePoolInternal clientRunspacePool, TypeTable typeTable)
at System.Management.Automation.Runspaces.Internal.RemoteRunspacePoolInternal.CreateDSHandler(TypeTable typeTable)
at System.Management.Automation.Runspaces.Internal.RemoteRunspacePoolInternal..ctor(Int32 minRunspaces, Int32 maxRunspaces, TypeTable typeTable, PSHost host, PSPrimitiveDictionary applicationArguments, RunspaceConnectionInfo connectionInfo, String name)
at System.Management.Automation.Runspaces.RunspacePool..ctor(Int32 minRunspaces, Int32 maxRunspaces, TypeTable typeTable, PSHost host, PSPrimitiveDictionary applicationArguments, RunspaceConnectionInfo connectionInfo, String name)
at System.Management.Automation.RemoteRunspace..ctor(TypeTable typeTable, RunspaceConnectionInfo connectionInfo, PSHost host, PSPrimitiveDictionary applicationArguments, String name, Int32 id)
at System.Management.Automation.Runspaces.RunspaceFactory.CreateRunspace(RunspaceConnectionInfo connectionInfo, PSHost host, TypeTable typeTable, PSPrimitiveDictionary applicationArguments, String name)
at System.Management.Automation.Runspaces.RunspaceFactory.CreateRunspace(RunspaceConnectionInfo connectionInfo, PSHost host, TypeTable typeTable)
at System.Management.Automation.Runspaces.RunspaceFactory.CreateRunspace(PSHost host, RunspaceConnectionInfo connectionInfo)
at System.Management.Automation.Runspaces.RunspaceFactory.CreateRunspace(RunspaceConnectionInfo connectionInfo)
at Services.Services.CalculationService.ProcessCalculations(Int32 clientId, Int32 calculationId) in /Users/Services/CalculationService.cs:line 90
Here is my .csproj file:
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netcoreapp2.2</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.PowerShell.Commands.Diagnostics" Version="6.1.1" />
<PackageReference Include="Microsoft.PowerShell.SDK" Version="6.1.1" />
<PackageReference Include="Microsoft.WSMan.Management" Version="6.1.1" />
<PackageReference Include="System.Management.Automation" Version="6.1.1" />
<PackageReference Include="WindowsAzure.Storage" Version="8.1.4" />
</ItemGroup>
<ItemGroup>
</ItemGroup>
</Project>
I am running on macOS but the app will run on Azure.
Is the problem with the version of nuget packages? I can't find what I am missing. Or is the problem on the remote computer?
This was occurring for me with .NET Core 3.1 on Fedora 33. Not sure if there is a package that provides this, and I'm not sure if it applies to macOS either, but I found that the exception is correct in my case. It cannot find some shared libraries related to the PowerShell Remoting Protocol (PSRP) client.
I had already installed PowerShell 7.0.3, and made sure that I could actually remote using WS Management. At first, it seemed that I needed to install the PSRP server and the Open Management Infrastructure (OMI) library. However, that didn't resolve the issue.
Poking around some old GitHub issues on the PowerShell repo, I got some clues that the runtime either couldn't find the libpsrpclient shared library object or one of its dependencies. I discovered that these shared libraries existed in the PowerShell installation location, which would explain why PowerShell itself had no problem remoting:
libpsrpclient.so - presumably the client library itself
libmi.so - a dependency library for omi
libssl.so.1.0.0 - a symlink to /lib64/libssl.so.10 (which is itself a symlink to /lib64/libssl.so.1.0.2o on Fedora 33)
libcrypto.so.1.0.0 - a symlink to /lib64/libcrypto.so.10 (which again is itself a symlink to /lib64/libcrypto.so.1.0.2o)
Anyway, here's the workaround on Linux:
Navigate to your PowerShell directory
cd /opt/microsoft/powershell/7
Copy (or symlink) the shared libraries to a location in your shared library path (like /usr/lib):
sudo cp libpsrpclient.so libmi.so libssl.so.1.0.0 libcrypto.so.1.0.0 /usr/lib
Relink/cache shared library:
sudo ldconfig -n -v /usr/lib
Edit: On Fedora Linux 36 with PowerShell 7.2.5, I had to use a forked version of Microsoft's OMI. For some reason, the libraries that came with it don't work anymore, perhaps because they depend upon OpenSSL 1.0, which doesn't ship with Fedora Linux anymore?
Initiate an elevated PowerShell session:
sudo pwsh
Install the PSWSMan module (this is a forked version of Microsoft OMI):
Install-Module PSWSMan
Let the module copy the correct libraries into your PowerShell directory:
Install-WSMan
Proceed with previous steps (except you won't copy the libssl and libcrypto libraries, because this forked version is compiled against OpenSSL 1.1 instead)

.exe file not recognized after resigning the manifest on ClickOnce Publish

I am using MVS 2015 with .Net Framework 4.5.
I publish my C# WF Application, everything is fine, but I have to obfuscate the .exe from Application Files.
After I do it, obviously, the setup does not recognize anymore the .exe, the hashes are different and so on.
I resign the new .exe added file with Signtool providing the necessary .pfx and password, then I use Mage to update the .manifest and the .application according to the second part of this MSDN documentation.
Everything is successful, but when I run the setup and I hit install, after a while (around 80% of the installation progress) I receive an error that says that there is something wrong with the new .exe file:
PLATFORM VERSION INFO
Windows : 10.0.16299.0 (Win32NT)
Common Language Runtime : 4.0.30319.42000
System.Deployment.dll : 4.7.2556.0 built by: NET471REL1
clr.dll : 4.7.2633.0 built by: NET471REL1LAST_C
dfdll.dll : 4.7.2556.0 built by: NET471REL1
dfshim.dll : 10.0.16299.15 (WinBuild.160101.0800)
SOURCES
Deployment url : file:///E:/share/myApp.application
Application url : file:///E:/share/myApp.exe.manifest
IDENTITIES
Deployment Identity : myApp.exe.application, Version=1.0.0.0, Culture=neutral, PublicKeyToken=6500754c4a44ec95, processorArchitecture=msil
Application Identity : myApp.exe, Version=1.0.0.0, Culture=neutral, PublicKeyToken=6500754c4a44ec95, processorArchitecture=msil, type=win32
APPLICATION SUMMARY
* Installable application.
ERROR SUMMARY
Below is a summary of the errors, details of these errors are listed later in the log.
* Activation of E:\share\myApp.application resulted in exception. Following failure messages were detected:
+ Exception occurred loading manifest from file myApp.exe: the manifest may not be valid or the file could not be opened.
+ Cannot load internal manifest from component file.
COMPONENT STORE TRANSACTION FAILURE SUMMARY
No transaction error was detected.
WARNINGS
There were no warnings during this operation.
OPERATION PROGRESS STATUS
* [24.03.2018 11:03:32] : Activation of E:\share\myApp.application has started.
* [24.03.2018 11:03:32] : Processing of deployment manifest has successfully completed.
* [24.03.2018 11:03:32] : Installation of the application has started.
* [24.03.2018 11:03:33] : Processing of application manifest has successfully completed.
* [24.03.2018 11:03:35] : Found compatible runtime version 4.0.30319.
* [24.03.2018 11:03:35] : Request of trust and detection of platform is complete.
ERROR DETAILS
Following errors were detected during this operation.
* [24.03.2018 11:03:43] System.Deployment.Application.InvalidDeploymentException (ManifestLoad)
- Exception occurred loading manifest from file myApp.exe: the manifest may not be valid or the file could not be opened.
- Source: System.Deployment
- Stack trace:
at System.Deployment.Application.Manifest.AssemblyManifest.ManifestLoadExceptionHelper(Exception exception, String filePath)
at System.Deployment.Application.Manifest.AssemblyManifest.LoadFromInternalManifestFile(String filePath)
at System.Deployment.Application.DownloadManager.ProcessDownloadedFile(Object sender, DownloadEventArgs e)
at System.Deployment.Application.FileDownloader.DownloadModifiedEventHandler.Invoke(Object sender, DownloadEventArgs e)
at System.Deployment.Application.FileDownloader.OnModified()
at System.Deployment.Application.SystemNetDownloader.DownloadSingleFile(DownloadQueueItem next)
at System.Deployment.Application.SystemNetDownloader.DownloadAllFiles()
at System.Deployment.Application.FileDownloader.Download(SubscriptionState subState, X509Certificate2 clientCertificate)
at System.Deployment.Application.DownloadManager.DownloadDependencies(SubscriptionState subState, AssemblyManifest deployManifest, AssemblyManifest appManifest, Uri sourceUriBase, String targetDirectory, String group, IDownloadNotification notification, DownloadOptions options)
at System.Deployment.Application.ApplicationActivator.DownloadApplication(SubscriptionState subState, ActivationDescription actDesc, Int64 transactionId, TempDirectory& downloadTemp)
at System.Deployment.Application.ApplicationActivator.InstallApplication(SubscriptionState& subState, ActivationDescription actDesc)
at System.Deployment.Application.ApplicationActivator.PerformDeploymentActivation(Uri activationUri, Boolean isShortcut, String textualSubId, String deploymentProviderUrlFromExtension, BrowserSettings browserSettings, String& errorPageUrl, Uri& deploymentUri)
at System.Deployment.Application.ApplicationActivator.PerformDeploymentActivationWithRetry(Uri activationUri, Boolean isShortcut, String textualSubId, String deploymentProviderUrlFromExtension, BrowserSettings browserSettings, String& errorPageUrl)
What am I doing wrong? What am I missing? :(
I have investigated Marko application, and if you have in use .NET Refactor and have a problem from above here is workaround for get it working:
.Net Reactor has a Visual Studio Add-In that needs installed and configured in the project
Anti ILDASM from .Net Reactor (option that's enabled by default) has to be disabled when obfuscating so that MVS could do the proper packing process
Anyway, if you gonna modify your assemblies after publish you need to recompute hash anyway. How it's possible:
Don't use a Visual Studio publish engine and generate you
application by "mage.exe". It's let to you prepare you source
application first and create ClickOnce application after.
Download utility from second download link [here]. Execute and [Choose] your folder > Change action to [Update] > and [Build]. No more actions required. Update operation will recompute hashs.
If your obfuscator software supports command line parameters then you can add "Post-build event" script in your .exe VS project properties and it will be executed before clickonce build.
"Deploying Obfuscated Assemblies" article you can found here: Securing ClickOnce Applications

Unable to publish existing ASP.NET Core 1.0 Web API using VS Tools

I just started working on AWS Lambda using C# and .NET Core. I'm familiar with ASP.NET Core Web API, and have done few projects in it.
I was able to publish a brand new ASP.NET Core Web API project as server-less application in AWS Lambda using API Gateway proxy and able to access my Web API methods.
Now, I have an existing ASP.NET Core Web API project, which I want to publish as server-less application to AWS Lambda using the API Gateway proxy. I followed the instructions given in the below URL to setup my existing project to publish to AWS Lambda.
https://aws.amazon.com/blogs/developer/deploy-an-existing-asp-net-core-web-api-to-aws-lambda/
I'm able to see the publish wizard, and it stats up nut fails with the following trace. Wondering if anyone here could help me understand and fix the issue.
.....
... publish: Configuring project completed successfully
... publish: publish: Published to D:\Aditya\Apps\ManzilApp\Server\src\ManzilApp.Server\bin\Release\netcoreapp1.0\publish
... publish: Published 1/1 projects successfully
Flattening platform specific dependencies
... flatten: runtimes/rhel-x64/native/libuv.so
**Unknown error executing AWS Serverless deployment: Could not find a part of the path** 'D:\Aditya\Apps\ManzilApp\Server\src\ManzilApp.Server\bin\Release\netcoreapp1.0\publish\runtimes/rhel-x64/native/libuv.so'.
at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
at System.IO.File.InternalCopy(String sourceFileName, String destFileName, Boolean overwrite, Boolean checkHost)
at System.IO.File.Copy(String sourceFileName, String destFileName)
at Amazon.Lambda.Tools.LambdaPackager.<>c__DisplayClass4_0.<FlattenRuntimeFolder>b__0(String sourceRelativePath)
at Amazon.Lambda.Tools.LambdaPackager.FlattenRuntimeFolder(IToolLogger logger, String publishLocation, JsonData depsJsonTargetNode)
at Amazon.Lambda.Tools.LambdaPackager.CreateApplicationBundle(LambdaToolsDefaults defaults, IToolLogger logger, String workingDirectory, String projectLocation, String configuration, String targetFramework, String& publishLocation, String& zipArchivePath)
at Amazon.Lambda.Tools.Commands.DeployServerlessCommand.<ExecuteAsync>d__55.MoveNext()
Finally, I got the AWS Lambda deploy tool working in VS 2015 on my existing ASP.NET Core 1.0 Web API project. I had to change the sdk version in global.json file in my source folder (same folder where my .sln file resides). Not sure what is the reason (still would like to understand), but this solved the issue.
{
"projects": [ "src", "test" ],
"sdk": {
"version": "1.0.0-preview2-003131"
}
}

Client Version Error after installing Azure 1.8

I recently installed the Azure SDK 1.8 on my machine but am still using a project that is running version 1.7.1 (June 2012 SP1 for VS2012). Since I did this, every time I try to run my project I get the following error:
ErrorCode<ERRCA0019>:SubStatus<ES0001>:Check the client version. It should be within the allowed version range on the server. If necessary, upgrade the client to the allowed version.
[DataCacheException: ErrorCode<ERRCA0019>:SubStatus<ES0001>:Check the client version. It should be within the allowed version range on the server. If necessary, upgrade the client to the allowed version.]
Microsoft.ApplicationServer.Caching.DataCache.ThrowException(ErrStatus errStatus, Guid trackingId, Exception responseException, Byte[][] payload, EndpointID destination) +767
Microsoft.ApplicationServer.Caching.DataCache.ThrowException(ResponseBody respBody, EndpointID destination) +149
Microsoft.ApplicationServer.Caching.DataCacheFactory.EstablishConnection(IEnumerable`1 servers, RequestBody request, Func`3 sendMessageDelegate, DataCacheReadyRetryPolicy retryPolicy) +967
Microsoft.ApplicationServer.Caching.WcfClientProtocol.Initialize(IEnumerable`1 servers) +606
Microsoft.ApplicationServer.Caching.DataCacheFactory.GetCache(String cacheName, CreateNewCacheDelegate cacheCreationDelegate, DataCacheInitializationViaCopyDelegate initializeDelegate) +1103
Microsoft.ApplicationServer.Caching.DataCacheFactory.GetCache(String cacheName) +131
Microsoft.Web.DistributedCache.DataCacheFactoryWrapper.CreateDataCacheFromFactory(DataCacheFactory factory, String cacheName) +63
Microsoft.Web.DistributedCache.CacheHelpers.RunCacheCreationHooks(CacheConnectingEventArgs fetchingEventArgs, IDataCacheFactory dataCacheFactory, Object sender, EventHandler`1 fetchingHandler, EventHandler`1 fetchedHandler) +356
Microsoft.Web.DistributedCache.DistributedCacheSessionStateStoreProvider.CreateInternalProvider(IHttpRuntime httpRuntime, SessionInitializationData initData, IDataCacheFactory dataCacheFactory, EventHandler`1 cacheFetching, EventHandler`1 cacheFetched) +447
Microsoft.Web.DistributedCache.DistributedCacheSessionStateStoreProvider.GetInternalProvider() +315
Microsoft.Web.DistributedCache.DistributedCacheSessionStateStoreProvider.ResetItemTimeout(HttpContext context, String id) +59
System.Web.SessionState.SessionStateModule.BeginAcquireState(Object source, EventArgs e, AsyncCallback cb, Object extraData) +707
System.Web.AsyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +12600474
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +288
I have not had much luck finding a solution. Some forums have mentioned using a different AppFabric version, but they all seem to be referring to running it in the actual Azure cloud service and I can't even get it to run on my local machine.
Any thoughts?
I ran into a similar problem while upgrading to the October 2012 release. I resolved it by removing all the caching references in my project, and then installing the Windows Azure Shared Caching package from NuGet.
I'm not sure if the resulting project will still run with the June 2012 SDK. But it's worth a try.

Why does invoking PowerShell from C# throw a System.Management.Automation.CommandNotFoundException?

I'm using this c#:
public bool RunPowershell(string script)
{
RunspaceConfiguration runspaceConfig = RunspaceConfiguration.Create();
using (Runspace runspace = RunspaceFactory.CreateRunspace(runspaceConfig))
{
runspace.Open();
using (RunspaceInvoke scriptInvoker = new RunspaceInvoke(runspace))
{
scriptInvoker.Invoke(script);
}
}
return true;
}
To run this script:
Add-PSSnapin -name Microsoft.SystemCenter.VirtualMachineManager
$vmm = Get-VMMServer -ComputerName "VmmComputerName"
It works ok on a Windows 2003 32bit OS, but on a Windows 2008R2 64bit, I get this error:
System.Management.Automation.CommandNotFoundException: The term 'Get-VMMServer' 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 System.Management.Automation.CommandDiscovery.LookupCommandInfo(String commandName, CommandOrigin commandOrigin)
at System.Management.Automation.CommandDiscovery.LookupCommandProcessor(String commandName, CommandOrigin commandOrigin, Nullable`1 useLocalScope)
at System.Management.Automation.CommandFactory._CreateCommand(String commandName, CommandOrigin commandOrigin, Nullable`1 useLocalScope)
at System.Management.Automation.ExecutionContext.CreateCommand(String command)
at System.Management.Automation.CommandNode.CreateCommandProcessor(Int32& index, ExecutionContext context)
at System.Management.Automation.CommandNode.AddToPipeline(PipelineProcessor pipeline, ExecutionContext context)
at System.Management.Automation.PipelineNode.Execute(Array input, Pipe outputPipe, ArrayList& resultList, ExecutionContext context)
at System.Management.Automation.ParseTreeNode.Execute(Array input, Pipe outputPipe, ExecutionContext context)
at System.Management.Automation.AssignmentStatementNode.Execute(Array input, Pipe outputPipe, ExecutionContext context)
at System.Management.Automation.StatementListNode.ExecuteStatement(ParseTreeNode statement, Array input, Pipe outputPipe, ArrayList& resultList, ExecutionContext context)
And, I have got Microsoft.SystemCenter.VirtualMachineManager installed. The script also works if I manually type it in to the power-shell console on the 2008R2 machine.
Can you please help on any ideas for what I might be missing?
Thanks very much.
This occurs because powershell snap-in metadata is recorded in the registry. In your case, this means that the snap-in info is only available in the 32 bit software hive in the registry. Normally the trick to make it available is to use the 64 bit version of the .NET framework's installutil.exe (in the framework64 directory) to register it, but sometimes it's 32 bit only for a reason. It may be depending on 32 bit COM objects that are not available in a 64 bit environment.
So you have two approaches:
1) register the snap-in for 64 bit by using installutil.exe /i (unlikely to work)
or
2) target your .NET exe for 32 bit only via VS project properties (anycpu -> x86)
or
3) wrap your work up in a script like this: http://www.nivot.org/blog/post/2012/12/18/Ensuring-a-PowerShell-script-will-always-run-in-a-64-bit-shell
-Oisin
Here's an example that handles named parameters and worked for my needs. Original was taken from the linked option in x0n's post. See the linked post for additional details. I'm executing this script from a C# console application that has 3rd party dependencies on x86.
param([string[]]$listOfVMNames, [string]$userName, [string]$resourceGroupName, [int]$waitForJob)
if ($pshome -like "*syswow64*") {
& (join-path ($pshome -replace "syswow64", "sysnative") powershell.exe) -file `
(join-path $psscriptroot $myinvocation.mycommand) -listOfVMNames (,$listOfVMNames) -userName $userName -resourceGroupName $resourceGroupName -waitForJob $waitForJob
exit
}

Categories