批量使用 PowerShell 命令的问题

2024-03-04

我使用 PowerShell 命令从云下载 zip 文件。 该命令在 PowerShell 和命令行中都能正常工作。但是,如果我将命令行中的命令插入批处理脚本中,则只会下载 html。 为什么该命令在命令行中可以正常工作,但在批处理文件中却不能? 我没有主意了:D

powershell Invoke-WebRequest """https://sync.luckycloud.de/d/fb56e4a8239a4c6cac7a/files/?p=%2FValheimServer%20Buddelkiste%20Modpack%20v3.4%20-%20Standart.zip&dl=1""" -OutFile """C:\Users\Anonymos\Downloads\servermodpack.zip"""

它在 cmd 中工作正常并加载 ~40 Mb。但在 Batch 中它只加载 9kb(它是 Html)


In a batch file - as opposed to the interactive cmd.exe command prompt[1] - you need to to escape % chars. as %% in order to pass them through literally:

powershell -c "Invoke-WebRequest 'https://sync.luckycloud.de/d/fb56e4a8239a4c6cac7a/files/?p=%%2FValheimServer%%20Buddelkiste%%20Modpack%%20v3.4%%20-%%20Standart.zip&dl=1' -OutFile C:\Users\Anonymos\Downloads\servermodpack.zip"

Note:

  • 我用过-c (-Command), the 位置上默示Windows PowerShell CLI (powershell.exe https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_powershell_exe)为了概念清晰而明确参数(在PowerShell(核心)7+,其 CLI 是pwsh https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_pwsh,默认为现在-f (-File)).

  • 另外,附上整个命令行传递到 PowerShell 中"..."通常最好是为了防止cmd.exe元字符other than %(例如&)以免引起问题。

    • 如果命令行需要使用embedded "字符(上面的解决方案通过使用嵌入来避免这种情况'...'引用),逃避它们的最安全的方法是使用"^""(原文如此)与powershell.exe, and "" with pwsh.exe - see 这个答案 https://stackoverflow.com/a/49060341/45375了解详情。

[1] In interactive use, % characters cannot technically be escaped, but they're retained as-is unless they're part of a cmd.exe-style environment-variable reference that refers to an existing environment variable, such as %OS%. However, there are ways to treat % literally even in such cases, as discussed in this answer https://stackoverflow.com/a/33026344/45375. These techniques are important for invoking cmd.exe command lines programmatically from outside cmd.exe, such as from Node.Js or Python, because such programmatic invocations - perhaps surprisingly - use the rules of interactive cmd.exe sessions, not batch files.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

批量使用 PowerShell 命令的问题 的相关文章

随机推荐