1

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 :)

2
  • If you have permission issues, it might be useful to test with a very simple script, so that you are only testing the c# - powershell integration. Commented Aug 10, 2021 at 7:43
  • I found the solution, it was becaus the Powershell didnt run in 64 bit. Now it works. I'll post the solution Commented Aug 10, 2021 at 7:59

2 Answers 2

1

I haven't used the SDK but as stated in the documents, it seems that methods including AddScript create a command pipeline, and Invoke should be called on them.

So maybe you should use it like below:

using (PowerShell ps = PowerShell.Create().AddScript("YourPathToTheScript"))
{
    ps.Invoke();
}
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.