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

zphenhs4  于 5个月前  发布在  Shell
关注(0)|答案(1)|浏览(71)

我尝试在两种情况下从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"
}

字符串
我从main函数调用run脚本函数,如下所示:

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文件可以运行并成功显示输出。*

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

cgh8pdjw

cgh8pdjw1#

试试这个:

internal static bool RunPSScript(string Script, ref string erro, int idUtilizadorGravacao)
        {
            try
            {
                PSCommand command = new PSCommand();
                command.AddScript(Script);
                System.Management.Automation.PowerShell ps = PowerShell.Create();
                ps.Commands = command;
                System.Collections.ObjectModel.Collection<System.Management.Automation.PSObject> results = ps.Invoke();
                if (ps.Streams != null && ps.Streams.Error.Count > 0)
                {
                    foreach (System.Management.Automation.ErrorRecord item in ps.Streams.Error)
                    {
                        if (item.Exception.Message != null)
                        {
                            erro = item.Exception.Message;
                        }
                        if (item.ErrorDetails.Message != null)
                        {
                            erro += " " + item.ErrorDetails.Message;
                        }
                        Logs.RegistarLog(SourceDataContracts.Util.GeralEnum.UserAccountAction.Sistema, erro, true, idUtilizadorGravacao, 0);
                    }
                }
                if (!string.IsNullOrEmpty(erro))
                {
                    return false;
                }
                return true;
            }
            catch (Exception ex)
            {
                erro += " " + ex.Message;
                return false;
            }
        }

字符串
脚本PS

$Tenant="usr"
$TenantPass = ConvertTo-SecureString "ww" -AsPlainText -Force
$credential= new-object -typename System.Management.Automation.PSCredential -argumentlist    $Tenant, $TenantPass   
$s = New-PSSession -ComputerName "svr" -Credential $credential
Invoke-Command -Session $s -Command { 
& pwsh      -file='c:\file.ps1' -var='test'
}
Remove-PSSession $s

相关问题