Solved

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

Posted on 2016-11-03
3
176 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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

Backup Solution for AWS

Read about how CloudBerry Backup fully integrates your backups with Amazon S3 and Amazon Glacier to provide military-grade encryption and dramatically cut storage costs on any platform.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
asp web application 3 41
Securing WEBAPI on Azure 2 26
Python to .bat or Powershell 2 29
Nested forach loop to linq 3 28
Windows 10 came with  a lot of built in applications, Some organisations leave them there, some will control them using GPO's. This Article is useful for those who do not want to have any applications in their image (example:me).
A recent project that involved parsing Tableau Desktop and Server log files to extract reusable user queries for use in other systems. I chose to use PowerShell to gather the data, and SharePoint to present it...
Exchange organizations may use the Journaling Agent of the Transport Service to archive messages going through Exchange. However, if the Transport Service is integrated with some email content management application (such as an antispam), the adminiā€¦

749 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