Search code examples
c#powershellinvokeexecute

Run Powershell Script in c# using Powershell Class


I know this question is getting asked a lot. But none of the Solutions helped me.

My Script won't run. When I'm executing it with Powershell it works. But not with this C# Code :

using (PowerShell ps = PowerShell.Create())
{
    ps.AddScript(@"& 'MyPathToTheScript'");
    ps.Invoke();
}

As you can see I tried AddScript and AddCommand, but either won't run my script. I followed the Instructions that I saw on Microsoft Docs :

Adding and invoking commands

Except i don't need any parameters :)

Edit#1

My PowerShell Script, needs to be run as Administrator. Could this be the issue ? That the script runs, but throws an Error 'cause of 'Access denied'?

Can I do this from C# or do I have to add this in the script ?

Thanks for your help :)


Solution

  • I found my Solution in this thread. The Script was executed in behind, but didn't found the New-LocalUser function, so I googled and found out, that the Powershell has to run in 64 bit. I added the Code from the link below to my C# Code and it worked :)

    enter link description here