简体   繁体   English

在 C# 中创建一个 powershell 对象

[英]create a powershell object in c#

I would like to create a powershell object and pass it values from a textbox but I don't know how to do it.我想创建一个 powershell 对象并从文本框中传递它的值,但我不知道该怎么做。 I did it from visual basic but I don't know how to do it in c #我是从visual basic做的,但我不知道如何在c#中做

this is my example in vba这是我在 vba 中的示例

strPSCommand = ""Get-AdUser "" & txt_userName & "" -Properties * |select-object Name,department,company,extensionAttribute1,title,manager| Export-csv C:\Users\etaarratia\Documents\prueba\nombre.txt""

strDOSCommand = ""powershell -command "" & strPSCommand & """"

Set objShell = CreateObject(""Wscript.Shell"")

Set objExec = objShell.Exec(strDOSCommand)

I want to create something similar in c#我想在 c# 中创建类似的东西

Preparation:准备:

using System.Management.Automation; //install with Nuget Package Manager
//Create a new PowerShell Class instance and empty pipeline
using (PowerShell PowerShellInstance = PowerShell.Create())
{
  // use "AddScript" to add the contents of a script file to the end of the execution pipeline.

  // use "AddCommand" to add individual commands/cmdlets to the end of the execution pipeline.

  PowerShellInstance.AddScript("param($param1) $d = get-date; 
  $s = 'test string value'; " + "$d; $s; $param1; get-service");

  // use "AddParameter" to add a single parameter to the last command/script on the pipeline.
  PowerShellInstance.AddParameter("param1", "parameter 1 value!");
}

Script/Command Execution:脚本/命令执行:

Now you have populated the pipeline with scripts, commands and parameters.现在您已经用脚本、命令和参数填充了管道。 You can now execute the pipeline either async or synchronously:您现在可以异步或同步执行管道:

Execute Pipeline synchronously:同步执行流水线:

// execute pipeline synchronously wihout output
    PowerShellInstance.Invoke();  

 // execute the pipeline symchronously with output
    Collection<PSObject> PSOutput = PowerShellInstance.Invoke();

// loop through each output object item
foreach (PSObject outputItem in PSOutput)
{
    // if null object was dumped to the pipeline during the script then a null
    // object may be present here. check for null to prevent potential Null Reference Exception.
    if (outputItem != null)
    {
        //do something with the output item 
        // outputItem.BaseOBject
    }
}

Execute Pipeline asynchronously:异步执行流水线:

using (PowerShell PowerShellInstance = PowerShell.Create())
    {
        // this script has a sleep in it to simulate a long running script
        PowerShellInstance.AddScript("start-sleep -s 10; get-service");

        // begin invoke execution on the pipeline
        IAsyncResult result = PowerShellInstance.BeginInvoke();

        // simulate being busy until execution has completed with sleep or wait
        while (result.IsCompleted == false)
        {
            Console.WriteLine("Pipeline is being executed...");
            Thread.Sleep(3000);
            //optionally add a timeout here...            
        }           
    }

You can write a method in C# that will save the details of the user to the file you are looking for.您可以在 C# 中编写一个方法,将用户的详细信息保存到您要查找的文件中。

Helper Method to Save User保存用户的助手方法

This method saves the details you are looking for: Name,department,company,extensionAttribute1,title,manager此方法保存您要查找的详细信息: Name,department,company,extensionAttribute1,title,manager

    public static void SaveUser(UserPrincipal user, string textFile)
    {
        DirectoryEntry de = (user.GetUnderlyingObject() as DirectoryEntry);
        string thisUser = $"{user.Name},{de.Properties["department"].Value},{de.Properties["extensionAttribute1"].Value},{de.Properties["title"].Value},{de.Properties["manager"].Value.ToString().Replace(",","|")}";
        File.AppendAllLines(textFile, new string[] { thisUser }); // Append a new line with this user.
    }

and look up and save the user in main method like this,并像这样在 main 方法中查找并保存用户,

Usage用法

Assemblies you will need for this您将需要的程序集

    using System.DirectoryServices;
    using System.DirectoryServices.AccountManagement;
    using System;
    using System.IO;

and usage will be like this,和用法将是这样的,

    string txt_userName = "userId";
    PrincipalContext ctx = new PrincipalContext(ContextType.Domain, "domainName", "userName", "Password");
    // if you are running this script from a system joined to this domain, and logged in with a domain user, simply use
    // PrincipalContext ctx = new PrincipalContext(ContextType.Domain);

    UserPrincipal user = (UserPrincipal)Principal.FindByIdentity(ctx, IdentityType.Name, txt_userName);
    if (user != null)
    {
        string saveToFile = @"C:\Users\etaarratia\Documents\prueba\nombre.txt";
        SaveUser(user, saveToFile);
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM