请原谅我对.bat文件的无知,但我不习惯它们。我要做的是得到一个。bat文件来搜索特定的文件名,然后还执行该。txt文件的搜索,以找到该文件的特定所有者。如果所有匹配,将该文件移到另一个目录。
这可能吗?我该如何开始?我熟悉的编程与JS,但这是所有。从来没有创建过批处理文件,但总是听到他们创造奇迹。
*****这是我收集到目前为止…不能让这个工作。您还会注意到,我不确定如何告诉它搜索文件的特定所有者…ie (Jane Doe)和文件名(Testing),如果全部匹配,移动到另一个目录*****
@echo OFF
setlocal enableextensions disabledelayedexpansion
set "source=C:Usersandrew.mossDesktopTest1"
set "target=C:Usersandrew.mossDesktopTest2"
set "searchString=Testing"
set "found="
for /f "delims=" %%a in ('
findstr /m /i /l /c:"%Testing%" "%C:Usersandrew.mossDesktopTest1%" 2^>nul
') do (
if not defined found set "found=1"
echo move "%%a" "%C:Usersandrew.mossDesktopTest2%"
)
if not defined found (
echo Failure
)
pause
我从头开始提供一个我认为适合您需求的脚本,所以它是:
@echo off
setlocal EnableExtensions DisableDelayedExpansion
rem // Define constants here:
set "_SOURCE=." & rem // (path to directory where to search for files)
set "_TARGET=.." & rem // (path to directory where to move found files)
set "_PATTERN=test.*" & rem // (file name pattern; may contain wild-cards)
set "$RECURSIVE=#" & rem // (set to non-empty value to search sub-dir.s)
set "$OWNER=aschipfl" & rem /* (login name of owner; may be preceded with
rem domain and a backslash, like `DOMAIN`) */
rem // Predefine recursive option:
if defined $RECURSIVE set "$RECURSIVE=/S"
rem // Split domain off of owner:
for /F "tokens=1-2 delims= eol= " %%C in ("%$OWNER%") do (
if not "%%D"=="" (
set "$DOMAIN=%%C"
set "$OWNER=%%D"
) else set "$DOMAIN="
)
rem /* Loop through all matching files in the given location found by `dir`;
rem the `/Q` option lets include domain/owner in the output; `findstr`
rem filters out lines beginning with ` `, hence headers and footers: */
pushd "%_SOURCE%" || exit /B 1
for /F "tokens=4,*" %%E in ('
dir /Q /N /-C %$RECURSIVE% /A:-D "%_PATTERN%" ^
^| findstr /V /B /C:" "
') do (
rem // Reset flag:
set "FLAG="
rem // Check whether certain domain has been specified:
if defined $DOMAIN (
rem // Domain specified, so domain and owner must match:
if /I "%%E"=="%$DOMAIN%%$OWNER%" (
rem // Match encountered, hence set flag:
set "FLAG=#"
)
) else (
rem // Domain not specified, so owner must match only:
set "OWN=%%E"
setlocal EnableDelayedExpansion
rem // Dismiss domain of currently iterated file item:
set "OWN=!OWN:*=!"
rem // Check whether owner matches:
if "!OWN!"=="%$OWNER%" (
endlocal
rem // Match encountered, hence set flag:
set "FLAG=#"
) else endlocal
)
rem // Check whether flag is set:
if defined FLAG (
rem /* Flag is set, hence do something with current file item;
rem here, the file is moved to the given target directory;
rem remove the `if exist` query to force overwriting: */
if not exist "%_TARGET%%%~nxF" (
> nul move /Y "%%~fF" "%_TARGET%"
)
)
endlocal
)
popd
endlocal
exit /B
有许多解释性注释。核心命令是dir /Q
,它能够返回文件的所有者。请注意,它返回以域名和反斜杠开头的登录名,例如DOMAINjdoe
。因此,您需要在脚本中以这种方式指定所有者。您可以省略域前缀,在这种情况下,域将被忽略。但是,您不能指定显示用户名,例如Jane Doe
,因为这将无法识别。
请注意,如果给定的登录名包含空格,脚本将失败。