How to call Powershell functions from C# in WinUI 3
Asked Answered
I

0

4

I am trying to call a function in a PowerShell script file. I am using WinUI 3. I get difficult-to-understand output in the debugger output, and the PowerShell script does not appear to execute at all. I have verified the PowerShell script runs correctly when I run it directly from PowerShell (or start it directly in Visual Studio).

The following C# code is used to call the function Setup-Workspaces in the PowerShell script. Note that the datatype of workspace.Name is string. This is based on the answer here.

/// <summary>
/// Launches the given workspace using the given powershell script.
/// </summary>
/// <param name="script"></param>
/// <param name="workspace"></param>
internal static void LaunchWorkspace(string script, Workspace workspace)
{
    using (PowerShell powerShell = PowerShell.Create())
    {
        // Add the script to run from.
        powerShell.AddScript(script, false);

        powerShell.Invoke();

        powerShell.Commands.Clear();

        // Add the command in the script to run.
        powerShell.AddCommand("Setup-Workspaces").AddParameter("WorkspaceName", workspace.Name);

        // Execute the command from the script.
        var results = powerShell.Invoke();
        //System.Diagnostics.Debug.WriteLine("Stuff happened");
        //System.Diagnostics.Debug.WriteLine("THE SCRIPT\n\n\n");
    }
}

The following is the function called from the PowerShell script. Note that the function is written expecting only one of the two parameters to be provided. I have verified this works when running this script independently of the C# code.

function Setup-Workspaces {
    # Define the parameter.
    param (
        $Workspaces, $WorkspaceName
    )

    Write-Host ("Setup-Workspaces called... ")

    # ... rest of function here
}

The Write-Host output never appears in the debugger output window... so I take that to mean the function is not running at all.

The output I get in the debugger window (omitting most of it, which are a bunch of "LOADED" statements:

onecore\com\combase\objact\objact.cxx(4080)\combase.dll!00007FFB6A405105: (caller: 00007FFB6A401B12) ReturnHr(4) tid(9874) 80040154 Class not registered
onecore\net\netprofiles\service\src\nsp\dll\namespaceserviceprovider.cpp(550)\nlansp_c.dll!00007FFB242CC759: (caller: 00007FFB6A04388E) LogHr(1) tid(ea84) 8007277C No such service is known. The service cannot be found in the specified name space.
onecore\printscan\appxpackaging\signing\src\appxsip.cpp(612)\AppxSip.dll!00007FFA8490183C: (caller: 00007FFB69582C5A) ReturnHr(1) tid(ea84) 80070032 The request is not supported.
onecore\printscan\appxpackaging\signing\src\appxbundlesip.cpp(693)\AppxSip.dll!00007FFA84901327: (caller: 00007FFB69582C5A) ReturnHr(2) tid(ea84) 80070032 The request is not supported.
Internment answered 25/1, 2022 at 5:2 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.