9

I started a new .NET Framework 4.7.2 library project. I need to automate PowerShell scripts, but the "framework" tab in Visual Studio's reference adding UI didn't list System.Management.Automation as an option. So I added a reference to this Nuget package:

https://www.nuget.org/packages/System.Management.Automation/7.0.0

Then with this code:

PowerShell ps = PowerShell.Create();
ps.AddScript(@"C:\ps\function.ps1");
ps.AddArgument(1);
ps.AddArgument(2);
Collection<PSObject> results = ps.Invoke<PSObject>();

I get this error about versions of a DLL which I did not directly reference:

Assembly 'System.Management.Automation' with identity 'System.Management.Automation, Version=7.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' uses 'System.Linq.Expressions, Version=4.2.2.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' which has a higher version than referenced assembly 'System.Linq.Expressions' with identity 'System.Linq.Expressions, Version=4.1.2.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'

I'm not sure how to resolve this, and I think maybe I approached adding my PowerShell automation library reference the wrong way. What's the right way to do this currently?

Before you point me at an old answer, I found a similar question about this which points to a different Nuget package, now marked "deprecated" and doesn't look official anyway. That makes me nervous.

https://www.nuget.org/packages/System.Management.Automation.dll/

BigScary
  • 530
  • 1
  • 6
  • 19

2 Answers2

17

System.Management.Automation v7.0.0 only works with .NET Core. If your project requires .NET Framework, you must use System.Management.Automation v5.1.x.

Steve Lee
  • 286
  • 2
  • 5
  • 1
    Thanks - where would I get that version, then? Doesn't seem to available from the same nuget collection linked above. – BigScary Sep 02 '20 at 20:06
  • 11
    For 5.1, you should use https://www.nuget.org/packages/Microsoft.PowerShell.5.ReferenceAssemblies/ – Steve Lee Sep 03 '20 at 21:26
  • 2
    Tried to install the nuget package for version 5.1, but it wasn't compatible with my framework version 4.6, so I used the one @SteveLee suggested above. – Henning Winter Sep 08 '21 at 14:24
5

I use System.Management.Automation.dll in my .net framework 4.7.2 app. I just added it via the following reference:

C:\WINDOWS\assembly\GAC_MSIL\System.Management.Automation\1.0.0.0__31bf3856ad364e35\System.Management.Automation.dll
isxaker
  • 8,446
  • 12
  • 60
  • 87