Search code examples
c#.netpowershellopenhardwaremonitor

Executing C# code in PowerShell results in an error - verify that the assembly containing this type is loaded


I am trying to execute below piece of code in PowerShell and I'm getting below error (please refer screenshot). I already tried many ways to handle this error but there is no luck.

I referred to these articles:

  1. stackoverflow.com/questions/12923074/how-to-load-assemblies-in-powershell
  2. stackoverflow.com/questions/64266974/powershell-5-1-cannot-find-type-mytype-verify-that-the-assembly-containing
  3. hanselman.com/blog/watir-for-net-watin-approaches-08-release-and-automating-ie-from-powershell
  4. https://community.idera.com/database-tools/powershell/powertips/b/tips/posts/using-using-namespace

Can you help me with this?

Thanks in advance!

enter image description here

$id = get-random
$Source = @”
using OpenHardwareMonitor.Hardware;
using System;

namespace GetCpuTemperatureExample
{
public class GetCpuTemerature$id : IVisitor
{

public void VisitComputer(IComputer computer)
{
computer.Traverse(this);
}
public void VisitHardware(IHardware hardware)
{
hardware.Update();
foreach (IHardware subHardware in hardware.SubHardware) subHardware.Accept(this);
}
public void VisitSensor(ISensor sensor) { }
public void VisitParameter(IParameter parameter) { }
public static double GetSystemInfo(GetCpuTemerature$id updateVisitor)
{
double result=0;
try
{

Computer computer = new Computer();
computer.Open();
computer.CPUEnabled = true;
computer.Accept(updateVisitor);
for (int i = 0; i < computer.Hardware.Length; i++)
{
double sum = 0;
int countOfCPU = 0;
if (computer.Hardware[i].HardwareType == HardwareType.CPU)
{
for (int j = 0; j < computer.Hardware[i].Sensors.Length; j++)
{
if (computer.Hardware[i].Sensors[j].SensorType == SensorType.Temperature)
{
if (computer.Hardware[i].Sensors[j].Name.Contains("Core"))
{
sum += Convert.ToDouble(computer.Hardware[i].Sensors[j].Value.ToString());
countOfCPU++;
}

}
}
result=(sum / countOfCPU);
}
}
computer.Close();
}
catch (Exception ex)
{
}
return result;
}
}
}

"@

$referencedAssemblies = "C:\Program Files\OpenHardwareMonitorLib.dll"
Import-Module 'C:\Program Files\OpenHardwareMonitorLib.dll'
Add-Type -Path $referencedAssemblies
$cpar = New-Object System.CodeDom.Compiler.CompilerParameters
$cpar.ReferencedAssemblies.Add($referencedAssemblies)
Add-Type -TypeDefinition $Source -CompilerParameters $cpar -Language CSharp
$GetCpuTemeratureObj = New-Object GetCpuTemerature$id
$CPUTemp = [GetCpuTemperatureExample.GetCpuTemerature]::GetSystemInfo($GetCpuTemeratureObj)
echo $CPUTemp

Solution

  • You need to use the full type name in both cases (including the namespace and the ID at the end):

    $GetCpuTemeratureObj = New-Object "GetCpuTemperatureExample.GetCpuTemerature$id"
    $CPUTemp = ([type]"GetCpuTemperatureExample.GetCpuTemerature$id")::GetSystemInfo($GetCpuTemeratureObj)
    echo $CPUTemp