我正在使用C#处理程序来清理Windows 10开始菜单并分配自定义布局。为此,我需要从powershell运行一个命令,并在运行时遇到错误。
我是如何完成任务的。
我正在启动C:\。\。\ powershell.exe并传递-command参数:Import-StartLayout -LayoutPath C:\ StartMenu.xml -MountPath C:\
Process process = new Process();
process.StartInfo.FileName = @"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe";
process.StartInfo.Arguments = @" -command Import-StartLayout -LayoutPath C:\StartMenu.xml -MountPath C:\";
process.Start();
以下是我收到的错误:
Import-StartLayout : The term 'Import-StartLayout' 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.
At line:1 char:1
+ Import-StartLayout -LayoutPath C:\StartMenu.xml -MountPath C:\; Start ...
+ ~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (Import-StartLayout:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
为什么cmd或powershell不会使用Import-StartLayout的外部cmdlet?
答案 0 :(得分:-1)
Import-StartLayout
,如果您知道,请继续
您可以尝试使用System.Diagnostics.Process
,如下所示:
Process powerShell = new Process()
{
StartInfo =
{
Arguments = "Import-StartLayout -LayoutPath C:\\StartMenu.xml -MountPath C:\\",
FileName = "powershell"
}
};
powerShell.Start();
另一种方法是使用System.Management.Automation
,这不是Microsoft官方支持的软件包。
using (Runspace runSpace = RunspaceFactory.CreateRunspace())
{
runSpace.Open();
using (Pipeline pipeline = runSpace.CreatePipeline())
{
Command importStartLayout = new Command("Import-StartLayout");
importStartLayout.Parameters.Add("LayoutPath", "C:\\StartMenu.xml");
importStartLayout.Parameters.Add("MountPath", "C:\\");
pipeline.Commands.Add(importStartLayout);
Collection<PSObject> resultsObjects = pipeline.Invoke();
StringBuilder resultString = new StringBuilder();
foreach (PSObject obj in resultsObjects)
{
resultString.AppendLine(obj.ToString());
}
}
}