【问题标题】:trying to pass variables adds extra characters试图传递变量会添加额外的字符
【发布时间】:2013-03-08 18:36:33
【问题描述】:

几年前我看到其他人解决了这个问题,但他们似乎没有给出有效的答案。

当我尝试在批处理文件中传递这两个命令时(手动完成时它们可以工作):

nltest /dsgetsite>c:\windows\temp\site.txt 
set /p CurrentADSite<c:\windows\temp\site.txt

但是当我尝试通过批处理文件发出命令时,我得到了这个:

C:\working>nltest /dsgetsite  1>c:\windows\temp\site.txt

C:\working>set /p CurrentADSite  0<c:\windows\temp\site.txt
The syntax of the command is incorrect.

我到底是如何让这个工作的?有没有更简单的方法可以将 dsgetsite 结果直接传递到变量中?

【问题讨论】:

  • 这是Super User 问题,不是Stack Overflow 问题。
  • Lasse,因为批处理文件、shell脚本等自动化语言不会编程?我不同意。

标签: batch-file environment-variables


【解决方案1】:

您可以使用for /f 来避免临时文件(而且您[通常] 不能写入 Windows 目录,因此无论如何都会炸毁):

for /f %%x in ('nltest /dsgetsite') do if not defined CurrentADSite set CurrentADSite=%%x

【讨论】:

    【解决方案2】:

    根据http://ss64.com/nt/set.html,您可能错过了 =
    "将文件的第一行放入变量中:
    Set /P _MyVar=&lt;MyFilename.txt"

    如果一切都失败了,你总是可以依靠:

    :: start the temp batch with start of set command
    echo set CurrentADSite=>c:\windows\temp\site.bat
    :: add to the temp bat : the variable assignment
    nltest /dsgetsite>>c:\windows\temp\site.bat
    :: run the temp batch and return here
    call c:\windows\temp\site.bat
    

    【讨论】:

    • 两个问题:第一这不是倒退吗?我不应该在填充蝙蝠后设置网站吗?其次,>> 附加。这不会导致 bat 文件在每次运行时变得越来越大,因为它会附加每次后续运行的结果?
    • 是的,不起作用。创建的 bat 文件不连贯。它在第二行创建实际变量:
    • 对不起,如果批处理文件以 2 行结束,那超出了我的控制范围!我已经用一些充满希望的东西编辑了我的答案,希望 :) ... 至于我的后备方法,该集合在发出调用时第二次发生,第一个 echo 只是在批处理文本文件中放置一个命令,但直到它被称为。第二个问题:每次运行 3 命令时,echo 都会将批处理文件清除回一个新文件,只有第二次写入批处理文件才会追加。 HTH
    • 您必须改用&gt;site.cmd &lt;nul set /p X=set CurrentADSite=,因为这是不获取尾随换行符的唯一方法。
    • 我很困惑.. 你能把那行写完整吗,乔伊。非常感谢
    猜你喜欢
    • 2012-02-15
    • 2023-03-30
    • 2015-09-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-14
    • 2021-06-22
    相关资源
    最近更新 更多