如何在批处理文件中实现字符串与变量拼接?示例代码求助
Hey there! Let's sort out that string concatenation issue in your batch file. The key mistake here is that batch scripting doesn't use the + operator for string joining — you just need to place the string and variable directly next to each other.
Why Your Original Code Failed
Your current script:
@echo off set FileNameAndPCName="Locker\" + "%COMPUTERNAME%" echo %FileNameAndPCName% pause
This will output exactly "Locker\" + "%COMPUTERNAME%" instead of the concatenated value, because batch treats the + sign and extra quotes as literal parts of the string.
Correct Implementation
Here's the fixed version that gives you the desired format like Locker/Bill (or Locker\Bill if you prefer backslashes — just adjust the separator):
@echo off set "FileNameAndPCName=Locker/%COMPUTERNAME%" echo %FileNameAndPCName% pause
Breakdown of the Fix:
- No
+operator needed: Simply append%COMPUTERNAME%directly to your base stringLocker/. - Quoting best practice: Using
set "var=value"(quotes around the entire assignment) prevents accidental trailing spaces and correctly handles values with spaces. If you want the final output to include quotes around the whole string, adjust it like this:
This will output@echo off set "FileNameAndPCName="Locker/%COMPUTERNAME%"" echo %FileNameAndPCName% pause"Locker/Bill"instead ofLocker/Bill.
Bonus: Step-by-Step Concatenation
If you want to build the value in separate steps (e.g., reusing the base path elsewhere), you can do this:
@echo off set "BaseDir=Locker/" set "FileNameAndPCName=%BaseDir%%COMPUTERNAME%" echo %FileNameAndPCName% pause
内容的提问来源于stack exchange,提问作者A random Guy

