Search code examples
c#powershellparameter-passing

How to pass arguments to a powershell script from C# program?


I have a script file sample.ps1 which has the following command :

copy-item C:\source -destination C:\destination.

Instead of hard coding the value for source and destination I want to pass it as arguments to the script.

copy-item $source -destination $destination.

I want to call this script from a stand alone client and pass the source and destination as parameters. I have the following program to execute the script file :

            string shellUri = "http://schemas.microsoft.com/powershell/Microsoft.PowerShell";
            string userName = "MachineName\\Administrator";
            string password = "Password";
            SecureString securePassword = new SecureString();

            foreach (char c in password)
            {
                securePassword.AppendChar(c);
            }
            PSCredential credential = new PSCredential(userName, securePassword);
            WSManConnectionInfo connectionInfo = new WSManConnectionInfo(false, "machinename", 5985, "/wsman", shellUri, credential);
            using (Runspace runspace = RunspaceFactory.CreateRunspace(connectionInfo))
            {

                runspace.Open();
        String file = "C:\\scripts\\Sample.ps1";
                Pipeline pipeline = runspace.CreatePipeline();

                pipeline.Commands.AddScript(System.IO.File.ReadAllText(file));
        }

I want to pass the parameters to the script Sample.ps1 through the C# program. How is that possible?


Solution

  • Here are the answers to all of your questions: