[英]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.