Solved

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

Posted on 2016-11-03
3
39 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:ccbbc_cs
  • 2
3 Comments
 
LVL 12

Accepted Solution

by:
Dustin Saunders earned 500 total points
Comment Utility
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:ccbbc_cs
Comment Utility
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:ccbbc_cs
Comment Utility
This worked great! Thank you Dustin.
0

Featured Post

Do You Know the 4 Main Threat Actor Types?

Do you know the main threat actor types? Most attackers fall into one of four categories, each with their own favored tactics, techniques, and procedures.

Join & Write a Comment

Active Directory replication delay is the cause to many problems.  Here is a super easy script to force Active Directory replication to all sites with by using an elevated PowerShell command prompt, and a tool to verify your changes.
Synchronize a new Active Directory domain with an existing Office 365 tenant
Excel styles will make formatting consistent and let you apply and change formatting faster. In this tutorial, you'll learn how to use Excel's built-in styles, how to modify styles, and how to create your own. You'll also learn how to use your custo…
When you create an app prototype with Adobe XD, you can insert system screens -- sharing or Control Center, for example -- with just a few clicks. This video shows you how. You can take the full course on Experts Exchange at http://bit.ly/XDcourse.

743 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

16 Experts available now in Live!

Get 1:1 Help Now