如何避免在此批处理文件中重复启动cmd.exe以运行AWS CLI命令?

时间:2015-02-27 09:46:14

标签: windows batch-file amazon-s3 cmd aws-cli

通过以下各种示例,我设法拼凑了一个工作批处理文件,该文件使用AWS CLI从AWS S3存储桶中提取文件列表,并在其开头附加一个URL。

我知道你可以在像'S3 Browser'这样的程序中做类似的事情,但我需要一个“一键解决方案”。结果如下;当我运行它时,它成功地从4个子文件夹中提取列表并将它们保存到4个不同的文本文件中。

它绝对能满足我的需求,但我认为这是一项非常笨拙的努力。例如,我在每个循环上启动,然后关闭cmd.exe以发送命令。

我试过把它放在循环之外;它似乎就像它应该很容易做到但是,作为批处理文件的原始初学者,我无法让它工作。

有什么想法吗?

以下是代码:

@echo off 

REM ----------- SET VARIABLES -------------------
REM Set AWS Base URL
REM ----------------
set BaseURL=https://s3-eu-west-1.amazonaws.com

REM SET AWS Bucket Name
REM -------------------
set Bucket=XXXXXX

REM SET Bucket Sub-Folder
REM ---------------------
set sub-folder-1=XXXXXX

REM SET Bucket Sub-Folder
REM ---------------------
set sub-folder-2=XXXXXX

REM SET Bucket Sub-Folders
REM ----------------------
set sub-folder-3=MP4 MP3 PDF Thumbnails

REM Set AWS file download location
set DownloadAWSFileTo=C:\Desktop

REM ------------------------------------------------

REM Loop through all sub-folders
    For %%a in (%sub-folder-3%) do (
        REM Start AWS CLI, download/save directory list to desktop, and close CMD window
        start cmd.exe /k "aws s3 ls s3://%Bucket%/%sub-folder-1%/%sub-folder-2%/%%a/ > %DownloadAWSFileTo%\filelist.txt" ^& exit

    REM Pause for 3 seconds to make sure CMD is finished
        timeout /t 3

    REM Remove everything from AWS directory list EXCEPT file names
        for /f "tokens=4 delims= " %%i in (filelist.txt) DO ( echo %%i >> CLEANfilelist.txt)

    REM Append URL structure to beginning of each line and make new list
        for /F "delims=" %%j in (CLEANfilelist.txt) do echo.%BaseURL%/%Bucket%/%sub-folder-1%/%sub-folder-2%/%%a/%%j >> %%a-URLs-%sub-folder-2%-AWS.txt

    REM Delete unwanted text files
        del filelist.txt
        del CLEANfilelist.txt
   )

1 个答案:

答案 0 :(得分:1)

只需删除cmd.exe即可......

REM Loop through all sub-folders
For %%a in (%sub-folder-3%) do (
    REM AWS CLI command to get directory file list and save to desktop
        aws s3 ls s3://%Bucket%/%sub-folder-1%/%sub-folder-2%/%%a/ > %DownloadAWSFileTo%\filelist.txt

    REM Remove everything from AWS directory list EXCEPT file names
        for /f "tokens=4 delims= " %%i in (filelist.txt) do (echo %%i >> CLEANfilelist.txt)

    REM Append URL structure to beginning of each line and make new list
        for /F "delims=" %%j in (CLEANfilelist.txt) do echo.%BaseURL%/%Bucket%/%sub-folder-1%/%sub-folder-2%/%%a/%%j >> %%a-URLs-%sub-folder-2%-AWS.txt

    REM Delete unwanted text files
        del filelist.txt
        del CLEANfilelist.txt
)

REM Pause to finish final file cleanup
timeout /t 3