【问题标题】:Run PowerShell Unzip commands through C# Process.Start()通过 C# Process.Start() 运行 PowerShell Unzip 命令
【发布时间】:2017-08-12 01:13:24
【问题描述】:

我想使用 PowerShell 和 C# 将下载文件夹中的 zip 文件解压缩到桌面。

我需要它与 Windows 7、8 和 10 一起使用。


我正在尝试使用这些 PowerShell 命令

 

$shell = New-Object -ComObject shell.application
$zip = $shell.NameSpace("zip file path")
foreach ($item in $zip.items()) {
    $shell.Namespace("unzip destination path").CopyHere($item)
}

并通过 C# Process.Start() 运行它

Process.Start("powershell.exe",
    "timeout 3; "
    + "$shell = New-Object -ComObject shell.application; "
    + "$zip = $shell.NameSpace(\"C:\\Users\\Matt\\Downloads\\MyFile.zip\"); "
    + "foreach ($item in $zip.items()) {$shell.Namespace(\"C:\\Users\\Matt\\Desktop\\\").CopyHere($item, 0x14)}"
);

问题

PowerShell 启动但无法提取,并在我读取错误之前关闭。

但是,如果我将这些链接的命令复制粘贴到没有 C# 的 PowerShell 中,它就可以工作。

$shell = New-Object -ComObject shell.application; $zip = $shell.NameSpace('C:\Users\Matt\Downloads\MyFile.zip'); foreach ($item in $zip.items()) {$shell.Namespace('C:\Users\Matt\Desktop\').CopyHere($item, 0x14)}

这可行,但仅适用于 PowerShell 5。

Process.Start("powershell.exe",
    "timeout 3; Expand-Archive 'C:\\Users\\Matt\\Downloads\\MyFile.zip' -Force -DestinationPath 'C:\\Users\\Matt\\Desktop\\'"
);

【问题讨论】:

    标签: c# powershell


    【解决方案1】:

    我可能在写出问题并重构其他链式命令时解决了它。

    我找到了这篇文章并将其与其他代码结合起来。
    https://www.howtogeek.com/tips/how-to-extract-zip-files-using-powershell/

    Process.Start("powershell.exe",
        "-nologo -noprofile -command "
        + "timeout 3; "
        + "$shell = new-object -com shell.application; "
        + "$zip = $shell.NameSpace('C:\\Users\\Matt\\Downloads\\MyFile.zip'); "
        + "foreach ($item in $zip.items()) {$shell.Namespace('C:\\Users\\Matt\\Desktop\\').CopyHere($item, 0x14)}"
    );
    

    区别在于:

    添加-nologo -noprofile -command
    -com 而不是-ComObject
    单引号 ' 而不是双引号 " 在路径周围。
    并使用Write-Host \"hello\" -NoNewLine 而不是echo 链接消息。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-12-05
      相关资源
      最近更新 更多