我尝试在两种情况下从 C# 运行 PowerShell 脚本。一种情况是在本地运行(
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"
}
我从主函数中调用了运行脚本函数,如下所示:-
程序.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# 应用程序中显示所需的输出?
试试这个
内部静态 bool RunPSScript(字符串脚本,引用字符串错误,int idUtilizadorGravacao)
{
尝试
{
PSCommand 命令 = new PSCommand();
命令.AddScript(脚本);
System.Management.Automation.PowerShell ps = PowerShell.Create();
ps.Commands=命令;
System.Collections.ObjectModel.Collection
脚本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