Solved

Call Powershell Script (.ps1)--that requires parameters--from C#

Posted on 2016-11-03
3
63 Views
Last Modified: 2016-11-08
I have a Powershell script that uses a parameter which is basically a string parameter for varying purposes.  I want to call the script from C# and supply the parameter.  All of the examples I have found have me either inhaling the contents of the file as text and adding parameters to specific commands, or inhaling the contents and not discussing parameter requirements for the script.

How do I execute the script and supply the user-defined parameter of the script?  Here is a how the script file is setup:
param(
    [Parameter(Position=0,Mandatory=$true)][String]$FileName
)

$ADCreds = Get-Credential

Import-Module ActiveDirectory

Import-Csv $FileName | ForEach-Object {
    
    If ($_.status -ne 'Cleared') {
        foreach($user in Get-ADUser -filter '*' -Credential $ADCreds -SearchBase 'ou=Users,DC=MYCOMPANY,DC=LAN' -Properties * | Select-Object givenName,sn,sAMAccountName) {
            Set-ADObject -Identity $user.sAMAccountName -Remove @{upnsuffixes="Cleared.MyCompany.LAN"} -Credential $creds
        }
    }
    else {
        foreach($user in Get-ADUser -filter '*' -Credential $ADCreds -SearchBase 'ou=Users,DC=MYCOMPANY,DC=LAN' -Properties * | Select-Object givenName,sn,sAMAccountName) {
            Set-ADUser -Identity $user.sAMAccountName  -UserPrincipalName ($user.sAMAccountName + "@Cleared.MyCompany.LAN") -Credential $creds
        }
    }
}

Open in new window

I already know that I need to do something about the ADCreds, my specific topic is how to call this file from C# and supply the $FileName parameter.
0
Comment
Question by:Shane Kahkola
  • 2
3 Comments
 
LVL 12

Accepted Solution

by:
Dustin Saunders earned 500 total points
ID: 41872418
This might be helpful, this is the code I use to call one of my powershell scripts.  This method passes a dual array of strings [variableName,variableValue] and then sets the variables in the script.

As far as the credentials go, I generally store that in a secured file so I have a centralized repository of credentials for the different environments.

 public static void RunPowershellCommand(string scriptPath, string[,] variables)
        {
            RunspaceConfiguration runspaceConfiguration = RunspaceConfiguration.Create();
            Runspace runspace = RunspaceFactory.CreateRunspace(runspaceConfiguration);
            runspace.Open();
            RunspaceInvoke scriptInvoker = new RunspaceInvoke(runspace);
            scriptInvoker.Invoke("Set-ExecutionPolicy Unrestricted");

            Pipeline pipeline = runspace.CreatePipeline();

            Command myCommand = new Command(scriptPath, false);

            if (variables[0, 0] != null)
            {
                for (int i = 0; i < variables.GetLength(0); i++)  //Add all the powershell variables we might need in the partner specific.
                {
                    runspace.SessionStateProxy.SetVariable(variables[i, 0], variables[i, 1]);
                }
            }


            pipeline.Commands.Add(myCommand);
            Collection<PSObject> psObjects;
            psObjects = pipeline.Invoke();
            runspace.Close();
      }

Open in new window


Note that this requires powershell references:
using System.Management.Automation;
using System.Management.Automation.Runspaces;
using System.Collections.ObjectModel;

Open in new window

0
 
LVL 3

Author Comment

by:Shane Kahkola
ID: 41877330
I am sorry for the delay in response. Unfortunately my question came late Thursday and I have been away from my office since. I am attempting to implement your idea, Dustin, and will report back today with my results.
0
 
LVL 3

Author Closing Comment

by:Shane Kahkola
ID: 41879442
This worked great! Thank you Dustin.
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Synchronize a new Active Directory domain with an existing Office 365 tenant
A procedure for exporting installed hotfix details of remote computers using powershell
Video by: Mark
This lesson goes over how to construct ordered and unordered lists and how to create hyperlinks.
Many functions in Excel can make decisions. The most simple of these is the IF function: it returns a value depending on whether a condition you describe is true or false. Once you get the hang of using the IF function, you will find it easier to us…

920 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

13 Experts available now in Live!

Get 1:1 Help Now