You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在C# WPF应用中调用PowerShell压缩文件夹遇模块加载错误求助

解决C# WPF调用PowerShell压缩文件夹的模块加载错误及WinZip进度UI需求

一、解决Microsoft.PowerShell.Archive模块加载失败问题

1. 手动导入指定模块路径

非交互式PowerShell环境(如C#调用)可能无法自动加载模块,需手动指定模块的.psd1文件路径:

  • 先找到模块的安装路径,Windows PowerShell 5.1默认路径示例:C:\Program Files\WindowsPowerShell\Modules\Microsoft.PowerShell.Archive\1.2.5.0\Microsoft.PowerShell.Archive.psd1(版本号可能不同,以实际为准)
  • 修改PowerShell脚本,先执行导入命令:
$modulePath = "C:\Program Files\WindowsPowerShell\Modules\Microsoft.PowerShell.Archive\1.2.5.0\Microsoft.PowerShell.Archive.psd1"
Import-Module $modulePath -Force
$Target = 'C:\Users\user\Downloads\Test.zip'
$Source = 'C:\Users\user\Downloads\temp'
Compress-Archive -Path $Source -DestinationPath $Target -Force

2. 检查并调整PowerShell执行策略

如果当前用户执行策略为Restricted,会阻止模块加载,可在C#中临时设置:

using (PowerShell ps = PowerShell.Create())
{
    // 设置当前用户执行策略为RemoteSigned(避免模块加载被阻止)
    ps.AddCommand("Set-ExecutionPolicy")
      .AddArgument("RemoteSigned")
      .AddParameter("Scope", "CurrentUser")
      .AddParameter("Force");
    ps.Invoke();
    ps.Commands.Clear();

    // 执行压缩脚本
    ps.AddScript(psScript);
    var results = ps.Invoke();

    // 处理错误信息
    if (ps.HadErrors)
    {
        foreach (var error in ps.Streams.Error)
        {
            // 此处可将错误日志输出到WPF界面或日志文件
            Console.WriteLine(error.ToString());
        }
    }
}

二、实现WinZip进度UI展示

Compress-Archive是Windows自带的PowerShell命令,与WinZip无关联,无法触发WinZip的进度UI。需直接调用WinZip的命令行工具:

1. 调用WinZip命令行工具(推荐直接用Process,无需PowerShell)

var processStartInfo = new ProcessStartInfo
{
    FileName = @"C:\Program Files\WinZip\wzzip.exe", // WinZip命令行工具路径,以实际安装为准
    // 参数说明:-ui 显示进度UI;-s 静默模式(可根据需求调整);最后是目标压缩包和源文件路径
    Arguments = "-ui -s \"C:\\Users\\user\\Downloads\\Test.zip\" \"C:\\Users\\user\\Downloads\\temp\\*\"",
    UseShellExecute = true, // 确保能启动WinZip的可视化界面
    WindowStyle = ProcessWindowStyle.Normal
};
Process.Start(processStartInfo);

2. 若通过PowerShell调用WinZip命令行

$winZipPath = "C:\Program Files\WinZip\wzzip.exe"
$targetZip = "C:\Users\user\Downloads\Test.zip"
$sourceFiles = "C:\Users\user\Downloads\temp\*"
& $winZipPath -ui -s $targetZip $sourceFiles

注意事项

  • 路径中包含空格时需用双引号包裹,避免解析错误
  • 确保应用运行用户拥有源文件夹、目标路径及WinZip目录的读写权限
  • 64位应用需调用对应位数的PowerShell/WinZip工具(如64位PowerShell路径为C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe)

内容的提问来源于stack exchange,提问作者mdb

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.19 19:14:51