a program, command or batch file

advertisement
How to check in command-line if a given
file or directory is locked (used by any
process)?
But detecting if a file is being written to by another process is not difficult.
@echo off
2>nul (
>>test.txt echo off
) && (echo file is not locked) || (echo file is locked)
I use the following test script from another window to place a lock on the file.
(
>&2 pause
) >> test.txt
When I run the 2nd script from one window and then run the 1st script from a second
window, I get my "locked" message. Once I press <Enter> in the 1st window, I get the
"unlocked" message if I rerun the 1st script.
Explanation
Whenever the output of a command is redirected to a file, the file of course must be
opened for write access. The Windows CMD session will attempt to open the file, even if
the command does not produce any output.
The >> redirection operator opens the file in append mode.
So >>test.txt echo off will attempt to open the file, it writes nothing to the file
(assuming echo is already off), and then it closes the file. The file is not modified in any
way.
Most processes lock a file whenever they open a file for write access. (There are OS
system calls that allow opening a file for writing in a shared mode, but that is not the
default). So if another process already has "test.txt" locked for writing, then the
redirection will fail with the following error message sent to stderr - "The process cannot
access the file because it is being used by another process.". Also an error code will be
generated upon redirection failure. If the command and the redirection succeed, then a
success code is returned.
Simply adding 2>nul to the command will not prevent the error message because it
redirects the error output for the command, not the redirection. That is why I enclose the
command in parentheses and then redirect the error output to nul outside of the parens.
So the error message is effectively hidden, but the error code is still propagated outside of
the parens. The standard Windows && and || operators are used to detect whether the
command inside the parens was successful or failed. Presumably echo off will never
fail, so the only possible reason for failure would be the redirection failed. Most likely it
fails because of a locking issue, though technically there could be other reasons for
failure.
It is a curious "feature" that Windows does not set the %ERRORLEVEL% dynamic
variable to an error upon redirection failure unless the || operator is used. (See File
redirection in Windows and %errorlevel%). So the || operator must read the returned
error code at some low level, not via the %ERRORLEVEL% variable.
Using these techniques to detect redirection failure can be very useful in a batch context.
It can be used to establish locks that allow serialization of multiple events in parallel
processes. For example, it can enable multiple processes to safely write to the same log
file at the "same" time. How do you have shared log files under Windows?
EDIT
Regarding locked folders. I'm not sure how Windows implements this, perhaps with a
lock. But if a process has an active directory involving the folder, then the folder cannot
be renamed. That can easily be detected using
2>nul ren folderName folderName && echo Folder is NOT locked || echo
folder is LOCKED
EDIT
I have since learned that (call ) (with a space) is a very fast command that is
guaranteed to succeed with ERRORLEVEL set to 0. And (call) (without a space) is a
fast command guaranteed to fail with ERRORLEVEL 1.
So I now use the following to check if a file is locked:
2>nul (
>>test.txt (call )
) && (echo file is not locked) || (echo file is locked)
In addition to great answer from dbenham, the following form finally help me understand
used technique:
( type nul >> file.txt ) 2>nul || echo File is locked!
type nul command gives an empty output
like echo off command in orginal.
and does not affect the current echo setting
If you want to use if–then–else condition remember of correct order - success
statement (&&) is going first and alternate statement (||) is going second:
command && (echo Command is successful) || (echo Command has failed)
http://ss64.com/nt/
An A-Z Index of the Windows CMD
command line
ADDUSERS
ADmodcmd
ARP
ASSOC
ASSOCIAT
AT
ATTRIB
Add or list users to/from a CSV file
Active Directory Bulk Modify
Address Resolution Protocol
Change file extension associations•
One step file association
Schedule a command to run at a specific time
Change file attributes
b
BCDBOOT Create or repair a system partition
BCDEDIT Manage Boot Configuration Data
BITSADMIN Background Intelligent Transfer Service
BOOTCFG Edit Windows boot settings
BROWSTAT Get domain, browser and PDC info
c
CACLS
CALL
CERTREQ
CERTUTIL
CD
CHANGE
CHKDSK
CHKNTFS
CHOICE
CIPHER
CleanMgr
CLIP
CLS
CMD
CMDKEY
COLOR
COMP
COMPACT
COMPRESS
CONVERT
COPY
CSCcmd
CSVDE
Change file permissions
Call one batch program from another•
Request certificate from a certification authority
Utility for certification authority (CA) files and services
Change Directory - move to a specific Folder•
Change Terminal Server Session properties
Check Disk - check and repair disk problems
Check the NTFS file system
Accept keyboard input to a batch file
Encrypt or Decrypt files/folders
Automated cleanup of Temp files, recycle bin
Copy STDIN to the Windows clipboard
Clear the screen•
Start a new CMD shell
Manage stored usernames/passwords
Change colors of the CMD window•
Compare the contents of two files or sets of files
Compress files or folders on an NTFS partition
Compress one or more files
Convert a FAT drive to NTFS
Copy one or more files to another location•
Client-side caching (Offline Files)
Import or Export Active Directory data
DATE
DEFRAG
DEL
DELPROF
DELTREE
DevCon
DIR
DIRQUOTA
DIRUSE
DISKPART
Display or set the date•
Defragment hard drive
Delete one or more files•
Delete user profiles
Delete a folder and all subfolders
Device Manager Command Line Utility
Display a list of files and folders•
File Server Resource Manager Disk quotas
Display disk usage
Disk Administration
d
DISKSHADOW Volume Shadow Copy Service
DISKUSE Show the space used in folders
DOSKEY
Edit command line, recall commands, and create macros
DriverQuery Display installed device drivers
DSACLs
Active Directory ACLs
DSAdd
Add items to active directory (user group computer)
DSGet
View items in active directory (user group computer)
DSQuery Search for items in active directory (user group computer)
DSMod
Modify items in active directory (user group computer)
DSMove
Move an Active directory Object
DSRM
Remove items from Active Directory
e
ECHO
Display message on screen•
ENDLOCAL End localisation of environment changes in a batch file•
ERASE
Delete one or more files•
EVENTCREATE Add a message to the Windows event log
EXIT
Quit the current script/routine and set an errorlevel•
EXPAND
Uncompress CAB files
EXTRACT Uncompress CAB files
f
FC
FIND
FINDSTR
FOR /F
FOR /F
FOR
FORFILES
FORMAT
FREEDISK
FSUTIL
FTP
FTYPE
Compare two files
Search for a text string in a file
Search for strings in files
Loop command: against a set of files•
Loop command: against the results of another command•
Loop command: all options Files, Directory, List•
Batch process multiple files
Format a disk
Check free disk space
File and Volume utilities
File Transfer Protocol
File extension file type associations•
GETMAC
GOTO
GPRESULT
GPUPDATE
Display the Media Access Control (MAC) address
Direct a batch program to jump to a labelled line•
Display Resultant Set of Policy information
Update Group Policy settings
g
h
HELP
Online Help
HOSTNAME Display the host name of the computer
i
iCACLS
IF
IFMEMBER
IPCONFIG
INUSE
Change file and folder permissions
Conditionally perform a command•
Is the current user a member of a group
Configure IP
Replace files that are in use by the OS
LABEL
LOGMAN
LOGOFF
LOGTIME
Edit a disk label
Manage Performance Monitor logs
Log a user off
Log the date and time in a file
MAKECAB
MAPISEND
MBSAcli
MEM
MD
Create .CAB files
Send email from the command line
Baseline Security Analyzer
Display memory usage
Create new folders•
l
m
MKLINK
MODE
MORE
MOUNTVOL
MOVE
MOVEUSER
MSG
MSIEXEC
MSINFO32
MSTSC
Create a symbolic link (linkd) •
Configure a system device COM/LPT/CON
Display output, one screen at a time
Manage a volume mount point
Move files from one folder to another•
Move a user from one domain to another
Send a message
Microsoft Windows Installer
System Information
Terminal Server Connection (Remote Desktop Protocol)
n
NET
Manage network resources
NETDOM
Domain Manager
NETSH
Configure Network Interfaces, Windows Firewall & Remote
access
NBTSTAT Display networking statistics (NetBIOS over TCP/IP)
NETSTAT Display networking statistics (TCP/IP)
NOW
Display the current Date and Time
NSLOOKUP Name server lookup
NTBACKUP Backup folders to tape
NTDSUtil Active Directory Domain Services management
NTRIGHTS Edit user account rights
o
OPENFILES Query or display open files
p
PATH
Display or set a search path for executable files•
PATHPING Trace route plus network latency and packet loss
PAUSE
Suspend processing of a batch file and display a message•
PERMS
Show permissions for a user
PERFMON Performance Monitor
PING
Test a network connection
POPD
Return to a previous directory saved by PUSHD•
PORTQRY Display the status of ports and services
POWERCFG Configure power settings
PRINT
Print a text file
PRINTBRM Print queue Backup/Recovery
PRNCNFG Configure or rename a printer
PRNMNGR Add, delete, list printers and printer connections
PROMPT
Change the command prompt•
PsExec
Execute process remotely
PsFile
Show files opened remotely
PsGetSid
Display the SID of a computer or a user
PsInfo
List information about a system
PsKill
Kill processes by name or process ID
PsList
List detailed information about processes
PsLoggedOn Who's logged on (locally or via resource sharing)
PsLogList Event log records
PsPasswd
Change account password
PsPing
Measure network performance
PsService View and control services
PsShutdown Shutdown or reboot a computer
PsSuspend Suspend processes
PUSHD
Save and then change the current directory•
q
QGREP
Search file(s) for lines that match a given pattern
Query Process / QPROCESS Display processes
Query Session / QWinsta
Display all sessions (TS/Remote Desktop)
Query TermServer /QAppSrv List all servers (TS/Remote Desktop)
Query User
/ QUSER
Display user sessions (TS/Remote Desktop)
r
RASDIAL Manage RAS connections
RASPHONE Manage RAS connections
RECOVER Recover a damaged file from a defective disk
REG
Registry: Read, Set, Export, Delete keys and values
REGEDIT Import or export registry settings
REGSVR32 Register or unregister a DLL
REGINI
Change Registry Permissions
REM
Record comments (remarks) in a batch file•
REN
Rename a file or files•
REPLACE Replace or update one file with another
Reset Session Delete a Remote Desktop Session
RD
Delete folder(s)•
RMTSHARE Share a folder or a printer
ROBOCOPY Robust File and Folder Copy
ROUTE
Manipulate network routing tables
RUN
Start | RUN commands
RUNAS
Execute a program under a different user account
RUNDLL32 Run a DLL command (add/remove print connections)
s
SC
Service Control
SCHTASKS Schedule a command to run at a specific time
SET
Display, set, or remove session environment variables•
SETLOCAL Control the visibility of environment variables•
SETX
Set environment variables
SFC
System File Checker
SHARE
List or edit a file share or print share
ShellRunAs Run a command under a different user account
SHIFT
Shift the position of batch file parameters•
SHORTCUT Create a windows shortcut (.LNK file)
SHUTDOWN Shutdown the computer
SLEEP
Wait for x seconds
SLMGR
Software Licensing Management (Vista/2008)
SORT
Sort input
START
Start a program, command or batch file•
STRINGS Search for ANSI and UNICODE strings in binary files
SUBINACL Edit file and folder Permissions, Ownership and Domain
SUBST
Associate a path with a drive letter
SYSMON
Monitor and log system activity to the Windows event log
SYSTEMINFO List system configuration
t
TAKEOWN
TASKLIST
TASKKILL
TELNET
TIME
TIMEOUT
TITLE
TLIST
TOUCH
TRACERT
TREE
TSDISCON
TSKILL
Take ownership of a file
List running applications and services
End a running process
Communicate with another host using the TELNET protocol
Display or set the system time•
Delay processing of a batch file
Set the window title for a CMD.EXE session•
Task list with full path
Change file timestamps
Trace route to a remote host
Graphical display of folder structure
Disconnect a Remote Desktop Session
End a running process
TSSHUTDN Remotely shut down or reboot a terminal server
TYPE
Display the contents of a text file•
TypePerf Write performance data to a log file
v
VER
VERIFY
VOL
Display version information•
Verify that files have been saved•
Display a disk label•
WAITFOR
WEVTUTIL
WHERE
WHOAMI
WINDIFF
WINRM
WINRS
WMIC
WUAUCLT
Wait for or send a signal
Clear event logs, enable/disable/query logs
Locate and display files in a directory tree
Output the current UserName and domain
Compare the contents of two files or sets of files
Windows Remote Management
Windows Remote Shell
WMI Commands
Windows Update
XCACLS
XCOPY
::
Change file and folder permissions
Copy files and folders
Comment / Remark•
w
x
Commands marked • are Internal commands only available within the CMD shell.
All other commands (not marked with •) are external commands.
External commands may be used under the CMD shell, PowerShell, or directly from
START-RUN.
See also: a categorized list of Windows CMD commands
Microsoft Help pages: XP , 2003 Server, 2008 Server, Windows 7/Server 2012 /
Technology
Discussion forum
Links to other sites, books etc...
How to copy “in use” files through batch
file in Windows 7
You want a utility that supports Volume Shadow Copy, e.g hobocopy.
If another application is using a file in a way that it does not allow concurrent access (such as
without FILE_SHARE_READ sharing mode), you can only use /C option to "Continues copying
even if errors occur."
To copy locked files ("currently in ise"), you may need to use programs:
0) Hobocopy ( someone said it to be deprecated; Also, i found a GUI version of HoboCopy, but i
cant found out how to work with it..)
1) Try Unlocker. After installation, right click on the file, then Copy.
2) http://sourceforge.net/projects/robocoprobocopy/files/latest/download (set options)
3) http://tinyapps.org/blog/windows/201303240715_copy_in_use_files_from_cli.html
4) in C:\WINDOWS\system32 open ntbackup.exe (after backup, while RESTORING, you can
choose "restore to single folder")
5) CObian Backup - http://www.cobiansoft.com/cobianbackup.htm ( i couldnt copy some files)
6) http://www.interworks.com/blogs/jvalente/2009/08/06/how-copy-or-back-file-if-use-orlocked-windows
7) Free trial of - ViceVersa ( http://www.tgrmn.com/web/download.htm )
8) http://www.youtube.com/watch?v=7eQ9LaBMGhs
9) http://answers.microsoft.com/en-us/windows/forum/windows_7-files/the-action-cant-becompleted-because-the-file-is/381e9f29-50a5-4fa3-b9f2-7b3389293063
10) http://forums.techguy.org/8344322-post7.html
Download