Matthew Smith
Matthew Smith

Reputation: 510

File Used In Another Process Error In Batch

I have created a program in batch that asks for a password to continue to the next part of the program. I have a file that I created which contain the password. In the program I get it to call up the contents of that text file and set that to a variable which is the 'password'... The only problem is that is I'm receiving an error saying: 'The File Is Being Used In Another Process'

This is the part of my code where I have located an error:

for /F "delims=" %%i in (Password.txt) do set content=%%i echo %content% set password123=%content%
powershell -Command $pword = read-host "Enter password" -AsSecureString ; ^ $BSTR=[System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($pword) ; ^ [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR) > .tmp.txt
set /p password=<.tmp.txt & del .tmp.txt
if %password123%=%password% goto :correct
if not %password123%=%password% goto :incorrect

Upvotes: 1

Views: 74

Answers (1)

JosefZ
JosefZ

Reputation: 30153

Bypass creating a password-containing temporary file. Parse powershell output e.g. as follows:

for /F "delims=" %%G in ('
powershell -NoProfile -Command "$pword = read-host 'Enter password' -AsSecureString ; $BSTR=[System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($pword) ; [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR)"
') do (
    set "password=%%G"
)

Also read entire if /?; use proper comparison operator ==. Use double quotes to escape possible cmd-poisonous characters like |<>& in a password

if "%password123%"=="%password%" ( goto :correct ) else goto :incorrect

To treat correctly also possible double quote(s) in a password, apply delayed expansion as follows:

SETLOCAL EnableDelayedExpansion
if "!password123!"=="!password!" ( 
  ENDLOCAL
  goto :correct
) else ( 
  ENDLOCAL
  goto :incorrect
)

Upvotes: 1

Related Questions