:loop
rem Step 1: Loop through each store code in st.txt
for /f "usebackq delims=" %%i in ("st.txt") do (
set "storeCode=%%i"
echo Processing store code: !storeCode!
pause
code
rem Step 2: Transform store code to pth12345
set "transformedCode=pth!storeCode!"
echo Transformed store code to: !transformedCode!
pause
rem Step 3: Check if the pth12345 file exists
if exist "!transformedCode!" (
echo Found the file: !transformedCode!
echo Skipping to next store code.
pause
goto :next
)
rem Step 4: Ping pth12345
ping -n 1 "!transformedCode!" > nul 2>&1
if errorlevel 1 (
echo !transformedCode! is offline. Stopping for this store code.
pause
goto :next
)
rem Fetch yesterday's date using osql
osql -UTRANSF -PFSNART -Sbgcpitsd-mn01 -dmaster -Q "select convert(varchar(10), getdate()-1, 120)" -h-1 -w150 > date.dat
echo Fetched yesterday's date.
pause
rem Check if the date.dat file was created
if not exist date.dat (
echo Failed to retrieve date from the database. Exiting.
pause
goto :end
)
rem Read the date from the file and format it
set /p date=<date.dat
echo Date retrieved: %date%
set day=%date:~0,10% rem Get the full date string "YYYY-MM-DD"
pause
rem Extract components
set yyyy=%day:~0,4% rem Year
set mm=%day:~5,2% rem Month
set dd=%day:~8,2% rem Day
echo Date components: Year=!yyyy!, Month=!mm!, Day=!dd!
pause
rem Construct the file names
set "brandFile=BRAND_!mm!!dd!.!storeCode!"
set "departmentFile=DEPARTMENT_!mm!!dd!.!storeCode!"
set "productFile=PRODUCT_!mm!!dd!.!storeCode!"
echo Constructed file names: !brandFile!, !departmentFile!, !productFile!
pause
rem Step 5: Run the osql command and check result for the specific product pattern
set "result=" rem Initialize result variable to empty
for /f "delims=" %%j in ('osql -UTRANSF -PFSNART -S!transformedCode! -Q "exec xp_cmdshell 'dir d:\FTPRoot\transfIN\PRODUCT_!mm!!dd!.!storeCode!'"') do (
echo Checking for PRODUCT file: %%j
echo %%j | findstr /c:"PRODUCT_!mm!!dd!.!storeCode!" >nul
if not errorlevel 1 (
set "result=PRODUCT_!mm!!dd!.!storeCode!"
)
)
pause
rem Step 6: Check result
if defined result (
echo Found result: !result!
echo Result indicates true for the presence of PRODUCT pattern for store code !storeCode!.
pause
goto :next
)
echo No relevant result found for store code !storeCode!. Continuing to download.
pause
rem Step 7: FTP download
(
echo open ftp.yourserver.com
echo username
echo password
echo get !brandFile! D:\map_drive\wprx\!brandFile!
echo get !departmentFile! D:\map_drive\wprx\!departmentFile!
echo get !productFile! D:\map_drive\wprx\!productFile!
echo bye
) > ftp_commands.txt
echo FTP commands prepared.
pause
ftp -n -s:ftp_commands.txt
echo Downloaded files to D:\map_drive\wprx\
pause
rem Step 8: Copy files to the pth12345 folder
(
echo exec xp_cmdshell 'net use x: \\172.16.141.210\map_drive "user&pass002" /user:ho\2083761'
echo exec xp_cmdshell 'copy x:\wprx\* d:\FTPRoot\TransfIN\ /y'
echo exec xp_cmdshell 'net use x: /d /y'
) > transfer2store.sql
osql -UTRANSF -PFSNART -S!transformedCode! -i transfer2store.sql
echo Copied files complete for store code !storeCode!
pause
:next
)
rem Compare st.txt and st_result.txt
fc /b st.txt st_result.txt > nul 2>&1
if errorlevel 1 (
echo st.txt and st_result.txt are different. Restarting loop.
timeout /t 60 /nobreak > nul
goto loop
) else (
echo st.txt and st_result.txt are the same. Stopping program.
)
:end
echo Script finished processing all store codes.
pause
endlocal
where is result to st_result.txt
Assistant
The provided batch script does not currently log the results to st_result.txt, although it mentions comparing st.txt and st_result.txt at the end. If you want to capture and log results of processed store codes into st_result.txt, you'll need to add code to write the relevant information during the loop.
Here’s how to modify the script to keep track of results:
Create or overwrite st_result.txt at the beginning of the loop (to clear previous data).
Append results to st_result.txt when processing each store code.
Modified Sections of the Script
Below you can see modifications in the relevant sections of your batch script for logging to st_result.txt:
batch
User
st.txt as
12345
12346
12347
st_result shoul be what, for compare to st.txt
Assistant
If you're comparing st.txt with st_result.txt, the contents of st_result.txt should reflect the outcomes of processing the store codes listed in st.txt. The way you construct st_result.txt largely depends on what results you want to log based on your batch script's execution.
Here's an example of what st_result.txt might look like, assuming your script processed each store code sequentially and logged relevant outcomes, including successes and failures.
Example Content of st.txt
code
12345
12346
12347
Example Content of st_result.txt
Assuming all store codes were processed successfully, the st_result.txt might look like this:
code
Processing store code: 12345
Found the file: pth12345
Skipping to next store code.
Processing store code: 12346
pth12346 is offline.
Processing store code: 12347
Fetched yesterday's date.
Date retrieved: 2023-10-12
Date components: Year=2023, Month=10, Day=12
Constructed file names: BRAND_1012.12347, DEPARTMENT_1012.12347, PRODUCT_1012.12347
No relevant result found for store code 12347. Continuing to download.
Downloaded files to D:\map_drive\wprx\
Copied files complete for store code 12347
Notable Points
Each Processing store code: entry corresponds to a line in st.txt.
The results for each store code might vary based on your script's actual execution (e.g., whether files were found, if the server was online, etc.).
If errors occur (like files not found or the server being offline), log those outcomes clearly so you can track which store codes succeeded or failed.
How to Compare the Two Files
When you run the command fc /b st.txt st_result.txt, it will compare the contents byte-by-byte. Since st.txt contains only the store codes, you will likely get a difference unless you create a st_result.txt with just the store codes as well.
If you want the contents of st_result.txt to make the comparison equal to st.txt, consider simply writing the successful store codes to as you process, like this:
User
where i should place
if defined result (
echo !storeCode! >> st_result.txt
)
Assistant
To ensure that the st_result.txt file captures the successful processing of each store code, you should place the if defined result condition after processing each store code but before moving on to the next one. This will ensure that you log only the store codes for which relevant results were found.
Here’s how to integrate this into your script:
Updated Script Snippet
You want to place the if defined result block right after you determine if there's a successful result, which can be before going to the :next label within the main processing loop.
Here's the relevant portion of your script with comments indicating where to place the logging for st_result.txt:
batch
rem Step 6: Check result
if defined result (
echo Found result: !result!
echo Result indicates true for the presence of PRODUCT pattern for store code !storeCode!.
rem Log the successful result to st_result.txt
echo !storeCode! >> st_result.txt rem <-- PLACE IT HERE
pause
goto :next
)
echo No relevant result found for store code !storeCode!. Continuing to download.
echo No relevant result found for store code !storeCode! >> st_result.txt
pause
Key Changes Made:
The line echo !storeCode! >> st_result.txt is added within the if defined result block. This means it will only log the store code if a result was successfully found for it.
The rest of the script remains as is, ensuring that you're still capturing when a store code does not yield a relevant result.
Final Structure of the Workflow
Your structure should then be:
Check for the definition of result after you determine if the PRODUCT file pattern was found.
If it is defined (indicating success), log the store code to st_result.txt.
If it's not defined, you can log that as well or handle it differently, as shown.
Complete Relevant Section Example
Here's how the complete relevant section might look in context:
batch
User
osql -UTRANSF -PFSNART -S!transformedCode! -i transfer2store.sql
echo Copied files complete for store code !storeCode!
echo Copied files complete for store code !storeCode! >> st_result.txt
pause
code
:next
)
look like :next in here make script error ) was unexpected at this time.
Assistant
The error message ) was unexpected at this time usually indicates a problem with the syntax in a batch script, often caused by mismatched parentheses, missing elements, or incorrect placement of labels.
Common Causes of the Error
Mismatched Parentheses: Ensure every opening parenthesis ( has a corresponding closing parenthesis ).
Label Definition and Usage: Improperly defined labels (like :next) can lead to issues if not placed correctly.
Control Structure Issues: Nested if statements, loops, and other structures must be properly closed.
Solution for Your Specific Case
From your snippet, it seems that the :next label may not be properly defined or is placed incorrectly. Let's consider placing the :next label correctly inside your loop but outside of relevant conditions.
Example Script Structure
Here’s an overall structure with corrections and comments to guide you:
batch
User
check my code
@echo off
setlocal EnableDelayedExpansion
rem Create or clear st_result.txt at the beginning
echo. > st_result.txt
:loop
rem Step 1: Loop through each store code in st.txt
for /f "usebackq delims=" %%i in ("st.txt") do (
set "storeCode=%%i"
code
rem Step 2: Transform store code to pth12345
set "transformedCode=PTH!storeCode!"
echo !transformedCode!
rem Step 3: Check if the pth12345 file exists
if exist "!transformedCode!" (
echo Found the file: !transformedCode!
echo Skipping to next store code.
goto :next
)
rem Step 4: Ping pth12345
ping -n 1 "!transformedCode!" > nul 2>&1
if errorlevel 1 (
echo !transformedCode! is offline. Stopping for this store code.
goto :next
)
rem Step 5: Get Date
osql -UTRANSF -PFSNART -Sbgcpitsd-mn01 -dmaster -Q "set nocount on; select convert(varchar(10), getdate()-1, 120)" -h-1 -w150 > date.dat
set /p day=<date.dat
set mm=!day:~6,2!
set dd=!day:~9,2!
del date.dat
set "brandFile=BRAND_!mm!!dd!.!storeCode!"
set "departmentFile=DEPARTMENT_!mm!!dd!.!storeCode!"
set "productFile=PRODUCT_!mm!!dd!.!storeCode!"
rem Step 6: Run the osql command and check result for the specific product pattern
set "result=" rem Initialize result variable to empty
for /f "delims=" %%j in ('osql -UTRANSF -PFSNART -S!transformedCode! -Q "exec xp_cmdshell 'dir d:\FTPRoot\transfIN\PRODUCT_!mm!!dd!.!storeCode!'"') do (
echo %%j | findstr /c:"PRODUCT_!mm!!dd!.!storeCode!" >nul
if not errorlevel 1 (
set "result=PRODUCT_!mm!!dd!.!storeCode!"
)
)
rem Step 6: Check result
if defined result (
echo Found !result!
echo !storeCode! >> st_result.txt
goto :next
)
rem Step 7: Not Found Product Continue download
echo Not Found !result!
(
echo user hotrn
echo hotrn
echo cd ..
echo cd ..
echo cd Aldata/LIFE/HEAD/SAV/DOWN/POS
echo hash
echo get !productFile! D:\map_drive\wprx\!productFile!
echo hash
echo hash
echo get !departmentFile! D:\map_drive\wprx\!departmentFile!
echo hash
echo hash
echo get !brandFile! D:\map_drive\wprx\!brandFile!
echo bye
) > ftpcmd.dat
ftp -n -s:ftpcmd.dat 10.4.9.128
del ftpcmd.dat
echo Downloaded files to D:\map_drive\wprx\
rem Step 8: Copy files to the pth12345 folder
(
echo exec xp_cmdshell 'net use x: \\172.16.141.210\map_drive "user&pass002" /user:ho\2083761'
echo exec xp_cmdshell 'copy x:\wprx\* d:\FTPRoot\TransfIN\ /y'
echo exec xp_cmdshell 'net use x: /d /y'
) > transfer2store.sql
osql -UTRANSF -PFSNART -S!transformedCode! -i transfer2store.sql
echo Copied files complete for store code !storeCode!
del /q transfer2store.sql > nul
del /q d:\map_drive\wprx\* > nul
:next
Assistant
Your batch script is structured fairly well, but there are a few adjustments and checks to ensure it runs smoothly and to prevent potential issues.
Key Observations and Recommendations
Correct Usage of Labels: Ensure that the :next label is placed properly; it should be outside of any code blocks to avoid confusion and ensure the script flows logically.
Error Handling: It's a good practice to handle potential errors throughout the script, especially with commands like osql and ftp.
Batch File Syntax: Ensure there are no misaligned or mismatched parentheses, especially in the control flow.
Clearing Directories: The line del /q d:\map_drive\wprx\* > nul should be used with caution to avoid accidental data loss.
Quoting Paths: When dealing with file paths, especially with spaces, it's a best practice to wrap paths in double quotes.
Here is the revised script with suggestions and corrections:
batch
User
how to hidden ftp -n -s:ftpcmd.dat 10.4.9.128 process
Assistant
To run the FTP command without displaying the console window (making it "hidden"), you can use a few methods in a batch file. One common way to achieve this in Windows batch scripting is to run the FTP command through a script executed by a different process that does not show the console.
Here’s how you can implement this:
Method 1: Use START with cmd.exe /c
You can use the START command to run the FTP command in a hidden window. Here's how you can do it:
/B option allows the command to be started without creating a new window.
cmd /c runs the command specified (in this case, the FTP command) and then terminates the command shell.
> NUL 2>&1 suppresses both the output and error messages, so you don't see anything in the console.
Updated Section of Your Script
Here's how your FTP download section would look with the hidden execution:
batch
rem Step 7: Not Found Product Continue download
echo Not Found !result!
(
echo user hotrn
echo hotrn
echo cd ..
echo cd ..
echo cd Aldata/LIFE/HEAD/SAV/DOWN/POS
echo hash
echo get !productFile! D:\map_drive\wprx\!productFile!
echo hash
echo get !departmentFile! D:\map_drive\wprx\!departmentFile!
echo hash
echo get !brandFile! D:\map_drive\wprx\!brandFile!
echo bye
) > ftpcmd.dat
rem Run FTP command without showing a window
START /B cmd /c "ftp -n -s:ftpcmd.dat 10.4.9.128 > NUL 2>&1"
del ftpcmd.dat
echo Downloaded files to D:\map_drive\wprx\
Method 2: Use PowerShell
You could also use PowerShell to run the FTP command in a hidden window. This method requires a PowerShell command to execute the FTP command while suppressing its visibility:
rem Step 6: Run the osql command and check result for the specific product pattern
set "result=" rem Initialize result variable to empty
code
(
echo exec xp_cmdshell 'exec xp_cmdshell 'dir d:\FTPRoot\transfIN\PRODUCT_!mm!!dd!.!storeCode!'"''
) > check_product.sql
osql -UTRANSF -PFSNART -S!transformedCode! -i check_product.sql
if not errorlevel 1 (
set "result=PRODUCT_!mm!!dd!.!storeCode!"
)
)
Assistant
It looks like you want to run a SQL command using osql to check for the existence of a specific product file in a directory, and you're attempting to capture the output to determine if the file exists or not. However, there are a few issues with the syntax in the code block you've provided, particularly with how nested quotes are handled and how you're checking for errors.
Correcting Your Code
To successfully run this command, you'll need to adjust both the SQL command you're echoing to the file and the logic that checks for a result.
Here is a corrected version of your code:
batch
rem Step 6: Run the osql command and check result for the specific product pattern
set "result=" rem Initialize result variable to empty
(
rem The outer single quotes are to ensure the SQL command is executed inside SQL Server
echo exec xp_cmdshell 'dir d:\FTPRoot\transfIN\PRODUCT_!mm!!dd!.!storeCode!'
) > check_product.sql
osql -UTRANSF -PFSNART -S!transformedCode! -i check_product.sql > result.dat
rem Check if result.dat contains the product filename
findstr /c:"PRODUCT_!mm!!dd!.!storeCode!" result.dat > nul
if not errorlevel 1 (
set "result=PRODUCT_!mm!!dd!.!storeCode!"
)
rem Clean up the output file
del result.dat
Explanation of Changes
Nested Quotes: The echo command correctly formats the SQL command with only one level of single quotes around the dir command. The SQL Server xp_cmdshell should contain the command you want to run directly without additional nested quotes.
Output Capture to a File:
Use > result.dat to capture the output of osql for checking later. This file will contain the results of the dir command.
Searching for the Result:
Use findstr to search through the result.dat output for the line that includes your specific product file name. This way, you can determine if the product file actually exists.
Error Checking:
Instead of checking the error level directly after the osql command, you check if findstr was successful (errorlevel 0 means the string was found).
Cleanup: It’s nice to clean up temporary files after you’re done with them.
Final Note
Make sure the SQL Server has the necessary permissions to execute xp_cmdshell, and that the dir command outputs to a path that is accessible within the context of the SQL Server instance.
Not yet included in a published release.
@echo off
setlocal EnableDelayedExpansion
rem Create or clear st_result.txt at the beginning
echo. > st_result.txt
:loop
rem Step 1: Loop through each store code in st.txt
for /f "usebackq delims=" %%i in ("st.txt") do (
set "storeCode=%%i"
echo Processing store code: !storeCode!
rem Log the processing action
echo Processing store code: !storeCode! >> st_result.txt
pause
rem Step 2: Transform store code to pth12345
set "transformedCode=pth!storeCode!"
echo Transformed store code to: !transformedCode!
pause
rem Step 3: Check if the pth12345 file exists
if exist "!transformedCode!" (
echo Found the file: !transformedCode!
echo Skipping to next store code.
echo Found the file: !transformedCode! >> st_result.txt
pause
goto :next
)
rem Step 4: Ping pth12345
ping -n 1 "!transformedCode!" > nul 2>&1
if errorlevel 1 (
echo !transformedCode! is offline. Stopping for this store code.
echo !transformedCode! is offline >> st_result.txt
pause
goto :next
)
rem Fetch yesterday's date using osql
osql -UTRANSF -PFSNART -Sbgcpitsd-mn01 -dmaster -Q "select convert(varchar(10), getdate()-1, 120)" -h-1 -w150 > date.dat
echo Fetched yesterday's date.
pause
rem Check if the date.dat file was created
if not exist date.dat (
echo Failed to retrieve date from the database. Exiting.
echo Failed to retrieve date from the database >> st_result.txt
pause
goto :end
)
rem Read the date from the file and format it
set /p date=<date.dat
echo Date retrieved: %date%
set day=%date:~0,10% rem Get the full date string "YYYY-MM-DD"
pause
rem Extract components
set yyyy=%day:~0,4% rem Year
set mm=%day:~5,2% rem Month
set dd=%day:~8,2% rem Day
echo Date components: Year=!yyyy!, Month=!mm!, Day=!dd!
pause
rem Construct the file names
set "brandFile=BRAND_!mm!!dd!.!storeCode!"
set "departmentFile=DEPARTMENT_!mm!!dd!.!storeCode!"
set "productFile=PRODUCT_!mm!!dd!.!storeCode!"
echo Constructed file names: !brandFile!, !departmentFile!, !productFile!
pause
rem Step 5: Run the osql command and check result for the specific product pattern
set "result=" rem Initialize result variable to empty
for /f "delims=" %%j in ('osql -UTRANSF -PFSNART -S!transformedCode! -Q "exec xp_cmdshell 'dir d:\FTPRoot\transfIN\PRODUCT_!mm!!dd!.!storeCode!'"') do (
echo Checking for PRODUCT file: %%j
echo %%j | findstr /c:"PRODUCT_!mm!!dd!.!storeCode!" >nul
if not errorlevel 1 (
set "result=PRODUCT_!mm!!dd!.!storeCode!"
)
)
pause
rem Step 6: Check result
if defined result (
echo Found result: !result!
echo Result indicates true for the presence of PRODUCT pattern for store code !storeCode!.
echo Found result: !result! >> st_result.txt
pause
goto :next
)
echo No relevant result found for store code !storeCode!. Continuing to download.
echo No relevant result found for store code !storeCode! >> st_result.txt
pause
rem Step 7: FTP download
(
echo open ftp.yourserver.com
echo username
echo password
echo get !brandFile! D:\map_drive\wprx\!brandFile!
echo get !departmentFile! D:\map_drive\wprx\!departmentFile!
echo get !productFile! D:\map_drive\wprx\!productFile!
echo bye
) > ftp_commands.txt
echo FTP commands prepared.
pause
ftp -n -s:ftp_commands.txt
echo Downloaded files to D:\map_drive\wprx\
echo Downloaded files to D:\map_drive\wprx\ >> st_result.txt
pause
rem Step 8: Copy files to the pth12345 folder
(
echo exec xp_cmdshell 'net use x: \\172.16.141.210\map_drive "user&pass002" /user:ho\2083761'
echo exec xp_cmdshell 'copy x:\wprx\* d:\FTPRoot\TransfIN\ /y'
echo exec xp_cmdshell 'net use x: /d /y'
) > transfer2store.sql
osql -UTRANSF -PFSNART -S!transformedCode! -i transfer2store.sql
echo Copied files complete for store code !storeCode!
echo Copied files complete for store code !storeCode! >> st_result.txt
pause
:next
)
rem Compare st.txt and st_result.txt
fc /b st.txt st_result.txt > nul 2>&1
if errorlevel 1 (
echo st.txt and st_result.txt are different. Restarting loop.
timeout /t 60 /nobreak > nul
goto loop
) else (
echo st.txt and st_result.txt are the same. Stopping program.
)
:end
echo Script finished processing all store codes.
pause
endlocal
Key Changes Made:
Initialization of st_result.txt: At the start of the loop, the file is created or cleared.
Logging Processing Steps: After relevant actions, results are appended to st_result.txt. This includes information on file findings, download actions, and any relevant messages.
You can adjust the messages being logged as needed based on what specific results you'd like to see in st_result.txt.
st_result.txt
Modified Example of st_result.txt for Comparison
You could end up with a simple result file that contains only processed store codes:
code
12345
12347
Where:
12345 was found as a previous file, and hence skipped.
12346 was offline thus not processed.
12347 was processed successfully.
In such a case, you can compare st.txt and st_result.txt, which would reflect the store codes that were processed successfully. To create this kind of result, you would include successful checks in your logging mechanism specifically for valid store codes.
To keep the logic consistent with your workflow:
Process each line in st.txt.
Log the store code to st_result.txt if that code was executed successfully (i.e., the desired file was downloaded and copied).
Example of Processing for st_result.txt
Update the batch file to log successful store codes only:
batch
if defined result (
echo !storeCode! >> st_result.txt
)
This way, st_result.txt ends up with only the store codes that had a successful run, allowing a logical comparison between what was processed versus what was requested.
rem Step 6: Check result
if defined result (
echo Found result: !result!
echo Result indicates true for the presence of PRODUCT pattern for store code !storeCode!.
rem Log the successful result to st_result.txt
echo !storeCode! >> st_result.txt rem <-- THIS LOGS SUCCESSFUL CODE
pause
goto :next
)
echo No relevant result found for store code !storeCode!. Continuing to download.
echo No relevant result found for store code !storeCode! >> st_result.txt
pause
Resulting Behavior
This adjustment will ensure st_result.txt contains only the store codes for which some meaningful action was taken, allowing for accurate comparisons against the original st.txt. When you compare the two files at the end of your script:
batch
fc /b st.txt st_result.txt > nul 2>&1
You should then see the differences based on which store codes had successful outcomes.
@echo off
setlocal EnableDelayedExpansion
rem Create or clear st_result.txt at the beginning
echo. > st_result.txt
:loop
rem Step 1: Loop through each store code in st.txt
for /f "usebackq delims=" %%i in ("st.txt") do (
set "storeCode=%%i"
echo Processing store code: !storeCode!
echo Processing store code: !storeCode! >> st_result.txt
pause
rem Step 2: Transform store code to pth12345
set "transformedCode=pth!storeCode!"
echo Transformed store code to: !transformedCode!
pause
rem Step 3: Check if the pth12345 file exists
if exist "!transformedCode!" (
echo Found the file: !transformedCode!
echo Skipping to next store code.
echo Found the file: !transformedCode! >> st_result.txt
pause
goto :next rem Move to next store code
)
rem Step 4: Ping pth12345
ping -n 1 "!transformedCode!" > nul 2>&1
if errorlevel 1 (
echo !transformedCode! is offline. Stopping for this store code.
echo !transformedCode! is offline >> st_result.txt
pause
goto :next rem Move to next store code
)
rem Fetch yesterday's date using osql
osql -UTRANSF -PFSNART -Sbgcpitsd-mn01 -dmaster -Q "select convert(varchar(10), getdate()-1, 120)" -h-1 -w150 > date.dat
echo Fetched yesterday's date.
pause
rem Check if the date.dat file was created
if not exist date.dat (
echo Failed to retrieve date from the database. Exiting.
echo Failed to retrieve date from the database >> st_result.txt
pause
goto :end
)
rem Read the date from the file and format it
set /p date=<date.dat
echo Date retrieved: %date%
set day=%date:~0,10% rem Get the full date string "YYYY-MM-DD"
pause
rem Extract components
set yyyy=%day:~0,4% rem Year
set mm=%day:~5,2% rem Month
set dd=%day:~8,2% rem Day
echo Date components: Year=!yyyy!, Month=!mm!, Day=!dd!
pause
rem Construct the file names
set "brandFile=BRAND_!mm!!dd!.!storeCode!"
set "departmentFile=DEPARTMENT_!mm!!dd!.!storeCode!"
set "productFile=PRODUCT_!mm!!dd!.!storeCode!"
echo Constructed file names: !brandFile!, !departmentFile!, !productFile!
pause
rem Step 5: Run the osql command and check result for the specific product pattern
set "result=" rem Initialize result variable to empty
for /f "delims=" %%j in ('osql -UTRANSF -PFSNART -S!transformedCode! -Q "exec xp_cmdshell 'dir d:\FTPRoot\transfIN\PRODUCT_!mm!!dd!.!storeCode!'"') do (
echo Checking for PRODUCT file: %%j
echo %%j | findstr /c:"PRODUCT_!mm!!dd!.!storeCode!" >nul
if not errorlevel 1 (
set "result=PRODUCT_!mm!!dd!.!storeCode!"
)
)
pause
rem Step 6: Check result
if defined result (
echo Found result: !result!
echo Result indicates true for the presence of PRODUCT pattern for store code !storeCode!.
rem Log the successful result to st_result.txt
echo !storeCode! >> st_result.txt rem <-- LOG SUCCESSFUL STORE CODE
pause
goto :next rem Move to next store code
)
echo No relevant result found for store code !storeCode!. Continuing to download.
echo No relevant result found for store code !storeCode! >> st_result.txt
pause
rem Step 7: FTP download
(
echo open ftp.yourserver.com
echo username
echo password
echo get !brandFile! D:\map_drive\wprx\!brandFile!
echo get !departmentFile! D:\map_drive\wprx\!departmentFile!
echo get !productFile! D:\map_drive\wprx\!productFile!
echo bye
) > ftp_commands.txt
echo FTP commands prepared.
pause
ftp -n -s:ftp_commands.txt
echo Downloaded files to D:\map_drive\wprx\
echo Downloaded files to D:\map_drive\wprx\ >> st_result.txt
pause
rem Step 8: Copy files to the pth12345 folder
(
echo exec xp_cmdshell 'net use x: \\172.16.141.210\map_drive "user&pass002" /user:ho\2083761'
echo exec xp_cmdshell 'copy x:\wprx\* d:\FTPRoot\TransfIN\ /y'
echo exec xp_cmdshell 'net use x: /d /y'
) > transfer2store.sql
osql -UTRANSF -PFSNART -S!transformedCode! -i transfer2store.sql
echo Copied files complete for store code !storeCode!
echo Copied files complete for store code !storeCode! >> st_result.txt
pause
:next rem <-- This label must be outside of the for loop and any conditional blocks
)
rem At the end, you can compare st.txt and st_result.txt
fc /b st.txt st_result.txt > nul 2>&1
if errorlevel 1 (
echo st.txt and st_result.txt are different. Restarting loop.
timeout /t 60 /nobreak > nul
goto loop
) else (
echo st.txt and st_result.txt are the same. Stopping program.
)
:end
echo Script finished processing all store codes.
pause
endlocal
Key Points
Placement of :next Label: Ensure the :next label is placed after all processing for each store code and outside of any conditional statements (like if or looping structures).
Structure Integrity: Make sure all opening parentheses ( have matching closing parentheses ) to maintain the proper structure. This includes the loops and conditional checks.
Use of Labels: Labels in batch files serve as points to jump to, so it's important that they're defined clearly and not placed inside complex blocks that may lead to ambiguity.
By ensuring these adjustments, you should avoid the ) was unexpected at this time error and achieve the expected functionality of your script.
)
rem Step 9: Compare st.txt and st_result.txt
fc /b st.txt st_result.txt > nul 2>&1
if errorlevel 1 (
echo st.txt and st_result.txt are different. Restarting loop.
timeout /t 10 /nobreak
goto loop
) else (
echo st.txt and st_result.txt are the same. Stopping program.
)
:end
echo Script finished processing all store codes.
pause
endlocal
@echo off
setlocal EnableDelayedExpansion
rem Create or clear st_result.txt at the beginning
echo. > st_result.txt
:loop
rem Step 1: Loop through each store code in st.txt
for /f "usebackq delims=" %%i in ("st.txt") do (
set "storeCode=%%i"
rem Step 2: Transform store code to PTH12345
set "transformedCode=PTH!storeCode!"
echo Processing code: !transformedCode!
rem Step 3: Check if the PTH12345 file exists
if exist "!transformedCode!" (
echo Found the file: !transformedCode!
echo Skipping to next store code.
goto :next
)
rem Step 4: Ping PTH12345
ping -n 1 "!transformedCode!" > nul 2>&1
if errorlevel 1 (
echo !transformedCode! is offline. Stopping for this store code.
goto :next
)
rem Step 5: Get Date
osql -UTRANSF -PFSNART -Sbgcpitsd-mn01 -dmaster -Q "set nocount on; select convert(varchar(10), getdate()-1, 120)" -h-1 -w150 > date.dat
if errorlevel 1 (
echo Failed to retrieve date. Check OSQL command.
goto :next
)
set /p day=<date.dat
set mm=!day:~5,2!
set dd=!day:~8,2!
del date.dat
set "brandFile=BRAND_!mm!!dd!.!storeCode!"
set "departmentFile=DEPARTMENT_!mm!!dd!.!storeCode!"
set "productFile=PRODUCT_!mm!!dd!.!storeCode!"
rem Step 6: Run the osql command and check result for the specific product pattern
set "result=" rem Initialize result variable to empty
for /f "delims=" %%j in ('osql -UTRANSF -PFSNART -S!transformedCode! -Q "exec xp_cmdshell 'dir d:\FTPRoot\transfIN\PRODUCT_!mm!!dd!.!storeCode!'"') do (
echo Checking %%j
echo %%j | findstr /c:"PRODUCT_!mm!!dd!.!storeCode!" >nul
if not errorlevel 1 (
set "result=PRODUCT_!mm!!dd!.!storeCode!"
)
)
rem Step 7: Check result
if defined result (
echo Found !result!
echo !storeCode! >> st_result.txt
goto :next
)
rem If not found, proceed to download
echo Not Found !result!
(
echo user hotrn
echo hotrn
echo cd ..
echo cd ..
echo cd Aldata/LIFE/HEAD/SAV/DOWN/POS
echo hash
echo get !productFile! D:\map_drive\wprx\!productFile!
echo hash
echo get !departmentFile! D:\map_drive\wprx\!departmentFile!
echo hash
echo get !brandFile! D:\map_drive\wprx\!brandFile!
echo bye
) > ftpcmd.dat
ftp -n -s:ftpcmd.dat 10.4.9.128
del ftpcmd.dat
echo Downloaded files to D:\map_drive\wprx\
rem Step 8: Copy files to the PTH12345 folder
(
echo exec xp_cmdshell 'net use x: \\172.16.141.210\map_drive "user&pass002" /user:ho\2083761'
echo exec xp_cmdshell 'copy x:\wprx\* d:\FTPRoot\TransfIN\ /y'
echo exec xp_cmdshell 'net use x: /d /y'
) > transfer2store.sql
osql -UTRANSF -PFSNART -S!transformedCode! -i transfer2store.sql
echo Copied files complete for store code !storeCode!
del /q transfer2store.sql > nul
rem Caution: Ensure you want to delete all files in the D:\map_drive\wprx directory.
del /q D:\map_drive\wprx\* > nul
:next
)
rem Step 9: Compare st.txt and st_result.txt
fc /b st.txt st_result.txt > nul 2>&1
if errorlevel 1 (
echo st.txt and st_result.txt are different. Restarting loop.
timeout /t 10 /nobreak
goto loop
) else (
echo st.txt and st_result.txt are the same. Stopping program.
)
:end
echo Script finished processing all store codes.
pause
endlocal
Key Changes
Error Handling for OSQL: Added a check for the success of the osql command retrieving the date.
Clarified Output Messages: Enhanced some echo statements to provide more clarity during execution.
Safety Note for Deleting Files: A cautionary note regarding the del command which removes all files in a specified directory. Ensure this is intended, as it cannot be undone.
Consistent Formatting: Cleaned up the formatting somewhat for readability.
Debugging Tips
If encountering issues, consider adding more echo statements to track variable values at various points.
Check for any connectivity issues with databases and FTP servers if commands fail.
Ensure you have permission to access and modify paths used in the script.
By implementing the above modifications, your script should work more reliably while providing useful feedback throughout its execution.
Example Using PowerShell
Replace your FTP command Section with this if you prefer using PowerShell:
batch
rem Step 7: Not Found Product Continue download
echo Not Found !result!
(
echo user hotrn
echo hotrn
echo cd ..
echo cd ..
echo cd Aldata/LIFE/HEAD/SAV/DOWN/POS
echo hash
echo get !productFile! D:\map_drive\wprx\!productFile!
echo hash
echo get !departmentFile! D:\map_drive\wprx\!departmentFile!
echo hash
echo get !brandFile! D:\map_drive\wprx\!brandFile!
echo bye
) > ftpcmd.dat
rem Run FTP command using PowerShell in hidden mode
powershell -windowstyle hidden -command "ftp -n -s:ftpcmd.dat 10.4.9.128"
del ftpcmd.dat
echo Downloaded files to D:\map_drive\wprx\
Conclusion
Using one of these methods, you can run the FTP command without displaying the command window. Make sure to test both approaches to see which one integrates better with your script and meets your needs. The START /B cmd /c method is often simpler and may suffice in most cases for running batch scripts.