我有一个工作 for 循环来打印一个工作目录下的所有 zip 文件的名称:
@echo off
setlocal
for %%i in (*.zip) do (
echo %%i
)
我有另一个有效的 if 块来检查并打印出 zip 文件的大小:
echo set FileSize=%%~z1 > %temp%\GetFileSize.bat
call %temp%\GetFileSize "720P_1500K_101399042.zip"
if %FileSize% GTR 1000 (
echo %FileSize% is greater than 1000
) else (
echo %FileSize% is NOT greater than 1000
)
现在,我尝试将这两部分组合在一起,得到一个for 循环获取工作目录下的所有 zip 文件,同时使用如果块检查文件大小,然后打印出大小。但我被告知:此时1000是意料之外的。为什么?
for %%i in (*.zip) do (
echo %%i
echo set FileSize=%%~z1 > %temp%\GetFileSize.bat
call %temp%\GetFileSize "%%i"
if %FileSize% GTR 1000 (
echo %FileSize% is greater than 1000
) else (
echo %FileSize% is NOT greater than 1000
)
)
答案1
我将使用 powershell 来实现此目的:
Get-ChildItem "Filepath" -Filter *.zip | ForEach {
"$_.Name"
If($_.Length -gt 1000){
Write-Host "$($_.Length) is greater than 1000"
}
Else {
Write-Host "$($_.Length) is NOT greater than 1000"
}
}
或者如果你严格地想使用批处理,那么为什么要将其传递给另一个批处理文件?直接这样做:
@echo off
setlocal
for %%i in (*.zip) do (
echo %%i
if %%~zi GTR 1000 (
echo %%~zi is greater than 1000
) else (
echo %%~zi is NOT greater than 1000
)
)
答案2
您可以尝试以下方法:
- 为了接受您的参数(
%1, %2, %3, %n...
)并回应名称和大小:
@echo off && setlocal enabledelayedexpansion
if not "%~x1" == ".zip" (
set "_loops=*.zip" ) else set "_loops=%*"
set^ "_bit=is greater" && for %%i in (!_loops!) do (
if not %%~zi gtr 1000 set "_bit=!_bit: = NOT !"
echo\File %%~nxi ^| Size %%~zi !_bit! than 1000
set "_bit=is greater"
)
endlocal && goto=:EOF
- 更简单一点,还有参数:
@echo off
if not "%~x1"==".zip" (
set "_zip=*.zip") else set "_zip=%*"
for %%i in (%_zip%)do if %%~zi gtr 1000 (
echo\%%~zi is greater than 1000
)else echo\%%~zi is NOT greater
- 一个仅回应名称和大小的选项:
@echo off && setlocal enabledelayedexpansion
set^ "_bit=is greater" && for %%i in ("*.zip") do (
if not %%~zi gtr 1000 set "_bit=!_bit: = NOT !"
echo\File %%~nxi ^| Size %%~zi !_bit! than 1000
set "_bit=is greater"
)
endlocal && goto=:EOF
- 如果大于,则复制文件:
@echo off
set "_bit=is greater"
setlocal enabledelayedexpansion
for %%i in ("*.zip")do if %%~zi gtr 1000 (
copy /b "file" + "%%~fi" "%%~dpni_new%%~xi" 2>nul
echo\File %%~nxi ^| Size %%~zi !_bit! than 1000 ) else (
echo\File %%~nxi ^| Size %%~zi !_bit: = NOT ! than 1000 )
endlocal && goto=:EOF
- 如果不大于,则复制文件:
@echo off
set "_bit=is greater"
setlocal enabledelayedexpansion
for %%i in ("*.zip")do if %%~zi leq 1000 (
copy /b "file" + "%%~fi" "%%~dpni_new%%~xi" 2>nul
echo\File %%~nxi ^| Size %%~zi !_bit: = NOT ! than 1000
) else ;echo\File %%~nxi ^| Size %%~zi !_bit! than 1000
endlocal && goto=:EOF
对于 PowerShell
Get-Item "D:\Folder\*.zip"|foreach-object { if ($_.Length -gt 1000)
{ Write-Host $_.Length is greater than 1000 } else {
Write-Host $_.Length is NOT greater than 1000 }}
- 或者使用别名:
gi "D:\Folder\*.zip" | ? { if ( $_.Length -gt 1000 )
{ write-host $_.Length is greater than 1000 } else {
write-host $_.Length is NOT greater than 1000 } }