在 C# 中创建 PowerShell 对象



我想创建一个powershell对象并从文本框中传递值,但我不知道该怎么做。我从视觉基础中做到了,但我不知道如何在 c # 中做到这一点

这是我在 VBA 中的示例

strPSCommand = ""Get-AdUser "" & txt_userName & "" -Properties * |select-object Name,department,company,extensionAttribute1,title,manager| Export-csv C:UsersetaarratiaDocumentspruebanombre.txt""
strDOSCommand = ""powershell -command "" & strPSCommand & """"
Set objShell = CreateObject(""Wscript.Shell"")
Set objExec = objShell.Exec(strDOSCommand)

我想在 c# 中创建类似的东西

可以用 C# 编写一个方法,将用户的详细信息保存到要查找的文件中。

保存用户的帮助程序方法

此方法保存您要查找的详细信息: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.
}

并在main方法中查找并保存用户,如下所示,

用法

为此需要的程序集

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

用法将是这样的,

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:UsersetaarratiaDocumentspruebanombre.txt";
SaveUser(user, saveToFile);
}

准备:

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!");
}

脚本/命令执行:

现在,你已使用脚本、命令和参数填充了管道。现在可以异步或同步执行管道:

同步执行管道:

// 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
}
}

异步执行管道:

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...            
}           
}

最新更新