【问题标题】:Read from .lnk file and delete when necessary从 .lnk 文件中读取并在必要时删除
【发布时间】:2015-04-15 10:57:50
【问题描述】:

我想知道在满足特定条件时是否可以批量删除.lnk文件。

例如,假设我有以下文件: %userprofile%\Microsoft\Windows\Start Menu\Programs\Startup\Software.lnk 这个链接文件实际上指向 C:\Windows\System32\calc.exe

应删除指向 calc.exe 而不是 software.exe 的任何 .lnk 文件。

如果有人有想法,不胜感激。

【问题讨论】:

  • 不幸的是,cmd 中没有内置命令可以为您提供 lnk 的目标。您必须使用某种批处理和 Powershell/VBS 的混合体。这篇文章应该对您有所帮助:stackoverflow.com/questions/19653707/…
  • @MichaelS 啊,但是there is,如果您将通过wmic 的WMI 查询算作内置命令。答案即将到来。

标签: batch-file


【解决方案1】:

您可以使用wmic 获取快捷方式文件的目标。

for %%I in (shortcut.lnk) do set "shortcut=%%~fI"
wmic path win32_shortcutfile where "name='%shortcut:\=\\%'" get target /format:list | find "="

... 将检索目标。如果您只想在目标以calc.exe 结尾时采取行动,只需将find 切换为findstr 并使用条件执行。

for %%I in (shortcut.lnk) do set "shortcut=%%~fI"
wmic path win32_shortcutfile where "name='%shortcut:\=\\%'" get target | findstr /i "\<calc.exe *$" && (
    del "%shortcut%"
)

如果你想循环访问一个目录中的所有快捷方式文件,只需将整个文件包含在for 循环中并使用延迟扩展。

@echo off
setlocal

for %%I in (*.lnk) do (
    rem // get full path of shortcut target
    set "target=%%~fI"

    rem // Because %target% was defined within this parenthetical code block,
    rem // you must use delayed expansion to retrieve it.

    setlocal enabledelayedexpansion
    wmic path win32_shortcutfile where "name='!target:\=\\!'" get target | findstr /i "\<calc.exe *$" >NUL && (
        echo %%~nxI points to calc.exe.
        >>out.log echo Deleting %%~fI
        del "%%~fI"
    )
    endlocal
)

\&lt;findstr正则表达式中的单词边界。其余基于this answer。)

【讨论】:

  • 非常好,谢谢罗霍!我遇到了 2 个小问题: 1) 我不知道快捷方式文件的名称,所以我尝试使用 *.lnk,但它不起作用。 2)如果它删除了任何东西,我想写一个日志文件,所以我附加了>>out.log,但日志文件是空的......谢谢!
  • @Jeremy 更新了答案。如果我的回答有帮助,请考虑将其标记为已接受。 See this page 解释为什么这很重要。欢迎来到 Stack Exchange!
  • 效果很好。谢谢 rojo 并感谢您的欢迎!
  • 嗨 Rojo,我遇到了问题。我想将您的脚本合并到我正在使用的另一个脚本中,但我多次收到此消息“没有可用的实例”并且没有任何内容被删除。唯一不同的是,在你的脚本之前我添加了“cd %AllUsersProfile%”,然后(在最后一个“)”之后)我做了另一个“setlocal enableextensions”,因为我还需要删除其他文件。有什么想法吗?
  • No instance(s) available 是当"name='filename'" 与现有路径\\to\\file 不匹配时从wmic 行生成的消息。我猜!target! 变量在该行之前被破坏了。尝试转向echo on,看看你是否能确定何时发生这种情况。
【解决方案2】:

检查shortcutJS.bat(它是批处理/jscript 混合,应使用.bat 扩展名保存)

您可以使用-examine 开关:

shortcutjs.bat -examine "C:\Users\user\Desktop\some.lnk"| find /i "calc.exe" &&(
    del /q /f "C:\Users\user\Desktop\some.lnk"
)

【讨论】:

    猜你喜欢
    • 2012-03-25
    • 2010-09-28
    • 2018-02-14
    • 2013-03-23
    • 2014-12-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多