So I have look at several post here and on other sites But even after changing Executionpolicy to RemoteSigened I still get the error, I have even tried with Bypass on MachinePolicy and enabled scripts to run in group policies.
I found this example Passing PowerShell parameter with C# I get the following error when i try to Invoke.
System.Management.Automation.PSSecurityException: 'File Path\TestADUser.ps1 cannot be loaded because running scripts is disabled on this system. For more information, see about_Execution_Policies at https://go.microsoft.com/fwlink/?LinkID=135170.'
public string Test()
{
StringBuilder sb = new StringBuilder();
string script = @"Path\TestADUser.ps1";
var FirstName = "Test1234";
PowerShell shell = PowerShell.Create();
shell.AddCommand(script, false);
shell.AddParameter("FirstName", FirstName);
Collection<PSObject> results = shell.Invoke();
Collection<ErrorRecord> errors = shell.Streams.Error.ReadAll();
if (errors.Count > 0)
{
foreach (ErrorRecord error in errors)
{
sb.AppendLine(error.ToString());
}
}
else
{
foreach (PSObject result in results)
{
sb.AppendLine(result.ToString());
}
}
return sb.ToString();
}
TestADUser.ps1
param(
[parameter(position=0)]
[string]$FirstName)
##Output
Write-Output $FirstName
