使用从C#远程传递的参数运行Powershell脚本

时间:2019-03-05 07:18:40

标签: c# powershell parameters console-application remote-access

在两种情况下,我尝试从C#运行PowerShell脚本。一种情况是在本地运行(powershell.ps1在本地计算机上),另一种情况是在远程计算机上运行(powershell.ps1在远程计算机上)。

该脚本包含具有强制参数servicenameaction的函数,这些函数应该由用户插入。我想从C#控制台应用程序传递参数。

powershell.ps1

param (
[Parameter(Mandatory=$true)]
[string] $ServiceName,
[String] $Action
)

function CheckService($ServiceName)
{
    if (Get-Service $ServiceName -ErrorAction SilentlyContinue)
    {
        $ServiceStatus = (Get-Service -Name $ServiceName).Status
        return "$ServiceName - $ServiceStatus"
    }
    else
    {
        return"$ServiceName not found"
    }
}

if (Get-Service $ServiceName -ErrorAction SilentlyContinue)
{

    if ($Action -eq 'Check')
    {
        CheckService $ServiceName
    }
    else
    {
        return "Action parameter is missing or invalid!"
    }
}
else
{
    return "$ServiceName not found"
}

我从主函数中这样调用运行脚本函数:-

Program.cs

 static void Main(string[] args)
 {
    try
    {
        var scriptremote = @"C:\\remote\\powershell.ps1 service1 check";
        var scriptlocal = @"\\local\\powershell.ps1 service1 check";
        var computer = "xxxxx.yyyy.com";
        var username = @"user";
        var password = "p4$$w0rD";
        string errors;
        IEnumerable<PSObject> output;
        var success = RunPowerShellScriptRemote(scriptremote, computer, username, password, out output, out errors);
        var localrun = RunPowerShellScript(scriptlocal, out output, out errors);
    }
    catch (Exception e)
    {
        Console.Write(e.Message);
    }
    Console.ReadKey();
 }

public static bool RunPowerShellScript(string script, out IEnumerable<PSObject> output, out string errors)
{
    return RunPowerShellScriptInternal(script, out output, out errors, null);
}

public static bool RunPowerShellScriptRemote(string script, string computer, string username, string password, out IEnumerable<PSObject> output, out string errors)
{
    output = Enumerable.Empty<PSObject>();
    var credentials = new PSCredential(username, ConvertToSecureString(password));
    var connectionInfo = new WSManConnectionInfo(false, computer, 5985, "/wsman", "http://schemas.microsoft.com/powershell/Microsoft.PowerShell", credentials);
    var runspace = RunspaceFactory.CreateRunspace(connectionInfo);
    try
    {
        runspace.Open();
    }
    catch (Exception e)
    {
        errors = e.Message;
        return false;
    }
    return RunPowerShellScriptInternal(script, out output, out errors, runspace);
}

public static bool RunPowerShellScriptInternal(string script, out IEnumerable<PSObject> output, out string errors, Runspace runspace)
{
    output = Enumerable.Empty<PSObject>();
    using (var ps = PowerShell.Create())
    {
        ps.Runspace = runspace;
        ps.AddScript(script);
        ps.AddParameter("service1");
        ps.AddParameter("Check");
        try
        {
            output = ps.Invoke();
            foreach (var o in output)
                Console.Write(o.ToString());
        }
        catch (Exception e)
        {
            Trace.TraceError("Error occurred in PowerShell script: " + e);
            errors = e.Message;
            return false;
        }

        if (ps.Streams.Error.Count > 0)
        {
            errors = String.Join(Environment.NewLine, ps.Streams.Error.Select(e => e.ToString()));
            return false;
        }

        errors = String.Empty;
        return true;
    }
}

此代码能够在本地运行并显示所需的输出。但是,当我尝试远程运行它时,会出现错误(即使在本地运行也是如此):

The term 'C:\\remote\\powershell.ps1 service1 check' 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

我也尝试使用ps.AddCommands代替ps.AddScript,但没有得到输出。还尝试声明scriptremote = @"&\"C:\\remote\\powershell.ps1" service1 check",但出现相同的错误。

注意:远程访问是可以的。可以运行远程计算机中没有参数的不同.ps1文件,并成功显示输出。

如何从C#应用程序将servicenameaction参数发送到.ps1脚本,并在C#应用程序中显示所需的输出?

0 个答案:

没有答案