C# 运行进程时出现Powershell错误
我正在用C#编写一个程序来清理windows 10的“开始”菜单并指定自定义布局。为此,我需要从powershell运行一个命令,并且在运行该命令时出错 我是如何努力完成这项任务的 我正在启动C:\.\.\powershell.exe并传递以下命令的-command参数:Import startayout-LayoutPath C:\StartMenu.xml-MountPath C:\C# 运行进程时出现Powershell错误,c#,windows,powershell,C#,Windows,Powershell,我正在用C#编写一个程序来清理windows 10的“开始”菜单并指定自定义布局。为此,我需要从powershell运行一个命令,并且在运行该命令时出错 我是如何努力完成这项任务的 我正在启动C:\.\.\powershell.exe并传递以下命令的-command参数:Import startayout-LayoutPath C:\StartMenu.xml-MountPath C:\ Process process = new Process(); process.StartInfo.Fil
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 StartAyout的外部cmdlet的想法???
Import StartAyout
在windows 7及更早版本上不存在,如果您知道,请继续。您可以尝试使用
System.Diagnostics.Process
,如下所示:
Process powerShell = new Process()
{
StartInfo =
{
Arguments = "Import-StartLayout -LayoutPath C:\\StartMenu.xml -MountPath C:\\",
FileName = "powershell"
}
};
powerShell.Start();
另一种方法是使用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());
}
}
}
使用(Runspace Runspace=RunspaceFactory.CreateRunspace())
{
Open();
使用(Pipeline Pipeline=runSpace.CreatePipeline())
{
命令importStartLayout=新命令(“导入布局”);
importStartLayout.Parameters.Add(“LayoutPath”,“C:\\StartMenu.xml”);
importStartLayout.Parameters.Add(“MountPath”,“C:\\”);
pipeline.Commands.Add(importStartLayout);
集合resultsObjects=pipeline.Invoke();
StringBuilder resultString=新建StringBuilder();
foreach(resultsObjects中的PSObject对象)
{
结果字符串AppendLine(obj.ToString());
}
}
}
从PowerShell CLI界面运行PS脚本时,测试的PC是哪个版本的windows?“我是如何完成任务的”-这一点在哪里?你是如何运行PowerShell的?@zwork确实如此。我在VisualStudio中调试时运行脚本,它运行时没有错误。当我在10个干净的版本上构建并运行它时,它会中断。@TessellingHeckler抱歉,它已添加到帖子中。我正在使用流程=新流程();调用文件以运行并传入参数。/C或/K不起作用,因为它是Powershell命令而不是CMD命令。