PowerShell脚本问题
问题描述:
下面是代码: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
),它吐出出现以下错误:
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.
但是,当我将命令直接放入PowerShell中时,它会执行该命令。我已经尝试添加一个管理单元,但这不起作用。
我在这里做错了什么?
答
Get-WBSummary
不是常规的内置Powershell cmdlet。你需要做的
Add-PSSnapin Windows.ServerBackup
在代码中的某个点的运行空间被初始化后。
答
您必须创建初始会话状态并添加管理单元。这里是如何做到这一点
initialSession = InitialSessionState.CreateDefault();
initialSession.ImportPSModule(new[] {"Path\to\module\here"});
就像我说我的问题,我没有:),它并没有帮助。我有这样的: 流水线pipeline = runspace.CreatePipeline(); (“Add-Pssnapin”Windows.serverbackup“); 命令addSnapin =新命令(”Add-PSSnapin“); addSnapin.Parameters.Add(”Name“,”Windows.serverbackup“); pipeline.Commands.Add pipeline.Commands.Add(addSnapin); –