First time posting here, hoping its an easy question. I have the following C# code:
try
{
Process process;
var ps1File = @"C:\Program Files\Maximus\MFS TechTools\Scripts\Term-ADUser.ps1";
var startInfo = new ProcessStartInfo()
{
//CreateNoWindow = true,
FileName = "powershell.exe",
RedirectStandardError = true,
RedirectStandardOutput = true,
CreateNoWindow = true,
Arguments = $"-NoProfile -ExecutionPolicy ByPass -File \"{ps1File}\" \"{usr}\"",
UseShellExecute = false
};
process = Process.Start(startInfo);
process.WaitForExit();
StreamReader output = process.StandardOutput;
while (output.Peek() > -1)
{
ni.Append(output.ReadLine() + Environment.NewLine);
}
process = null;
}
catch (Exception e)
{
ni.Append((e.Message) + Environment.NewLine);
}
To keep it simple, the code block, start the process 'powershell.exe' and runs a PowerShell script that we will call testscript.ps1.
Below is the PowerShell script:
Function Set-Flag($User) {
try
{
Set-ADUser -Identity $User -CannotChangePassword $true
$text = "Set - User Cannot Change Password Flag!"
}
catch
{
$text = $_
}
return $text
quit
}
Set-Flag
From my C# code being, I need to pass a string variable called usr to the PowerShell script so that it can be used in the function in the PowerShell script.
I have seen many examples of how to do this but can't seem to wrap my head around it.
I have tried using other methods of running the script directly from C# but due to a know issue between C# and the active directory attribute CannotChangePassword, it produces errors.
Any help would be appreciated. Thanks,
I tried the above C# code, expecting it to pass the value of variable usr to the PowerShell script.
The C# code ran the PowerShell script but did not seem to pass the value of the variable usr to the script.