
大家好,我目前在一所學校工作,我創建了一個腳本來掃描所有學生資料夾中的特定文件類型,我想知道是否有一種方法可以讓它在刪除之前複製特定文件類型?我想不出一種方法來做到這一點,因為 xcopy 和 robocopy 都需要語法中的來源位址。這是我的腳本
@echo off
net use X: \\LOCATION FOR STUDENT FOLDERS
net use Y: \\LOCATION FOR COPIED FILES
net use Z: \\LOCATION FOR .TXT FILE OF DELETED FILES
X:
cls
Echo Deleting bat files please wait...
del /s *.bat > Z:\DeletedFiles.txt 2>&1
Echo Deleting CMD files please wait...
del /s *.cmd >> Z:\DeletedFiles.txt 2>&1
Echo Deleting VBS files please wait...
del /s *.vbs >> Z:\DeletedFiles.txt 2>&1
Echo Deleting Executable files please wait...
del /s *.exe >> Z:\DeletedFiles.txt 2>&1
mountvol X:\ /D
mountvol Y:\ /D
mountvol Z:\ /D
cls
Echo Process Completed. Drives Unmounted
set /p=Press Any Key To Close
我假設它不像輸入下面的內容那麼容易(更不用說甚至可能)?
xcopy *.bat Y:\
順便說一下,我無法使用 powershell 腳本,因為我沒有權利運行它們(愚蠢的教育部門),但如果有 powershell 替代方案,請也發布它,因為這對我學習有好處。
答案1
使用FORFILES
這種方式可能比較容易理解:
forfiles /P C:\Windows /S /M *.dll /C "cmd /c @echo @path"
這是一個可以從命令列運行的範例,不會造成任何損害。
以下是您在腳本中使用它的方法:
forfiles /P X:\ /S /M *.bat /C "cmd /c @copy @path Y:\"
使用FOR
FOR /R X:\ %%B IN (*.bat) DO (
copy "%%~fB" Y:\
REM you could do the delete in here too,
REM but it's probably faster the way you have it
)
這是如何運作的:
FOR
帶有開關的命令遞歸/R
地查找提供的目錄(在本例中X:\
為該部分中定義的模式IN
。這裡我們給它模式*.bat
。對於找到的每個文件,它運行 後的語句DO
。找到的文件將是放入%%B
變數(您可以選擇任何字母)。
透過使用(...)
after ,DO
我們允許在循環的每次迭代中執行多個命令。
%%~fB
是一種處理 的值的特殊方式%%B
。所有此類特殊格式化程序均以~
開頭,並自行刪除引號(如果存在)。f
將值格式化為完整路徑名,以防將其用作相對路徑名。
for /?
在命令列運行給出了FOR
關於 的功能和可以使用的格式化標誌的非常詳細的說明。
筆記
我們使用%%B
而不是%B
像幫助中顯示的那樣,因為它位於批次文件內。以下是一些FOR
可以直接在命令列運行的範例:
FOR /R C:\Windows %Q IN (*.ttf) DO @echo I am a font: "%Q"
FOR /R C:\Windows %Q IN (*.dll) DO @echo Full path to DLL: %~fQ
如果這些位於批次檔中,則需要使用雙百分號。
關於 PowerShell
我還想指出,執行 powershell 腳本不需要任何特殊權限。
如果您收到有關執行策略的錯誤,這只是一種安全措施,在 powershell 中(而不是在腳本中)您可以執行:
Set-ExecutionPolicy Bypass
你應該閱讀更多關於執行政策充分掌握可能的設定。
如果您透過排程任務來執行 powershell 腳本,則可以在呼叫它時變更執行策略,如下所示:
powershell.exe -ExecutionPolicy Bypass
計劃任務的完整呼叫可能如下所示:
powershell.exe -NoProfile -NonInteractive -NoLogo -ExecutionPolicy Bypass -File C:\Scripts\script.ps1
答案2
使用FOR
循環:
SETLOCAL EnableExtensions
For /R "X:\" %%I IN (*.bat) do (
xcopy /i "%%I" "Y:\%%~nxI"
del "%%I"
)
所以你的腳本可以是:
@echo off
SETLOCAL EnableExtensions
net use X: \\LOCATION FOR STUDENT FOLDERS
net use Y: \\LOCATION FOR COPIED FILES
net use Z: \\LOCATION FOR .TXT FILE OF DELETED FILES
X:
cls
Echo Deleting bat, cmd, vbs, and exe files please wait...
For /R "X:\" %%I IN (*.*) do (
set "isTrue="
if (%%~xI == ".bat") set isTrue=1
if (%%~xI == ".cmd") set isTrue=1
if (%%~xI == ".vbs") set isTrue=1
if (%%~xI == ".exe") set isTrue=1
if defined isTrue (
xcopy "%%I" "Y:\%%~nxI"
del /s "%%I" > "Z:\DeletedFiles.txt" 2>&1
)
)
mountvol X:\ /D
mountvol Y:\ /D
mountvol Z:\ /D
cls
Echo Process Completed. Drives Unmounted
set /p=Press Any Key To Close