【问题标题】:Powershell Error when Running process运行进程时出现Powershell错误
【发布时间】:2017-08-05 00:18:42
【问题描述】:

我正在使用 C# 编写程序来清理 Windows 10 开始菜单并分配自定义布局。为此,我需要从 powershell 运行一个命令,并且在运行它时出现错误。

我是如何尝试完成任务的。

我正在启动 C:\.\.\powershell.exe 并传递以下命令参数: 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??

【问题讨论】:

  • 测试电脑是哪个版本的windows
  • 从 PowerShell CLI 界面运行 PS 脚本是否有效?
  • "我是如何完成任务的" - 那一点在哪里?你是如何运行 PowerShell 的?
  • @zwork 确实如此。我在 Visual Studio 中调试时运行脚本,它运行时没有错误。当我在 10 的干净版本上构建并运行它时,它会中断。
  • @TessellatingHeckler 抱歉,已添加到帖子中。我正在使用 Process process = new Process();调用文件以运行并传入参数。

标签: c# windows powershell


【解决方案1】:

Import-StartLayout 在 Windows 7 及更早版本上不存在,如果您知道,请继续。
您可以尝试使用System.Diagnostics.Process,如下所示:

Process powerShell = new Process()
{
    StartInfo =
    {
        Arguments = "Import-StartLayout -LayoutPath C:\\StartMenu.xml -MountPath C:\\",
        FileName = "powershell"
    }
};
powerShell.Start();

另一种方法是使用System.Management.Automation,它不是微软官方支持的软件包。

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());
        }
    }
}

【讨论】:

  • /C 或 /K 不起作用,因为它是 Powershell 命令而不是 CMD 命令。
猜你喜欢
  • 2020-08-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-08-27
  • 1970-01-01
  • 1970-01-01
  • 2022-10-23
相关资源
最近更新 更多