I am trying to write a Windows Form application in C # that displays AD Attributes for the specified user. The way I want it to work is for the user to enter a value (username) in a text field that is passed as a parameter to the Powershell script, and the output is displayed in the form.
My C # code to create a parameter and call the script is as follows:
private string RunScript(string scriptText) { // create Powershell runspace Runspace runspace = RunspaceFactory.CreateRunspace(); // open it runspace.Open(); RunspaceInvoke scriptInvoker = new RunspaceInvoke(runspace); // create a pipeline and feed it the script text Pipeline pipeline = runspace.CreatePipeline(); pipeline.Commands.AddScript(scriptText); pipeline.Commands.Add(new Command("Set-ExecutionPolicy Unrestricted -Scope Process", true)); // "Get-Process" returns a collection of System.Diagnostics.Process instances. pipeline.Commands.Add("Out-String"); //Create parameter and pass value to script String username = textBox3.Text; String scriptfile = @"c:\\scripts\\getpasswordexpirydate.ps1"; Command myCommand = new Command(scriptfile, false); CommandParameter testParam = new CommandParameter("username", username); myCommand.Parameters.Add(testParam); pipeline.Commands.Add(myCommand); // execute the script Collection<PSObject> results = pipeline.Invoke(); // close the runspace runspace.Close(); // convert the script result into a single string StringBuilder stringBuilder = new StringBuilder(); foreach (PSObject obj in results) { stringBuilder.AppendLine(obj.ToString()); } // return the results of the script that has // now been converted to text return stringBuilder.ToString(); }
My PowerShell script looks like this:
param([string]$username) function Get-XADUserPasswordExpirationDate() { Param ([Parameter(Mandatory=$true, Position=0, ValueFromPipeline=$true, HelpMessage="Identity of the Account")] [Object] $accountIdentity) PROCESS { $accountObj = Get-ADUser $accountIdentity -properties PasswordExpired, PasswordNeverExpires, PasswordLastSet if ($accountObj.PasswordExpired) { echo ("Password of account: " + $accountObj.Name + " already expired!") } else { if ($accountObj.PasswordNeverExpires) { echo ("Password of account: " + $accountObj.Name + " is set to never expires!") } else { $passwordSetDate = $accountObj.PasswordLastSet if ($passwordSetDate -eq $null) { echo ("Password of account: " + $accountObj.Name + " has never been set!") } else { $maxPasswordAgeTimeSpan = $null $dfl = (get-addomain).DomainMode if ($dfl -ge 3) {
If I run a script in PowerShell, for example .. \ script.ps1 jsmith with the parameter "jsmith" as the parameter that it works, however, when using the C # parameter, it does not accept this parameter and spits out "
Is there something I did wrong in my C # code that calls this parameter so as not to go to the script and accept it as input?
thanks
source share