Is there a way to see if *.xlsx files in a folder are password protected by reading the directory?
Example directory text file
1.xlsx
2.xlsx
3.xlsx
4.xlsx
Example results text file
1.xlsx - protected
2.xlsx
3.xlsx - protected
4.xlsx
I basically want to see which ones out of my directory are password protected without trying to open them. I am wondering if there is a directory switch. This is on a Windows machine by the way.
This will only work for OOXML files. As this kind of files are ZIP files, the first two bytes in the file are PK
unless the file is password protected.
So, assumming all the files to process are office OOXML files, let's test if the first character in the file is a P
. To capture this character, we will use a xcopy /w
, that will wait for a keypress and echo this keypress. To capture the first character, simply redirect the file as the input to the xcopy, so, the keypress will be the first character in the file. If this character is a P
the file is not password protected.
@echo off
setlocal enableextensions enabledelayedexpansion
for %%a in (*.xlsx) do (
call :isOfficeFilePasswordProtected "%%a"
if errorlevel 1 (
echo %%a
) else (
echo %%a - protected
)
)
exit /b
:isOfficeFilePasswordProtected file
if not exist "%~1" exit /b 1
if %~z1 lss 1 exit /b 1
setlocal enableextensions disabledelayedexpansion
set "id=" & for /f "delims=" %%a in ('
xcopy /l /w "%~f0" "%~f0" 2^>nul ^<"%~1"
') do if not defined id set "id=%%a"
if "%id:~-1%"=="P" ( set "exitCode=1" ) else ( set "exitCode=0" )
endlocal & exit /b %exitCode%