Запустите скрипт Powershell с параметрами, удаленно передаваемыми из C # - PullRequest
0 голосов
/ 05 марта 2019

Я пытался запустить скрипт PowerShell из C # в двух случаях.Один случай - запустить его локально (powershell.ps1 на локальном компьютере), а другой - запустить на удаленном компьютере (powershell.ps1 на удаленном компьютере).

Сценарий содержит обязательную функциюпараметр servicename и action, в который предполагается вставить пользователя.Я хотел передать параметры из консольного приложения 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 на удаленном компьютере без параметров могут быть запущены и успешно отображать выходные данные.

Как отправить параметры servicename и action из приложения C # в сценарий .ps1 и показатьжелаемый вывод обратно в приложение C #?

...