【问题标题】:Batch script to dynamically pass inputs to a .exe and run recursively将输入动态传递给 .exe 并递归运行的批处理脚本
【发布时间】:2020-06-03 05:18:38
【问题描述】:

我正在尝试运行一个批处理脚本,它将从 SQL Server 表结果集中获取值,并将其作为循环中的输入传递给批处理脚本中的 .EXE 并递归运行。

示例:

SQL Query: 
select Name from sys.tables

SQL Query output: 
a
b
c

/*Now I have to pass the output of sql query values(a,b,c) I got above as an 
input to Test.exe parameter 3 times in a for or while loop specific to batch 
script one value at a time and executes the exe. 

Example of values passed to exe looks as below.


Test.exe a  -- 1st run in a loop
Test.exe b  -- 2nd run in a loop
Test.exe c  -- 3rd run in a loop

-- My code overview or assumption, I would need the below code snippet to be replaced 
and rewritten in a way it executes successfully using batch script.*/


declare @name int
set @name = count(Name) from sys.tables


DECLARE @Counter INT 

SET @Counter=1

WHILE ( @Counter <= @name)

BEGIN

    C:\Users> .\Test.exe /Input_From_Sql_result_as_argument @Name 

    SET @Counter  = @Counter  + 1
END

我是批处理脚本的新手,如果您能对在批处理脚本中实现这一点提出一些想法,那将非常有帮助。如果我需要分享任何细节,请告诉我。

【问题讨论】:

  • 如果您向我们展示批处理脚本,我会的。这是一个 .sql 脚本,不是批处理。
  • @GerhardBarnard 是的,最终输出和执行应该通过运行一个批处理文件来完成,但是批处理文件中的逻辑取决于从 SQL 表派生的结果集,并且应该作为输入传递给将根据记录数循环运行的exe作为sql表中的输出。
  • 对于您示例的命令类型,您需要的批处理等效项是 for setstart 。在 cmd.exe 中键入每个命令,后跟 /?对于语法

标签: sql-server powershell tsql batch-file exe


【解决方案1】:

借助Setlocal EnableDelayedExpansion 和基本的For /F 循环,可以将每一行的内容设置为索引变量,就像数组一样

根据文件的内容/结构,您可能不需要使用数组方法 - 只需使用 For /F 循环变量/s(本例中为 %%G)执行您的操作。

同样,取决于内容,您可能需要修改 for 循环中的选项以检索特定标记。 (在 cmd.exe 中键入 For /F 以获取完整的语法 - 或搜索并阅读关于 SO 处理文件内容的许多其他问题)

一旦您建立了数组,您就可以使用For /L 循环遍历每一行并使用每一行的值插入要执行的命令。

如果,通过递归运行,您的意思是在文件夹和子文件夹中的每个文件上运行它(术语递归的典型含义,涉及批处理,将 For /F 循环嵌套在 For /R 循环中,并交换 @987654327 @ 和 %%A 在 For /F 循环中,如下所示:

CD(更改目录)/PUSHD 到要迭代的父文件夹/或/确保批处理从父文件夹运行

For /R %%A In (*.YOURextension) Do (For /F "delims=" %%G in (%%A) Do (commands))

``

@ECHO OFF
Setlocal EnableDelayedExpansion
Set index=0
Set "inputFile=Your File Path.extension"
For /f "delims=" %%G in (%inputfile%) DO (
REM Perform your action on the content here using %%G
    ECHO(%%G
REM Optional - assign value of each line to indexed variable
    Set /a "index+=1"
    Set "Line[!index!]=%%G"
)

For /L %%I in (1,1,!index!) DO (
REM - Alternate - Perfom your action on the content here using !Line[%%I]!
    ECHO(!Line[%%I]!
)

【讨论】:

  • 非常感谢,这真的很有帮助:)
猜你喜欢
  • 1970-01-01
  • 2013-09-29
  • 2014-04-22
  • 2023-01-23
  • 2021-10-30
  • 2017-01-30
  • 2022-07-02
  • 1970-01-01
  • 2019-01-04
相关资源
最近更新 更多