I can run this script perfectly from my desktop:
private void Sleep_Click(object sender, EventArgs e)
{
PowerShell ps = PowerShell.Create();
PetSerAl has, as usual, provided the crucial pointer in a comment on the question:
Use .AddCommand() to add a command by name or executable / script-file path.
By contrast, use the (poorly named) .AddScript() method to add a self-contained piece of PowerShell source code as a string, which is parsed into a script block (a better name for the method would therefore have been .AddScriptBlock()).
Therefore, simply using .AddCommand() in lieu of .AddScript() is the solution:
ps.AddCommand(@"C:\Program Files (x86)\Home Control\scripts\alllightsoff.ps1");
If you wanted to pass an argument, say -Delay 60, you'd then call:
ps.AddParameters(new Dictionary<string, int> { ["Delay"] = 60 });
.AddScript() didn't work:Since you're passing a piece of PowerShell source code, the usual evaluation rules apply:
A file path with embedded spaces such as
C:\Program Files (x86)\Home Control\alllightsoff.ps1 needs quoting for the PowerShell parser to recognize it as a single argument.
However, once quoted, you must use &, the call operator, for PowerShell to know that the quoted path represents a command (script file) to invoke (otherwise, it would treat it as a string).
Hence, if you want to use .AddScript() in your case, you must use:
ps.AddScript(@"& 'C:\Program Files (x86)\Home Control\scripts\alllightsoff.ps1'");
Note the leading & and the '...' around the file path.
If you wanted to pass an argument, say -Delay 60, you'd have to include it in the string:
ps.AddScript(
@"& 'C:\Program Files (x86)\Home Control\scripts\alllightsoff.ps1' -Delay 60"
);