简体   繁体   中英

Running remote PowerShell script using .Net 5.0

The method call in C# is like this -

        public void GetKey()
        {
            WSManConnectionInfo connectioninfo = new WSManConnectionInfo();
          
            var ss = new NetworkCredential("xxx.yyyy\\Administrator", "PassFail2Hehe");
            connectioninfo.ComputerName = "<some IP Address>";            
            connectioninfo.Credential = new PSCredential(ss.UserName, ss.SecurePassword);
          
            //Runspace runspace = RunspaceFactory.CreateRunspace(connectioninfo);
            //runspace.Open();
            using (PowerShell ps = PowerShell.Create())
            {
                var re = ps.AddScript("Get-Service");
                var results = re.Invoke();
            }
        }

I am using the NuGet package 'Microsoft.PowerShell.5.ReferenceAssemblies 1.1.0', as it is showing as the recommended package in Visual Studio 2019 for resolving the types of "Runspace", "PowerShell" etc.

However, I am getting the exception when the instance of "Runspace" or "PowerShell" is created. The exception is like this - "Common Language Runtime detected an invalid program."

I found this post and realized that I was getting the warning indeed for the NuGet package -

"Package 'Microsoft.PowerShell.5.ReferenceAssemblies 1.1.0' was restored using '.NETFramework,Version=v4.6.1, .NETFramework,Version=v4.6.2, .NETFramework,Version=v4.7, .NETFramework,Version=v4.7.1, .NETFramework,Version=v4.7.2, .NETFramework,Version=v4.8' instead of the project target framework 'net5.0'. This package may not be fully compatible with your project."

As per suggested in the post, I installed Powershell Core 7.1.3, but the warning and exceptions were not resolved. Then I switched to ".Net Standard 2.0", since it the project was a class library, but nothing changed. The same warning message and exception.

How can I make remote PowerShell call using ".Net Core 5.0" (or ".Net Standard 2.0")?

If you want to target.Net 5, the correct nuget package to use is Microsoft.PowerShell.SDK

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM