Wedge
Wedge

Reputation: 19815

Inconsistent assembly loading behavior in powershell

I was debugging why a powershell script started failing and it looked like it was using Hashset without referencing the System.Core assembly, so the fix is to end up with something like this:

Add-Type -AssemblyName System.Core
$hash = new-object 'System.Collections.Generic.HashSet[string]'

What I can't figure out is how it was working before, and still runs just fine on some machines, without the add-type line. What am I missing here?

Upvotes: 1

Views: 489

Answers (1)

Matt
Matt

Reputation: 46710

To continue from David's thought, and because code in comments is horrid, you should check to see if the assembly is loaded. A small blog about checking assemblies is here

If (!(([appdomain]::currentdomain.GetAssemblies()).FullName -match "System\.Core")){
    Add-Type -AssemblyName System.Core
}
$hash = new-object 'System.Collections.Generic.HashSet[string]'

I have this assembly loaded by default. Curious what the affected systems have. What is the Dot.Net framework versions on affected machines? I had some of my 3.5 code stop working after Windows updates and need to reinstall framework.

Comment from Jeroen Mostert

If you want to be really precise about it, you should verify you've got .NET's very own System.Core, not any old impostor, and then there is no need to check that's already happened. Add-Type -AssemblyName "System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"

Upvotes: 2

Related Questions