Powershell脚本,其中的路径在字符串中带有方括号

问题描述

我无法将Powershell脚本用于带有方括号的路径。

输入路径为“ c:\ temp \ yeah [就这样]”

param (  
    [string]$folderPath = $env:folderPath
 )
$folderPath = $folderPath + "\"

    Add-Content -Path $folderPath"01-playlist.m3u" -Value "a file name.mp3"

我查看了'-literalpath'和'Convert-path',但看不到如何在我的代码中实现。

解决方法

只需使用-LiteralPath而不是-Path

Add-Content -LiteralPath "D:\Test\yeah [thats it]\01-playlist.m3u" -Value "a file name.mp3"

现在该路径是按原义使用的,因此您不能像使用Path那样使用通配符。

顺便说一句,您的可选参数看起来很奇怪。除非您为它设置了环境变量,否则不会出现$env:folderPath

此外,要组合路径和文件名,有一个名为Join-Path的cmdlet。使用它比使用$folderPath + "\"这样的构造要好得多,在这种构造中,忘记反斜杠或添加太多的反斜杠非常容易。

我会写

$file = Join-Path -Path $folderPath -ChildPath '01-playlist.m3u'
Add-Content -LiteralPath $file -Value "a file name.mp3"
,

我认为您需要使用反引号。如果您是从外壳执行此操作 SELECT hire_date,COUNT(hire_date) FROM employees GROUP BY hire_date; 请注意,如果用单引号引起来,则倒勾的数量将变为两个。

查看此答案:https://superuser.com/questions/212808/powershell-bug-in-copy-move-rename-when-filename-contains-square-bracket-charac#:~:text=Getting%20PowerShell%20to%20correctly%20recognize,four%20backticks%20to%20escape%20it