I have a simple function in C# to call a PowerShell command and return the output and it works fine. However I want to have to be able to return values for custom functions that I add to PowerShell. Here is my C# code:
Runspace runspace = RunspaceFactory.CreateRunspace();
runspace.Open();
PowerShell ps = PowerShell.Create();
ps.Runspace = runspace;
ps.Commands.AddScript("MyCustomCommand");
ICollection<PSObject> results = ps.Invoke();
When I run PowerShell locally I have the profiles set up in the location C:\Windows\System32\WindowsPowerShell\v1.0\Microsoft.PowerShell_profile.ps1 so when I open PowerShell and input MyCustomCommand it returns a string:
Function MyCustomCommand {
[CmdletBinding()]
param()
return "someoutput"
}
However when I make that same MyCustomCommand call from C# it's not found. How can I add this profile permanently in a way that C# will also return that same output when calling the command in the same way that happens when I open an instance of PowerShell on my desktop?
Update I used the modules solution recommended by @start-automating but I was not able to run due to the execution policy so I modified it:
ps.Runspace = runspace;
ps.AddCommand("Set-ExecutionPolicy").AddArgument("Unrestricted");
ps.AddCommand("Import-Module").AddArgument("MyNewModuleName");
ps.Commands.AddScript("MyCustomCommand");
powershell.exeat runtime, or do you want to embed your current profile script in the application?