Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Executing PowerShell code at the API level
#16
ERROR: The 'Get-CimInstance' command was found in the module 'CimCmdlets', but the module could not be loaded due to the following error: [Cannot find the built-in module 'CimCmdlets' that is compatible with the 'Core' edition. Please make sure the PowerShell built-in modules are available. They usually come with the PowerShell package under the $PSHOME module path, and are required for PowerShell to function properly.]
For more information, run 'Import-Module CimCmdlets'.
0


The following code will display the above error message when the program is executed after being published using the following menu items in LA:
Run -> Publish... -> +Add .NET Runtime

PS:  The exe file generated directly using the compile button on the toolbar works correctly during testing.
 
Code:
Copy      Help
// script "PowerShell_SDK_T4.cs"
/*/ role exeProgram; nuget ps\Microsoft.PowerShell.SDK; /*/
using System.Management.Automation;

print.clear();

string code = """
$memoryInfo = Get-CimInstance -ClassName Win32_PhysicalMemory
$totalMemoryGB = ($memoryInfo | Measure-Object -Property Capacity -Sum).Sum / 1GB
$totalMemoryGB | Out-String
"""
;

var results = PS.Invoke(code);
foreach (var result in results)
{

    print.it(result.ToString());
    dialog.show(result.ToString());
}


static class PS
{
    public static System.Collections.ObjectModel.Collection<PSObject> Invoke(string command)
    {

        using (var ps = PowerShell.Create())
        {

            ps.AddScript(command);
            
            var results = ps.Invoke();
            
            // report non-runspace-terminating errors, if any.
            foreach (var error in ps.Streams.Error)
            {

                print.it("ERROR: " + error.ToString());
            }

            
            return results;
        }
    }
}

My goal is to execute the above program on a computer that does not have PowerShell 7 and .NET 8 runtime installed.


Messages In This Thread
RE: Executing PowerShell code at the API level - by Davider - 08-06-2024, 05:14 AM

Forum Jump:


Users browsing this thread: 2 Guest(s)