我想编写一个 .bat 文件,如果上述文件夹或文件均未打开,则打开多个文件夹;如果其中任何一个文件夹在 Windows 资源管理器中打开或正在由 Windows 运行,则关闭所有多个文件夹。
我认为我可以用上面提到的方法解决条件问题cmd.exe:复杂条件?发布,但我无法让它满足我所尝试过的一切需求。
set COND=
if COND1 set COND=1
if COND2 set COND=1
if defined COND ...
我不确定如何检查 Windows 资源管理器中打开了哪些文件夹,但我找到了关闭解决方案 cmd:如果尚未打开,则打开文件夹的资源管理器窗口但经过多次尝试后,我仍然无法找出正确的逻辑。
有没有更简单的方法来检查文件夹是否打开,或者进程是否运行?
答案1
下面是一个批处理文件,您可以将用双引号括起来并用逗号分隔的值设置为要在批处理变量中打开的文件夹的路径(即<"FolderPathValue1">,<"FolderPathValue1">
)SET oPenArray=
。
这确实使用了一些动态 PowerShell 逻辑来获取打开的文件夹并将其放入文件中,以便批处理FOR
逻辑可以迭代并相应地使用条件逻辑。
如果你希望更好地理解 PowerShell 逻辑,请阅读适用的支持资源链接;否则,您只需要关心将文件夹路径放入SET oPenArray=
变量中。
批处理脚本
@ECHO OFF
SET oPenArray="C:\Folder\Test","C:\Folder123\Prod"
SET "tmpFile=%temp%\oFolder.lst"
IF EXIST "%tmpFile%" DEL /Q /F "%tmpFile%"
CALL :PowerShell
CD /D "%PowerShellDir%"
Powershell -ExecutionPolicy Bypass -Command "& '%PSScript%'"
FOR /F "USEBACKQ TOKENS=*" %%A IN ("%tmpFile%") DO (
FOR %%B IN (%oPenArray%) DO (
IF /I NOT [%%~A]==[%%~B] EXPLORER "%%~B"
)
)
EXIT
:PowerShell
SET PowerShellDir=C:\Windows\System32\WindowsPowerShell\v1.0
SET PSScript=%temp%\~tmpOpenFolders.ps1
IF EXIST "%PSScript%" DEL /Q /F "%PSScript%"
ECHO $app = New-Object -COM 'Shell.Application' >> "%PSScript%"
ECHO $t = $app.Windows() ^| Select-Object LocationURL >> "%PSScript%"
ECHO $x = $t ^| %% {[string]$_.LocationURL -Replace "file:////", ""} >> "%PSScript%"
ECHO $folders = $x.Replace("file:///", "").Replace("/","\").Replace("%%20"," ") >> "%PSScript%"
ECHO $folders ^| Out-File "%tmpFile%" -Encoding "ascii" -Append >> "%PSScript%"
GOTO :EOF
支持资源
- 为/F
FOR /?
tokens=x,y,m-n - specifies which tokens from each line are to be passed to the for body for each iteration. This will cause additional variable names to be allocated. The m-n form is a range, specifying the mth through the nth tokens. If the last character in the tokens= string is an asterisk, then an additional variable is allocated and receives the remaining text on the line after the last token parsed. usebackq - specifies that the new semantics are in force, where a back quoted string is executed as a command and a single quoted string is a literal string command and allows the use of double quotes to quote file names in file-set.
- ForEach 对象
标准别名对于 Foreach 对象:'
%
' 符号,ForEach - 输出文件
- 称呼