0

I have a powershell script file that contains multiple functions. I would like to call one of the functions using C#. When I invoke my command, it throws an error

    "The term 'LogIn-System' is not recognized as the name of a cmdlet, 
function, script file, or operable program. Check the spelling of the name, 
or if a path was included, verify that the path is correct and try again."

Here is some sample code:

using (PowerShell powerShellInstance = PowerShell.Create())
{
   powerShellInstance.Runspace = runSpace;

   powerShellInstance
     .AddScript("myfunctions.ps1")
     .Invoke();
   powerShellInstance
     .AddCommand("LogIn-System")
     .AddParameter("SystemName", "Connect");
   Collection<PSObject> PSOutput = await Task.Run(() => 
     powerShellInstance.Invoke());
}
1
  • 1
    AddScript() should be commands instead of a path. Try either dot-sourcing with .AddScript(".\myfunctions.ps1") or use Import-Module like .AddScript("Import-Module myfunctions.ps1") instead. Or check out one of the other suggestions in this question: stackoverflow.com/questions/6266108 Commented Jul 29, 2021 at 16:21

1 Answer 1

0

You have to use two separate invokes. One to import the module, the second is your script. Since Import-Module is a Command from a previous loaded module, call it with AddCommand. Specify the Module name to import with the AddParameter function. For example:

PS
   .AddCommand("Import-Module")
   .AddParameter("Name", "ExchangeOnlineManagement")
   .Invoke();

PS
   .AddScript([your script name])
   .Invoke();
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.