简体   繁体   English

CMD中单引号和双引号的区别

[英]Differences between single and double quotes in CMD

I have a powershell file that replaces an IP in a config file.我有一个 powershell 文件,它替换了配置文件中的 IP。 The powershell takes in three parameters: powershell 接受三个参数:

  1. file name ( 'C:\Program Files (x86)\app\app.conf' )文件名( 'C:\Program Files (x86)\app\app.conf'
  2. IP to replace IP 替换
  3. new IP新 IP

Since we are dependent on using a batch file for our service to process the task, I wrote a batch script that simply takes three parameters and posts that to the powershell script.由于我们的服务依赖于使用批处理文件来处理任务,因此我编写了一个批处理脚本,它只需要三个参数并将其发布到 powershell 脚本。

We use batch file for calling and parsing the parameter: ($ just used to represent variables)我们使用批处理文件来调用和解析参数: ($只是用来表示变量)

changeip.bat '$filepath' $oldip $newip

This fails, but I don't understand why.这失败了,但我不明白为什么。 I've tried using double quotes instead of single quotes around $filepath and it worked.我尝试在$filepath周围使用双引号而不是单引号并且它有效。

How can the whitespace in $filepath be understood by double quotes and not single quotes? $filepath中的空格如何用双引号而不是单引号来理解?

The short answer is that CMD doesn't treat single quotes as anything but a regular character.简短的回答是CMD 不会将单引号视为常规字符。 It's not a pair/group like double quotes.它不是像双引号那样的一对/组。

The only place where the single quote has any special meaning is in a FOR /F loop, where you are specifying a command to run and iterate over the output.单引号具有任何特殊含义的唯一位置是在FOR /F循环中,您在其中指定要运行和迭代 output 的命令。

FOR /F %%d IN ('DIR /S /B C:\Windows') DO @ECHO File: %%d

FOR /F has an option to use backticks instead, in case you need to pass single quotes to the called process, but this is unrelated to your question. FOR /F可以选择使用反引号,以防您需要将单引号传递给被调用的进程,但这与您的问题无关。

I assume you are calling the batch file and its variables in powershell.我假设您正在 powershell 中调用批处理文件及其变量。 The single quotation pretty much denotes an as is state for the text between them and doesn't expand it to a variable, where as the double quotes expand the variable and wrap the text into a single string.单引号几乎表示它们之间的文本的原样 state 并且不会将其扩展为变量,而双引号会扩展变量并将文本包装成单个字符串。

EG.例如。

$Hostname = "Computer Name"
Get-WmiObject Win32_computersystem -ComputerName '$Hostname'

This will try and search for a computer called $Hostname这将尝试搜索名为 $Hostname 的计算机

$Hostname = "Computer Name"
Get-WmiObject Win32_computersystem -ComputerName "$Hostname"

This will try and search for a computer called "Computer Name"这将尝试搜索名为“计算机名”的计算机

This is a poor example as you don't need the quotations for either of these, but you get the idea.这是一个糟糕的示例,因为您不需要其中任何一个的引用,但您明白了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM