2016-04-12 26 views
1

我想在单个命令行中将本地路径转换为UNC路径。CMD惰性评估(字符串替换)+多个命令在单行中用“&”

要做到这一点,我希望能与\\%ComputerName%\c$更换C:在我的本地路径,然后调用我的网络资源与"\\Server\Resources\FileReceiver.exe" "%output%",通过我的%output%作为命令行参数。

我有一个工作ProofOfConcept.cmd文件,该文件是这样的:

SET "output=C:\MyFile.txt" 
CALL SET output=%%output:C:=\\%ComputerName%\c$%% 
"\\Server\Resources\FileReceiver.exe" "%output%" 
pause 

和输出:

C:\>SET "output=C:\MyFile.txt" 
C:\>CALL SET output=%output:C:=\\%ComputerName%\c$% 
C:\>"\\Server\Resources\FileReceiver.exe" "\\PC-01\c$\MyFile.txt" 
FileReceiver Util v1.0.3.94365 

accepting \\PC-01\c$\MyFile.txt... 

FileReceiver.exe exited on Server exited with error code 0. 
C:\>pause 
Press any key to continue . . . 

所以这个工作,但我的具体使用情况,我需要连接命令放在单个可执行行上,所以我用&替换换行符,我的ProofOfConcept.cmd现在看起来像这样:

SET "output=C:\MyFile.txt" & CALL SET output=%%output:C:=\\%ComputerName%\c$%% & "\\Server\Resources\FileReceiver.exe" "%output%" 

但不是格式化的路径,%的输出%现在是一个空字符串(“”):

C:\>SET "output=C:\MyFile.txt" & CALL SET output=%output:C:=\\%ComputerName%\c$% & "\\Server\Resources\FileReceiver.exe" "" & pause 
Press any key to continue . . 

我在做什么错?如果我添加第二行到我的.cmd文件echo %output%我得到一个值,但它不是在第一行进行评估。我正在猜测懒惰评估+线程,但我不知道如何解决。我是否需要将字符串替换为我的整个执行行FIRST,然后调用它?

回答

1

你说得对懒惰的评价。你可以把最后一个命令放在另一个CALL中:

SET "output=C:\MyFile.txt" & CALL SET output=%%output:C:=\\%ComputerName%\c$%% & CALL "\\Server\Resources\FileReceiver.exe" "%%output%%" 

这对我有用。

编辑:请注意最后一次CALL(“%% output %%”)中的双重百分比。这很重要,因为必须将“百分号”以“%output%”的形式传递到CALL上下文中。好的电话指出了这一点,@epicTurkey。谢谢!

+1

谢谢!随着CALL'ing命令,您的代码显示您将%output%替换为%% output %%。这对懒惰的解析器是必需的,并且可能是一个有用的细节,可以指出你的答案。 – TaterJuice