如何在url中使用Invoke-Webrequest与一些括号?



我遇到了Powershell的Invoke-Webrequest功能的问题。我知道如何使用它,但有些文件有一个括号在它的文件名。这是.ps1文件的代码:

Invoke-Webrequest http://FreeZipFiles.com/FreeZipFile.zip -Outfile C:UsersMyUserNameDesktoptest.zip

注意FreeZipFiles.com是虚构的当我运行代码时,我得到这个错误:

FREE! : The term 'FREE!' 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:76
+ ...  http://FreeZipFiles.com/FreeZipFile (FREE!). ...
+                                                               ~~~
+ CategoryInfo          : ObjectNotFound: (FREE!:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException

看了这个之后,我意识到括号表示"这是一个命令,运行它",但它不是!无论如何,提前感谢!

您的示例代码显示您的URL为http://FreeZipFiles.com/FreeZipFile.zip,但基于您的示例错误消息,我怀疑您已经遗漏了重要的部分,即URL中有一个空格,如http://FreeZipFiles.com/FreeZipFile.zip (FREE!)

在这种情况下,您应该确保引用URL:

Invoke-WebRequest 'http://FreeZipFiles.com/FreeZipFile.zip (FREE!)' -Outfile C:UsersMyUserNameDesktoptest.zip

第一种方法失败的原因是用作参数的未引号值被解释为字符串,但是由于空格分隔了参数和参数,因此必须注意确保空格被正确处理。通常这是通过引号来完成的。

也可以使用双引号,但是双引号可以展开某些特殊字符。例如,如果您这样做:

Invoke-Webrequest "http://FreeZipFiles.com/$HOST/FreeZipFile.zip" -Outfile C:UsersMyUserNameDesktoptest.zip

您可能会惊讶地发现,$HOST最终将采用PowerShell中$Host变量的值,而不是从字面上取值。单引号不能这样解释变量

从技术上讲,你可以用`(PowerShell中的转义字符)转义空格,但是你也必须转义括号本身:

Invoke-Webrequest http://FreeZipFiles.com/FreeZipFile.zip` `(FREE!`) -Outfile C:UsersMyUserNameDesktoptest.zip

很明显,这是不理想的,我添加它更多的是出于好奇。

最新更新