【发布时间】:2014-07-29 00:27:03
【问题描述】:
我创建了一个供内部使用的 asp.net Web 应用程序,该应用程序允许某些用户启动和停止链接到 QA 测试环境的虚拟机,页面后面的代码运行一个 powershell 脚本,该脚本启动选定的服务器一次按钮在 ASP.net 页面上按下。
我已经从这个网站上研究和实施了很多代码,但我遇到了一些问题。
每次我单击主页上的按钮时,从 powershell 脚本反馈的错误都会显示“您不能在空值表达式上调用方法。”唯一的问题是,如果我从这样的 powershell 提示符运行它“。\script\test.ps1 'W7EA9'”它工作正常。
这是调用powershell脚本的类。
public String Startserver(String Servername)
{
String scriptText =". \\scripts\\test.ps1 " + Servername + "";
// create Powershell runspace
Runspace runspace = RunspaceFactory.CreateRunspace();
// open it
runspace.Open();
// create a pipeline and feed it the script text
Pipeline pipeline = runspace.CreatePipeline();
pipeline.Commands.AddScript(scriptText);
// execute the script
Collection<PSObject> results = new Collection<PSObject>();
try
{
results = pipeline.Invoke();
}
catch (Exception ex)
{
results.Add(new PSObject((object)ex.Message));
}
// close the runspace
runspace.Close();
// convert the script result into a single string
StringBuilder stringBuilder = new StringBuilder();
foreach (PSObject obj in results)
{
stringBuilder.AppendLine(obj.ToString());
}
return stringBuilder.ToString();
//return scriptText;
}
这是它试图运行的 powershell 脚本
Param ($server = $arg[0])
$Core = get-wmiobject -namespace root\virtualization -class Msvm_Computersystem -filter "ElementName = '$server'"
$status = $Core.RequestStateChange(2) `
这可能很明显,但我只是没有看到它,任何帮助都会很棒。
谢谢
克里斯
【问题讨论】:
-
后面的代码将尝试在服务器中运行 powershell 命令。这是你要找的吗?
-
您确定将正确的 ServerName 传递给函数吗?
-
嗨,我希望在站点所在的服务器上运行脚本,我已经在我的机器上调试了应用程序,并且服务器名称在传递给 powershell 之前在字符串中传递跨度>
-
为什么在字符串末尾有“”?这还不够吗?
String scriptText =". \\scripts\\test.ps1 " + Servername; -
好点,我会改变它,看看效果如何
标签: c# asp.net powershell