从批处理文件中的变量中删除双引号会导致 CMD 环境出现问题

发布于 2024-08-16 06:44:25 字数 7300 浏览 5 评论 0原文

任何人都可以提供从批处理变量中删除引号的有效且安全的方法吗?

我编写了一个批处理文件,它成功导入了参数 %1、%2、%3 等的列表,并将它们放入命名变量中。其中一些参数包含多个单词,因此用双引号引起来。

> "Susie Jo" (%1)  
> "Smith Barnes" (%2)  
> "123 E. Main St." (%3)  

这些%variables 接下来被放置在命名变量中:

> set FirstName=%1  
> set LastName=%2  
> set ShipAddr=%3  

变量的验证是通过echo 完成的。 >回声。%FirstName%
> echo.%LastName%
> echo.%ShipAddr%

结果显示,因为

"Susie Jo"  
"Smith Barnes"  
"123 E. Main St."  

我需要消除所选变量上包含的引号。例如,FirstName 和 LastName 在其他地方使用,并且不得包含引号。

在测试批处理文件中,我成功地使用变量中的 ~tilde 字符消除了引号。

> set FirstName=%~1
> set LastName=%~2 

我以为我已经找到了解决方案,但很快我就在执行批处理文件时遇到了异常行为。突然 CMD 无法识别长路径语句。从完整路径正常执行批处理文件

> C:\Documents and Settings\Administrator\My Documents\Txt\batchtest\dataout.bat

会返回

> 'C:\Documents' is not recognized as an internal or external command....

因此,将 ~tilde 字符添加到传入的 %1 %2...%n 变量似乎导致了一些变化。可能某些环境变量已被更改?

我还尝试使用 FOR 命令进行各种尝试来清除变量内的引号。这看起来很尴尬,我一直无法学习如何通过创建变量列表来执行任务来完成此任务:

像这样:

for %%g in (%FirstName% %LastName%) do (
set %%g=%%~g
set %%h=%%~h
set FirstName=%%~g
set LastName=%%h
echo.%FirstName% %LastName%
)

我认为我有两个问题。

  1. 我在传入的 %1 %2 变量(%~1 等)中插入 ~tilde 的“简短而甜蜜”的想法似乎影响了一些设置并改变了 CMD 导航长路径名的方式。

  2. 我仍在寻找一种干净、简单的方法来消除所选命名变量中的引号。

对于那些更有经验的人的任何帮助将不胜感激。我的技能已经结束了...需要一些指导!

编辑 2009 年 12 月 26 日 13:36(太平洋标准时间) 整个批处理文件:

:: dataout.bat  
:: revision 12/25/2009 add ~tilde to incoming %variables to eliminate embedded "quotation marks.  
:: writes address list using command line parameters  
:: writes data output list for QBooks IIF import  
:: writes Merchant Order data for RUI  
:: sample command line string for testing  
:: listmail[firstname][lastname]["address string"]["city string"][state][zip][Order#][PurchDate][Regname]["FirstName LastName"][TransactionID][PaymentMethod][Total][ProductID][Qty][Price_Each][PackPrep] [Shipping] [CommissionPmt] [Invoice#]  
:: example: dataout Bellewinkle Moose "123 Green Forest Way" "Vancouver" WA 98664 1004968 05/25/2009 "Bellewinkle Moose" "Olive Oyl" 101738 "On Account" 20.67 FK-1P 1 8.95 3.00 1.39 239  
@echo off  
cls  
c:  
cd\  
cd documents and settings\administrator\my documents\txt\batchtest  
echo processing %1 %2  
:VARISET  
:: Convert %n command line parameters to string variables  
set ($FirstName)=%~1  
set ($LastName)=%~2  
set ($BillingAddress1)=%~3  
set ($BillingCity)=%~4  
set ($BillingState)=%~5  
set ($BillingPostal)=%~6  
set ($OrderNumber)=%~7  
set ($Purch_Date)=%~8  
set ($RegistrationName)=%~9  
shift  
set ($TransactionID)=%~9  
shift  
set ($PaymentMethod)=%~9  
shift  
set ($Total)=%~9  
shift
set ($ProductIdentifier)=%~9  
shift  
set ($Quantity)=%~9  
shift  
set ($Price_Each)=%~9  
shift  
set ($Pack_Prep)=%~9  
shift  
set ($Shipping)=%~9  
shift  
set ($ServiceFee)=%~9  
shift  
set ($Discount)=%~9  
shift  
set ($Invoice)=%~9  
shift  
set ($UnitPrice)=%~9  
set _ShipCombName=%($FirstName)% %($LastName)%  
echo ship combo name is %_ShipCombName%  
pause  
:: write string varibables to logfile  
echo FN %($FirstName)% LN %($LastName)% BA %($BillingAddress1)% %($BillingCity)% %($BillingState)% %($BillingPostal)% %($OrderNumber)% %($Purch_Date)% %($RegistrationName)% %($TransactionID)% %($PaymentMethod)% %($Total)% %($ProductIdentifier)% %($Quantity)% %($Price_Each)% %($Pack_Prep)% %($Shipping)% %($ServiceFee)% %($Discount)% %($Invoice)% %($UnitPrice)% %_ShipCombName% >> d_out_log.txt  
:: Assign Account by Service Provider  
IF /i %($PaymentMethod)%==Amazon Receivables SET _QBAcct=Amazon.com  
:: 12-25-2009 added second Amazon pm't method for versatility  
IF /i %($PaymentMethod)%==Amazon SET _QBAcct=Amazon.com  
IF /i %($PaymentMethod)%==MAST SET _QBAcct=Auth/Net  
IF /i %($PaymentMethod)%==MasterCard SET _QBAcct=Auth/Net  
IF /i %($PaymentMethod)%==Visa SET _QBAcct=Auth/Net  
IF /i %($PaymentMethod)%==PayPal SET _QBAcct=PayPalPmts  
IF /i %($PaymentMethod)%==On Account SET _QBAcct=%($RegistrationName)%  
IF /i %($PaymentMethod)%==Mail SET _QBAcct=%($RegistrationName)%  
IF /i %($PaymentMethod)%==AMER SET _QBAcct=Auth/Net  
IF /i %($PaymentMethod)%==DISC SET _QBAcct=Auth/Net  
:: Assign Rep designator based on QBAccount  
IF /i %($PaymentMethod)%==Amazon Receivables SET _Rep=Amazon  
:: 12-25-2009 added second Amazon pm't method for versatility  
IF /i %($PaymentMethod)%==Amazon SET _Rep=Amazon  
IF /i %($PaymentMethod)%==MAST SET _Rep=BlueZap  
IF /i %($PaymentMethod)%==MasterCard SET _Rep=BlueZap  
IF /i %($PaymentMethod)%==Visa SET _Rep=BlueZap  
IF /i %($PaymentMethod)%==PayPal SET _Rep=BlueZap  
IF /i %($PaymentMethod)%==On Account SET _Rep=R B  
IF /i %($PaymentMethod)%==Mail SET _Rep=R B  
IF /i %($PaymentMethod)%==AMER SET _Rep=BlueZap  
IF /i %($PaymentMethod)%==DISC SET _Rep=BlueZap  
:: check for duplicate address data  
findstr /i /s "%_ShipCombName%" addrlist.txt  
echo errorlevel: %errorlevel%  
if errorlevel 1 goto :ADDRWRITE  
if errorlevel 0 goto :ADDRFOUND  
:ADDRWRITE  
echo %_ShipCombName% >> addrlist.txt  
echo %($BillingAddress1)% >> addrlist.txt  
echo %($BillingCity)% %($BillingState)% %($BillingPostal)% >> addrlist.txt  
echo. >> addrlist.txt  
echo Address File Written  
:ADDRFOUND  
echo selected rep is %_Rep%  
echo selected account is: %_QBAcct%  
pause  
:: RUI OUT  
:: write Merchant Order ID & RUI Order ID to RUI  
:: check for duplicate RUI data in writeRUI.txt  
cd..  
cd RegKOut  
find /i "%($OrderNumber)%" writeRUI.txt  
echo errorlevel: %errorlevel%  
if errorlevel 1 goto :RUIWRITE  
if errorlevel 0 goto :IIFWRITE  
:RUIWRITE  
echo %($Invoice)%   %($OrderNumber)% >> writeRUI.txt  
:: end write RUI  
:: IIF OUT  
:IIFWRITE  
:: Check for duplicate invoice data in writeIIF.txt  
find /i "%($OrderNumber)%" writeIIF.txt  
echo errorlevel: %errorlevel%  
if errorlevel 1 goto :HEADWRITE  
if errorlevel 0 goto :LINEWRITE  
:HEADWRITE  
:: write Header, Ship/Handling, discount, Rep & commission data to QB IIF import file  
echo %($OrderNumber)%   %($Purch_Date)% Invoice %($TransactionID)%  %_QBAcct%   Accounts Receivable             %($Total)%  %_Rep% >> writeIIF.txt    
echo                        H/P %($Pack_Prep)%  1   ? >> writeIIF.txt  
echo                        SHP %($Shipping)%   1   ? >> writeIIF.txt  
echo                        DISC    %($Discount)%   1   ? >> writeIIF.txt  
echo                        Comm    %($ServiceFee)% 1   ? >> writeIIF.txt  
:LINEWRITE  
IF /i %($ProductIdentifier)% equ PH-1 goto WRITE_DEFA ELSE goto WRITE_DISC  
echo %($ProductIdentifier)%  
:WRITE_DISC  
::writes discounted prices parsed from custom variable:  
echo                        %($ProductIdentifier)%  %($Price_Each)% %($Quantity)%   ? >> writeIIF.txt  
goto :EOF  
:WRITE_DEFA  
:writes default prices parsed from Product data  
echo                        %($ProductIdentifier)%  %($UnitPrice)%  %($Quantity)%   ? >> writeIIF.txt  
goto :EOF  
:: 3-second delay  
:: TYPE NUL | CHOICE.COM /N /CY /TY,3 >NUL  
:EOF  

Can anybody help with effective and safe way of removing quotes from batch variables?

I have written a batch file which successfully imports a list of parameters %1, %2, %3 etc. and places them into named variables. Some of these parameters contain multiple words, and therefor are enclosed in double quotes.

> "Susie Jo" (%1)  
> "Smith Barnes" (%2)  
> "123 E. Main St." (%3)  

These %variables are next placed in named variables:

> set FirstName=%1  
> set LastName=%2  
> set ShipAddr=%3  

verification of variables is done by echo.
> echo.%FirstName%
> echo.%LastName%
> echo.%ShipAddr%

results display as

"Susie Jo"  
"Smith Barnes"  
"123 E. Main St."  

I need to eliminate the included quotes on selected variables. For instance, FirstName and LastName are used elsewhere and must not include quotes.

In a test batch file I was successful at eliminating quotes using the ~tilde character in variables.

> set FirstName=%~1
> set LastName=%~2 

I thought I had the solution, but I soon experienced unusual behavior with execution of batch files. Suddenly CMD is no recognizing long path statments. Normal execution of batch file from full path

> C:\Documents and Settings\Administrator\My Documents\Txt\batchtest\dataout.bat

returns

> 'C:\Documents' is not recognized as an internal or external command....

So it would appear that the addition of the ~tilde character to the in-coming %1 %2...%n variables has caused some change. Possibly some environment variables have been altered?

I also tried clearing quotes from within variable with various attempts using the FOR command. That seems awkward and I have been unable to learn how to accomplish this by creating a list of variable to perform the task:

something like this:

for %%g in (%FirstName% %LastName%) do (
set %%g=%%~g
set %%h=%%~h
set FirstName=%%~g
set LastName=%%h
echo.%FirstName% %LastName%
)

I think I have two issues.

  1. My 'short and sweet' idea of inserting ~tilde in the incoming %1 %2 variables (%~1, etc) seems to have affected some settings and altered how CMD navigates long pathnames.

  2. I'm still in search of a clean and easy way to eliminate quotes from selected named variables.

Any help for those more experienced would be most appreciated. I'm at the end of my skills here... need some guidance please!

edit 12/26/2009 13:36 PST
entire batch file:

:: dataout.bat  
:: revision 12/25/2009 add ~tilde to incoming %variables to eliminate embedded "quotation marks.  
:: writes address list using command line parameters  
:: writes data output list for QBooks IIF import  
:: writes Merchant Order data for RUI  
:: sample command line string for testing  
:: listmail[firstname][lastname]["address string"]["city string"][state][zip][Order#][PurchDate][Regname]["FirstName LastName"][TransactionID][PaymentMethod][Total][ProductID][Qty][Price_Each][PackPrep] [Shipping] [CommissionPmt] [Invoice#]  
:: example: dataout Bellewinkle Moose "123 Green Forest Way" "Vancouver" WA 98664 1004968 05/25/2009 "Bellewinkle Moose" "Olive Oyl" 101738 "On Account" 20.67 FK-1P 1 8.95 3.00 1.39 239  
@echo off  
cls  
c:  
cd\  
cd documents and settings\administrator\my documents\txt\batchtest  
echo processing %1 %2  
:VARISET  
:: Convert %n command line parameters to string variables  
set ($FirstName)=%~1  
set ($LastName)=%~2  
set ($BillingAddress1)=%~3  
set ($BillingCity)=%~4  
set ($BillingState)=%~5  
set ($BillingPostal)=%~6  
set ($OrderNumber)=%~7  
set ($Purch_Date)=%~8  
set ($RegistrationName)=%~9  
shift  
set ($TransactionID)=%~9  
shift  
set ($PaymentMethod)=%~9  
shift  
set ($Total)=%~9  
shift
set ($ProductIdentifier)=%~9  
shift  
set ($Quantity)=%~9  
shift  
set ($Price_Each)=%~9  
shift  
set ($Pack_Prep)=%~9  
shift  
set ($Shipping)=%~9  
shift  
set ($ServiceFee)=%~9  
shift  
set ($Discount)=%~9  
shift  
set ($Invoice)=%~9  
shift  
set ($UnitPrice)=%~9  
set _ShipCombName=%($FirstName)% %($LastName)%  
echo ship combo name is %_ShipCombName%  
pause  
:: write string varibables to logfile  
echo FN %($FirstName)% LN %($LastName)% BA %($BillingAddress1)% %($BillingCity)% %($BillingState)% %($BillingPostal)% %($OrderNumber)% %($Purch_Date)% %($RegistrationName)% %($TransactionID)% %($PaymentMethod)% %($Total)% %($ProductIdentifier)% %($Quantity)% %($Price_Each)% %($Pack_Prep)% %($Shipping)% %($ServiceFee)% %($Discount)% %($Invoice)% %($UnitPrice)% %_ShipCombName% >> d_out_log.txt  
:: Assign Account by Service Provider  
IF /i %($PaymentMethod)%==Amazon Receivables SET _QBAcct=Amazon.com  
:: 12-25-2009 added second Amazon pm't method for versatility  
IF /i %($PaymentMethod)%==Amazon SET _QBAcct=Amazon.com  
IF /i %($PaymentMethod)%==MAST SET _QBAcct=Auth/Net  
IF /i %($PaymentMethod)%==MasterCard SET _QBAcct=Auth/Net  
IF /i %($PaymentMethod)%==Visa SET _QBAcct=Auth/Net  
IF /i %($PaymentMethod)%==PayPal SET _QBAcct=PayPalPmts  
IF /i %($PaymentMethod)%==On Account SET _QBAcct=%($RegistrationName)%  
IF /i %($PaymentMethod)%==Mail SET _QBAcct=%($RegistrationName)%  
IF /i %($PaymentMethod)%==AMER SET _QBAcct=Auth/Net  
IF /i %($PaymentMethod)%==DISC SET _QBAcct=Auth/Net  
:: Assign Rep designator based on QBAccount  
IF /i %($PaymentMethod)%==Amazon Receivables SET _Rep=Amazon  
:: 12-25-2009 added second Amazon pm't method for versatility  
IF /i %($PaymentMethod)%==Amazon SET _Rep=Amazon  
IF /i %($PaymentMethod)%==MAST SET _Rep=BlueZap  
IF /i %($PaymentMethod)%==MasterCard SET _Rep=BlueZap  
IF /i %($PaymentMethod)%==Visa SET _Rep=BlueZap  
IF /i %($PaymentMethod)%==PayPal SET _Rep=BlueZap  
IF /i %($PaymentMethod)%==On Account SET _Rep=R B  
IF /i %($PaymentMethod)%==Mail SET _Rep=R B  
IF /i %($PaymentMethod)%==AMER SET _Rep=BlueZap  
IF /i %($PaymentMethod)%==DISC SET _Rep=BlueZap  
:: check for duplicate address data  
findstr /i /s "%_ShipCombName%" addrlist.txt  
echo errorlevel: %errorlevel%  
if errorlevel 1 goto :ADDRWRITE  
if errorlevel 0 goto :ADDRFOUND  
:ADDRWRITE  
echo %_ShipCombName% >> addrlist.txt  
echo %($BillingAddress1)% >> addrlist.txt  
echo %($BillingCity)% %($BillingState)% %($BillingPostal)% >> addrlist.txt  
echo. >> addrlist.txt  
echo Address File Written  
:ADDRFOUND  
echo selected rep is %_Rep%  
echo selected account is: %_QBAcct%  
pause  
:: RUI OUT  
:: write Merchant Order ID & RUI Order ID to RUI  
:: check for duplicate RUI data in writeRUI.txt  
cd..  
cd RegKOut  
find /i "%($OrderNumber)%" writeRUI.txt  
echo errorlevel: %errorlevel%  
if errorlevel 1 goto :RUIWRITE  
if errorlevel 0 goto :IIFWRITE  
:RUIWRITE  
echo %($Invoice)%   %($OrderNumber)% >> writeRUI.txt  
:: end write RUI  
:: IIF OUT  
:IIFWRITE  
:: Check for duplicate invoice data in writeIIF.txt  
find /i "%($OrderNumber)%" writeIIF.txt  
echo errorlevel: %errorlevel%  
if errorlevel 1 goto :HEADWRITE  
if errorlevel 0 goto :LINEWRITE  
:HEADWRITE  
:: write Header, Ship/Handling, discount, Rep & commission data to QB IIF import file  
echo %($OrderNumber)%   %($Purch_Date)% Invoice %($TransactionID)%  %_QBAcct%   Accounts Receivable             %($Total)%  %_Rep% >> writeIIF.txt    
echo                        H/P %($Pack_Prep)%  1   ? >> writeIIF.txt  
echo                        SHP %($Shipping)%   1   ? >> writeIIF.txt  
echo                        DISC    %($Discount)%   1   ? >> writeIIF.txt  
echo                        Comm    %($ServiceFee)% 1   ? >> writeIIF.txt  
:LINEWRITE  
IF /i %($ProductIdentifier)% equ PH-1 goto WRITE_DEFA ELSE goto WRITE_DISC  
echo %($ProductIdentifier)%  
:WRITE_DISC  
::writes discounted prices parsed from custom variable:  
echo                        %($ProductIdentifier)%  %($Price_Each)% %($Quantity)%   ? >> writeIIF.txt  
goto :EOF  
:WRITE_DEFA  
:writes default prices parsed from Product data  
echo                        %($ProductIdentifier)%  %($UnitPrice)%  %($Quantity)%   ? >> writeIIF.txt  
goto :EOF  
:: 3-second delay  
:: TYPE NUL | CHOICE.COM /N /CY /TY,3 >NUL  
:EOF  

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(12

挽袖吟 2024-08-23 06:44:25

末尾有一个额外的双引号,这会将其添加回字符串的末尾(从字符串中删除两个引号后)。

输入:

set widget="a very useful item"
set widget
set widget=%widget:"=%
set widget

输出:

widget="a very useful item"
widget=a very useful item

注意:要将双引号 " 替换为单引号 ',请执行以下操作:

set widget=%widget:"='%

注意:要将单词“World”(不区分大小写)替换为 BobB,请执行以下操作:

set widget="Hello World!"
set widget=%widget:world=BobB%
set widget

输出:

widget="Hello BobB!"

就您最初的问题而言(保存将以下代码写入批处理文件 .cmd 或 .bat 并运行):

@ECHO OFF
ECHO %0
SET BathFileAndPath=%~0
ECHO %BathFileAndPath%
ECHO "%BathFileAndPath%"
ECHO %~0
ECHO %0
PAUSE

输出:

"C:\Users\Test\Documents\Batch Files\Remove Quotes.cmd"
C:\Users\Test\Documents\Batch Files\Remove Quotes.cmd
"C:\Users\Test\Documents\Batch Files\Remove Quotes.cmd"
C:\Users\Test\Documents\Batch Files\Remove Quotes.cmd
"C:\Users\Test\Documents\Batch Files\Remove Quotes.cmd"
Press any key to continue . . .

%0 是脚本名称和路径。
%1 是第一个命令行参数,依此类推。

You have an extra double quote at the end, which is adding it back to the end of the string (after removing both quotes from the string).

Input:

set widget="a very useful item"
set widget
set widget=%widget:"=%
set widget

Output:

widget="a very useful item"
widget=a very useful item

Note: To replace Double Quotes " with Single Quotes ' do the following:

set widget=%widget:"='%

Note: To replace the word "World" (not case sensitive) with BobB do the following:

set widget="Hello World!"
set widget=%widget:world=BobB%
set widget

Output:

widget="Hello BobB!"

As far as your initial question goes (save the following code to a batch file .cmd or .bat and run):

@ECHO OFF
ECHO %0
SET BathFileAndPath=%~0
ECHO %BathFileAndPath%
ECHO "%BathFileAndPath%"
ECHO %~0
ECHO %0
PAUSE

Output:

"C:\Users\Test\Documents\Batch Files\Remove Quotes.cmd"
C:\Users\Test\Documents\Batch Files\Remove Quotes.cmd
"C:\Users\Test\Documents\Batch Files\Remove Quotes.cmd"
C:\Users\Test\Documents\Batch Files\Remove Quotes.cmd
"C:\Users\Test\Documents\Batch Files\Remove Quotes.cmd"
Press any key to continue . . .

%0 is the Script Name and Path.
%1 is the first command line argument, and so on.

带刺的爱情 2024-08-23 06:44:25

你的结论(1)听起来是错误的。一定还有其他因素在起作用。

批处理文件参数中的引号问题通常可以通过使用 %~ 删除引号,然后在适当的情况下手动将其放回去来解决。

例如:

set cmd=%~1
set params=%~2 %~3

"%cmd%" %params%

请注意 %cmd% 周围的引号。没有它们,带有空格的路径将无法工作。

如果您可以发布整个批处理代码,也许可以做出更具体的答案。

Your conclusion (1) sounds wrong. There must be some other factor at play.

The problem of quotes in batch file parameters is normally solved by removing the quotes with %~ and then putting them back manually where appropriate.

E.g.:

set cmd=%~1
set params=%~2 %~3

"%cmd%" %params%

Note the quotes around %cmd%. Without them, path with spaces won't work.

If you could post your entire batch code, maybe more specific answer could be made.

停滞 2024-08-23 06:44:25

我通常只是从变量中删除所有引号:

set var=%var:"=%

然后在需要的地方再次应用它们,例如:

echo "%var%"

I usually just remove all quotes from my variables with:

set var=%var:"=%

And then apply them again wherever I need them e.g.:

echo "%var%"
箜明 2024-08-23 06:44:25

花了很多时间尝试以简单的方式做到这一点。
仔细查看 FOR 循环后,我意识到只需一行代码即可完成此操作:

FOR /F "delims=" %%I IN (%Quoted%) DO SET Unquoted=%%I

示例:

@ECHO OFF
SET Quoted="Test string"

FOR /F "delims=" %%I IN (%Quoted%) DO SET Unquoted=%%I

ECHO %Quoted%
ECHO %Unquoted%

输出:

"Test string"
Test string

Spent a lot of time trying to do this in a simple way.
After looking at FOR loop carefully, I realized I can do this with just one line of code:

FOR /F "delims=" %%I IN (%Quoted%) DO SET Unquoted=%%I

Example:

@ECHO OFF
SET Quoted="Test string"

FOR /F "delims=" %%I IN (%Quoted%) DO SET Unquoted=%%I

ECHO %Quoted%
ECHO %Unquoted%

Output:

"Test string"
Test string
時窥 2024-08-23 06:44:25

简单的波形符语法仅适用于删除传递到批处理文件中的命令行参数周围的引号。

SET xyz=%~1

上面的批处理文件代码将把 xyz 设置为作为第一个参数传递的任何值,并删除前导和尾随引号(如果存在)。

但是,这种简单的波形符语法不适用于未作为参数传入的其他变量。

对于所有其他变量,您需要使用扩展替换语法,该语法要求您
指定要删除的前导和滞后字符。实际上,我们指示删除第一个和最后一个字符,而不查看它实际上是什么。

@SET SomeFileName="Some Quoted file name"
@echo %SomeFileName% %SomeFileName:~1,-1%

如果我们想在删除它之前检查第一个和最后一个字符实际上是引号,我们将需要一些额外的代码,如下所示

@SET VAR="Some Very Long Quoted String"
If aa%VAR:~0,1%%VAR:~-1%aa == aa""aa SET UNQUOTEDVAR=%VAR:~1,-1%

The simple tilde syntax works only for removing quotation marks around the command line parameters being passed into the batch files

SET xyz=%~1

Above batch file code will set xyz to whatever value is being passed as first paramter stripping away the leading and trailing quotations (if present).

But, This simple tilde syntax will not work for other variables that were not passed in as parameters

For all other variable, you need to use expanded substitution syntax that requires you to
specify leading and lagging characters to be removed. Effectively we are instructing to remove strip away the first and the last character without looking at what it actually is.

@SET SomeFileName="Some Quoted file name"
@echo %SomeFileName% %SomeFileName:~1,-1%

If we wanted to check what the first and last character was actually quotation before removing it, we will need some extra code as follows

@SET VAR="Some Very Long Quoted String"
If aa%VAR:~0,1%%VAR:~-1%aa == aa""aa SET UNQUOTEDVAR=%VAR:~1,-1%
匿名。 2024-08-23 06:44:25

我从这个链接中了解到,如果您使用的是XP或更高版本,那么这将简单地工作本身:

SET params = %~1

我无法在 Windows 7 上获得任何其他解决方案。

为了迭代它们,我这样做了:

FOR %%A IN (%params%) DO (    
   ECHO %%A    
)

注意:如果您这样做,您只会得到双引号传入的参数通常用空格分隔。

I learned from this link, if you are using XP or greater that this will simply work by itself:

SET params = %~1

I could not get any of the other solutions here to work on Windows 7.

To iterate over them, I did this:

FOR %%A IN (%params%) DO (    
   ECHO %%A    
)

Note: You will only get double quotes if you pass in arguments separated by a space typically.

情未る 2024-08-23 06:44:25

这听起来像是一个简单的错误,您在不应该使用的地方使用了 %~ 。使用 if %~ 并没有从根本上改变批处理文件的工作方式,它只是在这种情况下从字符串中删除引号。

This sounds like a simple bug where you are using %~ somewhere where you shouldn't be. The use if %~ doesn't fundamentally change the way batch files work, it just removes quotes from the string in that single situation.

饭团 2024-08-23 06:44:25

所有的答案都已完成。但想补充一件事,

设置名字=%~1

设置姓氏=%~2

此行应该有效,您需要进行一些小更改。

设置“名字=%~1”

设置“姓氏=%~2”

在引号内包含完整的分配。它将毫无问题地删除引号。这是一种首选的赋值方式,可以修复参数中引号引起的不必要的问题。

All the answers are complete. But Wanted to add one thing,

set FirstName=%~1

set LastName=%~2

This line should have worked, you needed a small change.

set "FirstName=%~1"

set "LastName=%~2"

Include the complete assignment within quotes. It will remove quotes without an issue. This is a prefered way of assignment which fixes unwanted issues with quotes in arguments.

此刻的回忆 2024-08-23 06:44:25

Azure devops 有时使用双引号字符 (") 来指定字符串。Powershell 可以使用单引号字符 (') 来指定字符串。自然我希望能够灵活地 我希望,因此可以从命令行 - 通过批处理文件以及作为 powershell 脚本,作为任何参数(包括空值)使用相同的参数,

自然的想法是写这样的内容:

build.bat:

@echo off
setlocal enabledelayedexpansion
set args=%*
set args=%args:"='%
echo powershell -executionpolicy bypass "%~dpn0.ps1" %args%
endlocal

能够指定参数,但是 你可以猜测 - 这不能立即生效 - 如果没有向批处理文件提供参数,那么 %* == 空字符串将扩展为无字符串,然后下一步。替换注意到 args 未设置 - 并且不是替换字符串 - 它会向 args 参数附加额外的 "=' 垃圾。

解决这个问题的方法就是在第一个分配中添加额外的空间。

build.bat:

@echo off
setlocal enabledelayedexpansion
set args=%*
set args=%args:"='%
echo powershell -executionpolicy bypass "%~dpn0.ps1" %args%
endlocal

此字符翻译后应该是正确的:

C:\test>build
powershell -executionpolicy bypass "C:\test.ps1"

C:\test>build aa
powershell -executionpolicy bypass "C:\test\build.ps1" aa

C:\test>build "aa"
powershell -executionpolicy bypass "C:\test\build.ps1" 'aa'

C:\test>build 'aa'
powershell -executionpolicy bypass "C:\test\build.ps1" 'aa'

Azure devops sometimes uses double quoting character (") to specify string. Powershell can use single quote character (') to specify string. Naturally I wanted to have a flexibility to be able to specify parameters however I wish, so same parameter can be used from both - command line - via batch file, and as a powershell script, as any parameter, including empty value.

Quote natural thinking is to write something like this:

build.bat:

@echo off
setlocal enabledelayedexpansion
set args=%*
set args=%args:"='%
echo powershell -executionpolicy bypass "%~dpn0.ps1" %args%
endlocal

But like you can guess - this does not work out of box - if no arguments are provided to batch file so %* == empty string. args expands as no string, and next replacement notices that args is not set - and instead of replacing string - it would append extra "=' garbage to args parameter.

Solution to this was just to add extra space in first assignment.

build.bat:

@echo off
setlocal enabledelayedexpansion
set args=%*
set args=%args:"='%
echo powershell -executionpolicy bypass "%~dpn0.ps1" %args%
endlocal

After this character translation should be correct:

C:\test>build
powershell -executionpolicy bypass "C:\test.ps1"

C:\test>build aa
powershell -executionpolicy bypass "C:\test\build.ps1" aa

C:\test>build "aa"
powershell -executionpolicy bypass "C:\test\build.ps1" 'aa'

C:\test>build 'aa'
powershell -executionpolicy bypass "C:\test\build.ps1" 'aa'

谁对谁错谁最难过 2024-08-23 06:44:25
  1. set widget=“一个非常有用的项目”
  2. set widget
  3. widget=“一个非常有用的项目”
  4. set widget=%widget:"=%"
  5. set widget
  6. set widget=一个非常有用的项目"

尾随引号 "第 4 行在字符串中添加了引号 "。应该将其删除。
第 4 行的语法以 % 结尾

  1. set widget="a very useful item"
  2. set widget
  3. widget="a very useful item"
  4. set widget=%widget:"=%"
  5. set widget
  6. set widget=a very useful item"

The trailing quote " in line 4 is adding a quote " to the string. It should be removed.
The syntax for line 4 ends with %

撩动你心 2024-08-23 06:44:25

我以为我已经找到了解决方案,但很快我就在执行批处理文件时遇到了异常行为。突然 CMD 无法识别长路径语句。从完整路径正常执行批处理文件

<块引用>

C:\Documents and Settings\Administrator\My Documents\Txt\batchtest\dataout.bat

返回

<块引用>

“C:\Documents”未被识别为内部或外部命令...

这就是你的整个问题。 CMD 无法从命令行理解文件名内的空格,因此它认为您正在尝试传递

和Settings\Administrator\My Documents\Txt\batchtest\dataout.bat

作为参数

“C:\文档”

程序。

您需要引用它才能运行路径中带有空格的批处理文件:

> "C:\Documents and Settings\Administrator\My Documents\Txt\batchtest\dataout.bat"

会起作用。

I thought I had the solution, but I soon experienced unusual behavior with execution of batch files. Suddenly CMD is no recognizing long path statments. Normal execution of batch file from full path

C:\Documents and Settings\Administrator\My Documents\Txt\batchtest\dataout.bat

returns

'C:\Documents' is not recognized as an internal or external command....

There's your whole problem. CMD doesn't understand spaces inside of filenames from the command line, so it thinks you're trying to pass

and Settings\Administrator\My Documents\Txt\batchtest\dataout.bat

as parameters to the

"C:\Documents"

program.

You need to quote it to run a batch file with spaces in the path:

> "C:\Documents and Settings\Administrator\My Documents\Txt\batchtest\dataout.bat"

would have worked.

若言繁花未落 2024-08-23 06:44:25
@echo off

Setlocal enabledelayedexpansion

Set 1=%1

Set 1=!1:"=!

Echo !1!

Echo "!1!"

Set 1=

演示带或不带引号,无论原始参数是否带引号。

如果您想测试一个可能包含或不包含引号的参数是否存在,请将此行放在上面的 echo 之前:

If '%1'=='' goto yoursub

但如果检查是否存在可能或不存在的文件可能没有引号,那么它是:

If EXIST "!1!" goto othersub

注意单引号和双引号的使用是不同的。

@echo off

Setlocal enabledelayedexpansion

Set 1=%1

Set 1=!1:"=!

Echo !1!

Echo "!1!"

Set 1=

Demonstrates with or without quotes reguardless of whether original parameter has quotes or not.

And if you want to test the existence of a parameter which may or may not be in quotes, put this line before the echos above:

If '%1'=='' goto yoursub

But if checking for existence of a file that may or may not have quotes then it's:

If EXIST "!1!" goto othersub

Note the use of single quotes and double quotes are different.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文