1

I would like to run the following powershell commands from my C# application:

Enter-PSSession –ComputerName fedsrv01.domain.local

Start-ADSyncSyncCycle -PolicyType Delta

I found some information on the Powershell Class but struggling to achieve what I want due to my lack of experience.

https://learn.microsoft.com/en-us/dotnet/api/system.management.automation.powershell?redirectedfrom=MSDN&view=pscore-6.2.0

This is what I have so far:

I have added the assembly and referenced system.management.automation

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

     //powershell.AddCommand("get-process");
     powershell.AddCommand("Enter-PSSession -ComputerName fedsrv01.domain.local");


     powershell.Invoke();
}

I get an error saying, 'The term 'Enter-PSSession -ComputerName fedsrv01.domain.local' is not recognized as the name of a cmdlet, function, script file, or operable program.

if I use: powershell.AddCommand("get-process") it executes fine.

If I launch Powershell on the same PC and enter, Enter-PSSession -ComputerName fedsrv01.domain.local it works fine.

Any assistance would be much appreciated.

Cheers,

Jono

Steve B
  • 36,818
  • 21
  • 101
  • 174
Jono
  • 49
  • 1
  • 8
  • Does this answer your question? [Powershell commands from C# 'the term is not recognizes as cmdlet'](https://stackoverflow.com/questions/20272931/powershell-commands-from-c-sharp-the-term-is-not-recognizes-as-cmdlet) – Vega Jun 18 '21 at 04:12

2 Answers2

2

Try compiling your application as x64. If it is compiled as x86 platform then it will be using the virtualized System32 dir so the function you require may not exist.

Powershell commands from C# 'the term is not recognizes as cmdlet'

mr.coffee
  • 962
  • 8
  • 22
1

Ok, after more research into the PowerShell class I now realise that you have to add the parameters separately using the .addparameter method. .addcommand is just for the PowerShell commands. It now makes sense why I got the error saying the command could not be found. It was assuming the entire string was a command. Problem solved!

Jono

Jono
  • 49
  • 1
  • 8