Home > Software engineering >  Executing C# code in PowerShell results in an error - verify that the assembly containing this type
Executing C# code in PowerShell results in an error - verify that the assembly containing this type

Time:03-29

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. 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
    

    CodePudding user response:

    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
    
  • Related