使用 C# 中的参数执行 Powershell 脚本

Sub*_*per 4 c# powershell visual-studio powershell-cmdlet

我陷入了这个项目,我尝试使用 Powershell 脚本创建一个用户,但我想从我的 Windowsform 运行该脚本。

脚本如下所示:

[CmdletBinding()]
 param (
[string] $Password
)  
[SecureString] $securePassword = ConvertTo-SecureString $Password -AsPlainText -Force

CreateUser $Username $Fullname $securePassword $Groups

function CreateUser { 
Param([string] $Username, [string] $Fullname, [SecureString] $Password, [string[]] $Groups)

Process{   
New-localuser -name $Username -FullName $Fullname -password $Password | Out-Null

    Write-Host "User" $_.username "created!"
    
    AddUserToGroup($Username, $Groups)
}
}

function AddUserToGroup([string] $Username, [string[]] $Groups){
Write-Output "Hello World";
}
Run Code Online (Sandbox Code Playgroud)

我知道代码可以工作,因为当我在 Powershell 中运行它时,它就可以工作。

我需要在 C# 代码中添加 4 个参数,即用户名、全名、密码和组[数组],因为脚本中的方法需要这些参数。

当我尝试从 C# 代码运行脚本时,出现错误:

The term "" is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
Run Code Online (Sandbox Code Playgroud)

我的 C# 看起来像这样

        RunspaceConfiguration runspaceConfiguration = RunspaceConfiguration.Create();
        Runspace runspace = RunspaceFactory.CreateRunspace(runspaceConfiguration);
        runspace.Open();

        RunspaceInvoke scriptInvoker = new RunspaceInvoke(runspace);
        string _pathToPSFile = File.ReadAllText(@"C:\Code\PathToScript\CreateUser.ps1");
        Pipeline pipeline = runspace.CreatePipeline();
        Command scriptCommand = new Command(_pathToPSFile);
        List<CommandParameter> commandParameters = new List<CommandParameter>();
        foreach (string scriptParameter in scriptParameters)
        {
            CommandParameter commandParm = new CommandParameter(null, scriptParameter);
            commandParameters.Add(commandParm);
            scriptCommand.Parameters.Add(commandParm);
        }
        pipeline.Commands.Add(scriptCommand);
        Collection<PSObject> psObjects;
        psObjects = pipeline.Invoke();
Run Code Online (Sandbox Code Playgroud)

我不知道当我使用 C# 运行脚本并添加参数时会发生什么,我是否必须在 C# 代码中调用该函数,还是它会自动执行?我是 Powershell 代码的初学者

这里真的需要帮助:)

如果您需要更多信息,或者有不清楚的地方,请告诉我:)

编辑 #1 C# 代码现在看起来像这样,必须添加运行空间调用,这是执行策略问题的原因

        RunspaceConfiguration runspaceConfiguration = RunspaceConfiguration.Create();
        Runspace runspace = RunspaceFactory.CreateRunspace(runspaceConfiguration);
        runspace.Open();

        RunspaceInvoke scriptInvoker = new RunspaceInvoke(runspace);
        scriptInvoker.Invoke("$ExecutionPolicy = Get-ExecutionPolicy -Scope CurrentUser");
        scriptInvoker.Invoke("Set-ExecutionPolicy Unrestricted -Scope CurrentUser ");

        PowerShell ps = PowerShell.Create();
        ps.Runspace = runspace;
        ps.AddCommand(@"C:\Code\Internal\as1UserManager\as1UserManager\PSScripts\CreateUser.ps1");

        foreach (string scriptParameter in scriptParameters)
        {
            ps.AddArgument(scriptParameter);
        }

        Collection<PSObject> psObjects = ps.Invoke();
        scriptInvoker.Invoke("Set-ExecutionPolicy -Scope CurrentUser $ExecutionPolicy -Force");
Run Code Online (Sandbox Code Playgroud)

编辑 #2 我必须按照建议在 CmdletBinding() 中添加参数。当然,在它存在之前,它并没有运行,称为 CreateUser 函数。现在一切都很好。代码现在看起来像这样

[CmdletBinding()]
param (  
[string] $Username = "Leon",
[string] $Fullname = "Kennedy",
[string] $Password = "sml12345",
[string] $Groups = "something"
) 
[SecureString] $securePassword = ConvertTo-SecureString $Password              -AsPlainText -Force


function CreateUser {
Param([string] $Username, [string] $Fullname, [SecureString]    securePassword, [string] $Groups)

Process{   
New-localuser -name $Username -FullName $Fullname -password  $securePassword | Out-Null

    Write-Host "User" $Username "created!"
    
    AddUserToGroup($Username, $Groups)
   }
}

CreateUser $Username $Fullname $securePassword $Groups

function AddUserToGroup([string] $Username, [string] $Groups){
Write-Output "Hello World";
}
Run Code Online (Sandbox Code Playgroud)

Mat*_*sen 5

相反,创建该类的PowerShell实例,它将允许您添加未命名的参数:

RunspaceConfiguration runspaceConfiguration = RunspaceConfiguration.Create();
Runspace runspace = RunspaceFactory.CreateRunspace(runspaceConfiguration);
runspace.Open();

PowerShell ps = PowerShell.Create();
ps.Runspace = runspace;
ps.AddCommand(@"C:\Code\PathToScript\CreateUser.ps1");

foreach (string scriptParameter in scriptParameters)
{
    ps.AddArgument(scriptParameter);
}

Collection<PSObject> psObjects;
psObjects = pipeline.Invoke();
Run Code Online (Sandbox Code Playgroud)