Пакетный файл - удаление ярлыка с рабочего стола ALLUSERS

49411
Damien

В Vista / 7, если я пытаюсь удалить ярлык с помощью следующей команды -:

del "%allusersprofile%\Desktop\MyShortcut.lnk" 

... Windows видит эту папку как пустую и не удаляет файл.

Переменная среды «allusersprofile» указывает на «C: \ ProgramData», однако «Рабочий стол» на самом деле является мягкой символической ссылкой на папку C: \ Users \ Public \ Desktop.

Проблема заключается в том, что эти программные ссылки являются просто ярлыками Windows Explorer и не распознаются командами cmd или пакетными файлами.

Единственное решение, которое я вижу, - это сделать следующее:

XP:

del "%allusersprofile%\Desktop\MyShortcut.lnk" 

Vista / 7:

del "%PUBLIC%\Desktop\MyShortcut.lnk" 

Есть ли общее решение для обеих ОС?

4
Я не знаю ни одного такого способа из-за изменений структуры файлов между XP и Vista / 7. Одним из способов достижения этой функциональности в скрипте является получение версии ОС с использованием `ver`, выполнение ее через серию проверок` if` / `else`, а затем использование` goto` для запуска соответствующей команды. Garrett 12 лет назад 2

4 ответа на вопрос

5
PenguinCoder

As stated by Garrett in comments of this question, the only solution I see is as follows:

SET Version=XP VER | FINDSTR /IL "6.1." > NUL IF %ERRORLEVEL% EQU 0 SET Version=7 IF %Version% EQU 7 ( del "%PUBLIC%\Desktop\MyShortcut.lnk" ) IF %Version% EQU XP ( del "%allusersprofile%\Desktop\MyShortcut.lnk" ) 

One might note that according to this StackOverflow question, and a blog post by Raymond Chen, a dir of %allusersprofile%\Desktop\<directory> should give the proper results on both XP and 7, however in my experience it does not.

2
Slicktrick

You didn’t specify a type of script (VBS vs. BAT), but here is a VB script that is system agnostic. Not my script, I pulled it from this Microsoft site. According to that page it’s been verified to work on Windows 2000, XP, Vista, and 7.

'''''''''''''''''''''''''''''''''' ' ' This VB script removes the requested desktop shortcuts ' ' Change only the file name (test.lnk) ' ' Script created by Holger Habermehl. October 23, 2012 '''''''''''''''''''''''''''''''''' Set Shell = CreateObject("WScript.Shell") Set FSO = CreateObject("Scripting.FileSystemObject") DesktopPath = Shell.SpecialFolders("Desktop") FSO.DeleteFile DesktopPath & "\test.lnk" 

EDIT

The above code will look at the specific user's desktop (i.e. Username "john" logs in, the code will look at "C:\Users\john\Desktop\" or "C:\Documents and Settings\john\Desktop"). If you want to check the public desktop, then change the line that reads

DesktopPath = Shell.SpecialFolders("Desktop") 

to

DesktopPath = Shell.SpecialFolders("AllUsersDesktop") 

But note that depending on the user's privileges and when you run the script, they may get a UAC box asking to sign in as an admin on Windows Vista/7. I'd run the script in a GPO as a computer startup script.

0
Gooofy

Good advice here which helped with my scenario.

  1. I created a batch file to remove the short-cuts

fixme.bat contains the following 3 lines:

del "C:\Users\Public\Desktop\gVim 7.4.lnk" del "C:\Users\Public\Desktop\Cygwin64 Terminal.lnk" pause 
  1. Right-mouse click on the batch file to pop-up the menu.

  2. Select "Run Elevated Privileges", enter your password.

Success.

You may also try "Run as administrator".

Good luck!

Привет Gooofy, спасибо за ответ. Охватывает ли это как XP, так и Vista / 7, как указано в исходном вопросе? bertieb 8 лет назад 1
0
theGiantMidget 2000

Это работает в win7.

Я не смог попробовать это в XP, но я думаю, что это должно работать.

 del "%HOMEDRIVE%%HOMEPATH%\Desktop\test.lnk" 

Сохраните его как командный файл и запустите его как обычно. Если ваша учетная запись не имеет прав администратора, вам может потребоваться щелкнуть правой кнопкой мыши и выбрать «Запуск от имени администратора». Вы также можете открыть cmd и просто ввести его в качестве команды.

Эта команда удаляет другой файл ... `% HOMEDRIVE %% HOMEPATH%` не совпадает с `% allusersprofile%` DavidPostill 7 лет назад 1
Это все еще идет на рабочий стол, хотя. `% allusersprofile%` отличается, но я подумал, что% HOMEDRIVE %% HOMEPATH% `может сработать для того, что он спрашивал. @DavidPostill theGiantMidget 2000 7 лет назад 0
Один - это рабочий стол для всех пользователей, а другой - для конкретного пользователя. Содержимое объединяется для создания рабочего стола для вошедшего в систему пользователя. DavidPostill 7 лет назад 1