gpt4 book ai didi

batch-file - 将当前文件名从循环传递到批处理脚本中的标签

转载 作者:行者123 更新时间:2023-12-03 08:47:18 26 4
gpt4 key购买 nike

在批处理脚本中,我正在遍历SQL脚本文件夹的循环中运行sqlcmd。如果发生错误,我希望能够将当前正在处理的脚本/输出文件传递给循环外部的标签。

这是示例代码:

@echo off
@setlocal enabledelayedexpansion

SET _INSTANCE=someinstance
SET _DATABASE=somedatabase
SET "_SCRIPTFOLDER=D:\Scripts for Testing"
SET "_OUTPUTFOLDER=D:\Output for Testing"

FOR %%S IN (
"%_SCRIPTFOLDER%\*.sql"
) DO (

SET /P _MSGa=Generating CSV: %%~nS.csv ... <NUL

sqlcmd -b -S %_INSTANCE% -d %_DATABASE% -i "%%~fS" -s "|" -o "%_OUTPUTFOLDER%\%%~nS.csv" -W
IF ERRORLEVEL >= 1 GOTO sqlcomderrorhandling

SET /P _MSGb=file created. Removing header dashes ... <NUL

REM REM Remove the line with dashes below the header
@FINDSTR /r /b /v /c:"-*|" "%_OUTPUTFOLDER%\%%~nS.csv" > "%_OUTPUTFOLDER%"\tmp.txt
IF ERRORLEVEL >= 1 GOTO findstrerrorhandling

XCOPY /Y "%_OUTPUTFOLDER%"\tmp.txt "%_OUTPUTFOLDER%\%%~nS.csv" >NUL
IF ERRORLEVEL >= 1 GOTO copyerrorhandling

ECHO done.
)
DEL /Q /F "%_OUTPUTFOLDER%"\tmp.txt
GOTO done

:sqlcomderrorhandling
ECHO An error occurred while processing the file %%~nS.csv

:done
@pause

最后一个ECHO仅输出%〜nS.csv,而不是CSV文件的实际名称。我需要以某种方式利用功能来做自己想做的事情吗?

最佳答案

根据rojo的第一部分评论和我自己的观点,这种结构是否更有意义?

@Echo Off

Set "_INSTANCE=someinstance"
Set "_DATABASE=somedatabase"
Set "_SCRIPTFOLDER=D:\Scripts for Testing"
Set "_OUTPUTFOLDER=D:\Output for Testing"

If Not Exist "%_OUTPUTFOLDER%\" (Echo Output folder doesn't exist
Timeout 3 /NoBreak >Nul
GoTo :EOF)

If Not Exist "%_SCRIPTFOLDER%\*.sql" (Echo Source folder doesn't contain any SQL files
Timeout 3 /NoBreak >Nul
GoTo :EOF)

CD /D "%_SCRIPTFOLDER%" 2>Nul || (Echo Source folder, %_SCRIPTFOLDER%, is not available.
Timeout 3 /NoBreak >Nul
GoTo :EOF)

For %%A In (*.sql) Do (
Echo Generating CSV: %%~nA.csv ...
SQLCmd -b -S %_INSTANCE% -d %_DATABASE% -i "%%A" -s "|" -o "%_OUTPUTFOLDER%\%%~nA.csv" -W 2>Nul && (
Echo File created. Removing header dashes ...
Findstr "[^-|]" "%_OUTPUTFOLDER%\%%~nA.csv">"%_OUTPUTFOLDER%"\%%~nA.tmp" && (
Move /Y "%_OUTPUTFOLDER%"\%%~nA.tmp" "%_OUTPUTFOLDER%\%%~nA.csv">Nul 2>&1 || (
Echo A Move error occurred while moving %%~nA.tmp
Timeout 2 /NoBreak >Nul)) || (Echo A FindStr error occurred while removing header dashes
Timeout 2 /NoBreak >Nul)) || (Echo A SQLCmd error occurred while processing the file %%~nS.csv
Timeout 2 /NoBreak >Nul))
Pause

关于batch-file - 将当前文件名从循环传递到批处理脚本中的标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51047327/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com