Joh*_*mer 7 powershell batch-file
我有一个DOS批处理文件,其中有一行执行powershell脚本.首先,我在批处理文件中尝试了一个非常简单的脚本:
powershell -command "get-date" < nul
Run Code Online (Sandbox Code Playgroud)
这很有效.但该脚本嵌套了双引号字符,有时可以使用反引号(`)字符进行转义.那么我试过这个:
powershell -command "Write-Host `"hello world`"" < nul
Run Code Online (Sandbox Code Playgroud)
这也很有效.但是,我需要运行的脚本非常复杂,并且具有多个级别的嵌套双引号字符.我已经采用了复杂的脚本并将其简化为具有相同原理的示例:
[string]$Source = " `"hello world`" ";
Write-Host $Source;
Run Code Online (Sandbox Code Playgroud)
如果我将此脚本保存在PS脚本文件中并运行它,它工作正常,打印出"hello world",包括双引号,但我需要将它嵌入批处理文件中的行中.所以我把脚本放在一行上,并尝试将其插入批处理文件行,但它不起作用.我试图逃避双引号,但它仍然不起作用,像这样:
powershell -command "[string]$Source = `" `"hello world`" `";Write-Host $Source;" < nul
Run Code Online (Sandbox Code Playgroud)
有办法做我想要的吗?你可能会问为什么我这样做,但这是一个很长的故事,所以我不会详细介绍.谢谢
Som*_*ica 11
您必须使用批处理的转义字符和PowerShell的转义字符的组合.
在批处理中,当转义引号时,使用公共shell反斜杠(\)来转义这些引号.在Powershell中,你使用反引号`.
因此,如果您想使用批处理打印带有Powershell的带引号的字符串,您需要首先批量转义引号以在Powershell中声明变量,然后确保引用字符串您需要批处理并且Powershell转义另一个引号,然后您的添加您想要的字符串,确保您先批量转义.
对于您的示例,这将工作:
powershell -command "[string]$Source = \"`\"hello world`\"\"; Write-Host $Source;"
Run Code Online (Sandbox Code Playgroud)
这是$ Source变量声明的细分:
"[string]$Source = # open quote to begin -command parameter declaration
\" # batch escape to begin the string portion
`\" # Powershell+Batch escape
hello world # Your content
`\" # Posh+Batch again
\"; # Close out the batch and continue
more commands " # Close quote on -command parameter
Run Code Online (Sandbox Code Playgroud)
这将批量呈现这样的字符串:
`"hello world`"
Run Code Online (Sandbox Code Playgroud)
请注意,您不需要显式地转换$Source为字符串,因为您从头开始将其构建为文字字符串.
$Source = "string stuff" 将按预期工作.
| 归档时间: |
|
| 查看次数: |
9452 次 |
| 最近记录: |