Want to win a PS4? Go Premium and enter to win our High-Tech Treats giveaway. Enter to Win

x
?
Solved

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

Posted on 2016-11-03
3
Medium Priority
?
623 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 13

Accepted Solution

by:
Dustin Saunders earned 2000 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 4

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 4

Author Closing Comment

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

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

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

This script can help you clean up your user profile database by comparing profiles to Active Directory users in a particular OU, and removing the profiles that don't match.
Recently we ran in to an issue while running some SQL jobs where we were trying to process the cubes.  We got an error saying failure stating 'NT SERVICE\SQLSERVERAGENT does not have access to Analysis Services. So this is a way to automate that wit…
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…
In this video, Percona Solution Engineer Rick Golba discuss how (and why) you implement high availability in a database environment. To discuss how Percona Consulting can help with your design and architecture needs for your database and infrastr…

618 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