Powershell 参数 $args[0] 带引号
Powershell parameter $args[0] with quotes
我正在 运行从将文件名作为第一个参数传递的批处理中调用 PowerShell 脚本。
在我使用的脚本中:
$file = Get-Item -LiteralPath $args[0]
但是当文件名包含引号(即:my'file.txt
)时,get-item
会触发错误。我试图删除 -LiteralPath
参数,但问题是一样的。
脚本的语法是
$file = 获取项目 -LiteralPath $args[0]
写主机 $file
cmd /c 暂停
如果我 运行 针对我的脚本'file.txt 我得到:
- C:\m\tag\testscript.ps1 'C:\m\tag\my'file.txt' <<<<
- 类别信息:解析器错误:(:字符串)[],ParentContainsErrorRecordException
- FullyQualifiedErrorId : TerminatorExpectedAtEndOfString
你是如何传递参数的?
这个有效:
.{gi -literalpath $args[0]} "my'file.txt"
我认为可能在 PowerShell 看到文件名 cmd 时已经去掉了所有双引号,因此 PowerShell 将单独的单引号视为解析错误。尝试像这样指定文件名
my''file.txt
假设您在文件批处理中以这种方式传递路径:
powershell.exe C:\path\myscript.ps1 "%1%"
您需要转义引号:
powershell.exe C:\path\myscript.ps1 \"%1%\"
我正在 运行从将文件名作为第一个参数传递的批处理中调用 PowerShell 脚本。 在我使用的脚本中:
$file = Get-Item -LiteralPath $args[0]
但是当文件名包含引号(即:my'file.txt
)时,get-item
会触发错误。我试图删除 -LiteralPath
参数,但问题是一样的。
脚本的语法是
$file = 获取项目 -LiteralPath $args[0] 写主机 $file cmd /c 暂停
如果我 运行 针对我的脚本'file.txt 我得到:
- C:\m\tag\testscript.ps1 'C:\m\tag\my'file.txt' <<<<
- 类别信息:解析器错误:(:字符串)[],ParentContainsErrorRecordException
- FullyQualifiedErrorId : TerminatorExpectedAtEndOfString
你是如何传递参数的?
这个有效:
.{gi -literalpath $args[0]} "my'file.txt"
我认为可能在 PowerShell 看到文件名 cmd 时已经去掉了所有双引号,因此 PowerShell 将单独的单引号视为解析错误。尝试像这样指定文件名
my''file.txt
假设您在文件批处理中以这种方式传递路径:
powershell.exe C:\path\myscript.ps1 "%1%"
您需要转义引号:
powershell.exe C:\path\myscript.ps1 \"%1%\"