PowerShell脚本问题
代码如下:
static String checkBackUp()
{
Runspace runspace = RunspaceFactory.CreateRunspace();
runspace.Open();
Pipeline pipeline = runspace.CreatePipeline();
pipeline.Commands.Add("Get-WBSummary");
pipeline.Commands.Add("Out-String");
Collection<PSObject> results = new Collection<PSObject>();
try
{
results = pipeline.Invoke();
}
catch (Exception ex)
{
results.Add(new PSObject((object)ex.Message));
}
runspace.Close();
StringBuilder stringBuilder = new StringBuilder();
foreach (PSObject obj in results)
{
stringBuilder.AppendLine(obj.ToString());
}
return stringBuilder.ToString();
}
问题是这会运行每个 cmdlet(例如 Get-Process
),但是当我尝试验证是否已进行备份时(Get-WBSummary
>),它会输出以下错误:
术语“Get-WBSummary”未被识别为 cmdlet、函数、脚本文件或可操作程序的名称。检查名称的拼写,或者如果包含路径,请验证路径是否正确,然后重试。
但是,当我将命令直接放入 PowerShell 中时,它会执行该命令。我已经尝试添加 SnapIn 但这不起作用。
我在这里做错了什么?
Here is the code:
static String checkBackUp()
{
Runspace runspace = RunspaceFactory.CreateRunspace();
runspace.Open();
Pipeline pipeline = runspace.CreatePipeline();
pipeline.Commands.Add("Get-WBSummary");
pipeline.Commands.Add("Out-String");
Collection<PSObject> results = new Collection<PSObject>();
try
{
results = pipeline.Invoke();
}
catch (Exception ex)
{
results.Add(new PSObject((object)ex.Message));
}
runspace.Close();
StringBuilder stringBuilder = new StringBuilder();
foreach (PSObject obj in results)
{
stringBuilder.AppendLine(obj.ToString());
}
return stringBuilder.ToString();
}
The problem is that this runs every cmdlet (like Get-Process
for example) but when I try to verify if a backup has been made (Get-WBSummary
), it spits out the following error:
The term 'Get-WBSummary' 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.
However when I put the command straight into PowerShell, it executes the command. I have already tried to add a SnapIn but this did not work.
What am I doing wrong here?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
Get-WBSummary
不是常规的内置 Powershell cmdlet。 初始化运行空间后,您需要执行
Add-PSSnapin Windows.ServerBackup
操作。在代码中的某个时刻
Get-WBSummary
isn't a regular built-in Powershell cmdlet. You'll need to doAdd-PSSnapin Windows.ServerBackup
at some point in your code after the runspace is initialised.
您必须创建初始会话状态并添加管理单元。以下是具体操作方法
You'll have to create an initial session state and add the snapin. Here is how to do it