簡體   English   中英

在批處理腳本中設置for循環

[英]Setting up a for loop in a batch script

我正在嘗試創建一個批處理文件,該文件將掃描文件夾中的文件

for /R D:\path\import_orders\xml_files\ %%f in (*.xml) do(
    copy %%f "\\destination"
    if errorlevel 0 move %%f "D:\path\import_orders\xml_files\archive\"
)

已修正 - 但是不會起作用。 如果我執行它,它只會輸出第一行代碼 現在可以使用了。 我在“ do(”之后添加了一個空格,現在它執行了。

1)我的第二個命令可以嗎? 如果第一條命令一切順利,我想將復制的文件移動到存檔中。

2)我應該如何更改循環使其僅在給定目錄中的文件而不是子目錄中工作?

  • 您在do和括號之間缺少空格

  • if errorlevel n等於或大於n的任何錯誤級別值都被評估為true,則構造, if errorlevel 0對於任何非負錯誤級別值將為true。 if not errorlevel 1則應使用if not errorlevel 1

  • 引用所有路徑是一個好習慣,以防萬一某些內容可能包含空格或特殊字符

for /R "D:\path\import_orders\xml_files" %%f in (*.xml) do (
    copy "%%~ff" "\\destination"
    if not errorlevel 1 move "%%~ff" "D:\path\import_orders\xml_files\archive\"
)

為了避免目錄遞歸,只需更改for循環,刪除/R (要求遞歸)即可將開始文件夾的提示移至文件選擇模式。

for %%f in ("D:\path\import_orders\xml_files\*.xml") do (
    copy "%%~ff" "\\destination"
    if not errorlevel 1 move "%%~ff" "D:\path\import_orders\xml_files\archive\"
)

但是無論如何, copy命令都不要求確認目標文件是否存在。 如果您不想覆蓋現有文件,則可以選擇一些方法

使用copy命令的開關

您可以使用/-y因此copy命令在覆蓋文件之前會要求您進行確認,並且可以通過管道自動回答問題來自動執行該過程。

echo n|copy /-y "source" "target"

這是npocmaka的答案中的方法 這種方法應該可以正常工作,但是

  • 必須兩個創建兩個cmd實例來處理管道的每一面,並對每個源文件進行處理,這樣會減慢該過程

  • 如果代碼在覆蓋問題沒有等待N字符作為否定答案的語言環境中執行,則可能會失敗。

首先檢查文件是否存在

您可以使用內置的if exist構造首先檢查目標文件是否存在

if not exist "\\destination\%%~nxf" copy "%%~ff" "\\destination"

%%~nxf如果正在處理的文件的名稱和擴展名

因此,最終的代碼可能是

for %%f in ("D:\path\import_orders\xml_files\*.xml") do (
    if not exist "\\destination\%%~nxf" copy "%%~ff" "\\destination"
    if not errorlevel 1 move "%%~ff" "D:\path\import_orders\xml_files\archive\"
)
for /R "D:\path\import_orders\xml_files\" %%f in (*.xml) do (
    (echo n|copy /-y "%%~ff" "\\destination"|find /i "0 file(s) copied." >nul 2>&1)||(
       move "%%~ff" "D:\path\import_orders\xml_files\archive\"
    )
)

編輯而不搜索子目錄:

for %%f in ("D:\path\import_orders\xml_files\*.xml") do (
    (echo n|copy /-y "%%~ff" "\\destination"|find /i "0 file(s) copied." >nul 2>&1)||(
       move "%%~ff" "D:\path\import_orders\xml_files\archive\"
    )
)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM