AskOverflow.Dev

AskOverflow.Dev Logo AskOverflow.Dev Logo

AskOverflow.Dev Navigation

  • Início
  • system&network
  • Ubuntu
  • Unix
  • DBA
  • Computer
  • Coding
  • LangChain

Mobile menu

Close
  • Início
  • system&network
    • Recentes
    • Highest score
    • tags
  • Ubuntu
    • Recentes
    • Highest score
    • tags
  • Unix
    • Recentes
    • tags
  • DBA
    • Recentes
    • tags
  • Computer
    • Recentes
    • tags
  • Coding
    • Recentes
    • tags
Início / computer / Perguntas / 1649349
Accepted
bgoodr
bgoodr
Asked: 2021-05-16 11:41:49 +0800 CST2021-05-16 11:41:49 +0800 CST 2021-05-16 11:41:49 +0800 CST

Como criar um atalho na área de trabalho e colocado em um local específico na área de trabalho usando apenas scripts

  • 772

Eu sei como criar atalhos usando o Windows Script Host ( link ). Mas o que eu preciso é criar atalhos e colocá-los em locais específicos sem precisar usar o mouse manualmente para colocá-los. Isso é possível por meio de scripts (por exemplo, PowerShell etc.)?

A razão é que eu gosto de ter o script de configuração do Windows para que o script de configuração possa estar sob controle de alterações (por exemplo, Git).

windows-10 windows
  • 1 1 respostas
  • 597 Views

1 respostas

  • Voted
  1. Best Answer
    Ben N
    2021-05-17T12:47:49+08:002021-05-17T12:47:49+08:00

    Isso é bastante complicado porque trabalhar com exibições do Explorer como a área de trabalho requer o uso de vários objetos COM que não oferecem suporte a scripts, mas isso pode ser feito no PowerShell declarando representações .NET das funções e estruturas nativas em alguns C# incorporados. Com base neste artigo de Raymond Chen , escrevi este script:

    Param(
        [Parameter(Mandatory)][string]$ShortcutTitle,
        [Parameter(Mandatory)][int]$IconX,
        [Parameter(Mandatory)][int]$IconY,
        [Parameter(Mandatory)][string]$TargetPath,
        [Parameter()][string]$Arguments = '',
        [Parameter()][string]$WorkingDirectory = ''
    )
    
    # Declarations of COM interfaces, functions, and structures for interfacing with the shell
    Add-Type -TypeDefinition @"
    using System;
    using System.Runtime.InteropServices;
    
    [StructLayout(LayoutKind.Sequential)]
    public struct POINT {
        public int x;
        public int y;
    }
    
    [StructLayout(LayoutKind.Sequential)]
    public struct STRRET {
        int uType;
        [MarshalAs(UnmanagedType.ByValArray, SizeConst = 260)]
        byte[] cStr;
    }
    
    public class PInvoke {
        [DllImport("Shlwapi.dll")]
        public static extern int StrRetToStrW(ref STRRET pstr, IntPtr pidl, [MarshalAs(UnmanagedType.LPWStr)] ref string ppsz);
    }
    
    [ComImport]
    [Guid("6d5140c1-7436-11ce-8034-00aa006009fa")]
    [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
    public interface ComServiceProvider {
        [return: MarshalAs(UnmanagedType.IUnknown)]
        Object QueryService(ref Guid guidService, ref Guid riid);
    }
    
    [ComImport]
    [Guid("000214e2-0000-0000-c000-000000000046")]
    [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
    public interface IShellBrowser {
        IntPtr GetWindow();
        void UnusedContextSensitiveHelp();
        void UnusedInsertMenusSB();
        void UnusedSetMenuSB();
        void UnusedRemoveMenusSB();
        void UnusedSetStatusTextSB();
        void UnusedEnableModelessSB();
        void UnusedTranslateAcceleratorSB();
        void UnusedBrowseObject();
        void UnusedGetViewStateStream();
        void UnusedGetControlWindow();
        void UnusedSendControlMsg();
        [return: MarshalAs(UnmanagedType.IUnknown)]
        Object QueryActiveShellView();
        void UnusedOnViewWindowActive();
        void UnusedSetToolbarItems();
    }
    
    [ComImport]
    [Guid("1af3a467-214f-4298-908e-06b03e0b39f9")]
    [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
    public interface IFolderView2 {
        void UnusedGetCurrentViewMode();
        void UnusedSetCurrentViewMode();
        [return: MarshalAs(UnmanagedType.IUnknown)]
        Object GetFolder(ref Guid riid);
        IntPtr Item(int iItemIndex);
        int ItemCount(int uFlags);
        void UnusedItems();
        void UnusedGetSelectionMarkedItem();
        void UnusedGetFocusedItem();
        POINT GetItemPosition(IntPtr pidl);
        void UnusedGetSpacing();
        void UnusedGetDefaultSpacing();
        void UnusedGetAutoArrange();
        void UnusedSelectItem();
        void SelectAndPositionItems(int cidl, [MarshalAs(UnmanagedType.LPArray)] IntPtr[] apidl, [MarshalAs(UnmanagedType.LPArray)] POINT[] apt, int dwFlags);
        void UnusedSetGroupBy();
        void UnusedGetGroupBy();
        void UnusedSetViewProperty();
        void UnusedGetViewProperty();
        void UnusedSetTileViewProperties();
        void UnusedSetExtendedTileViewProperties();
        void UnusedSetText();
        void SetCurrentFolderFlags(int dwMask, int dwFlags);
        int GetCurrentFolderFlags();
        void UnusedGetSortColumnCount();
        void UnusedSetSortColumns();
        void UnusedGetSortColumns();
        void UnusedGetItem();
        void UnusedGetVisibleItem();
        void UnusedGetSelectedItem();
        void UnusedGetSelection();
        void UnusedGetSelectionState();
        void UnusedInvokeVerbOnSelection();
        void UnusedSetViewModeAndIconSize();
        void UnusedGetViewModeAndIconSize();
        void UnusedSetGroupSubsetCount();
        void UnusedGetGroupSubsetCount();
        void UnusedSetRedraw();
        void UnusedIsMoveInSameFolder();
        void UnusedDoRename();
    }
    
    [ComImport]
    [Guid("000214e6-0000-0000-c000-000000000046")]
    [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
    public interface IShellFolder {
        void UnusedParseDisplayName();
        void UnusedEnumObjects();
        void UnusedBindToObject();
        void UnusedBindToStorage();
        void UnusedCompareIDs();
        void UnusedCreateViewObject();
        void UnusedGetAttributesOf();
        void UnusedGetUIObjectOf();
        STRRET GetDisplayNameOf(IntPtr pidl, int uFlags);
        void UnusedSetNameOf();
    }
    "@
    
    # Find the desktop window
    $shellWindowsType = [type]::GetTypeFromCLSID('9ba05972-f6a8-11cf-a442-00a0c90a8f39')
    $shellWindows = [activator]::CreateInstance($shellWindowsType)
    $csidlDesktop = 0
    $empty = $null
    $desktopWindow = $shellWindows.FindWindowSW([ref]$csidlDesktop, [ref]$empty, 8, 0, 1)
    $shellBrowser = [ComServiceProvider].GetMethod('QueryService').Invoke($desktopWindow, @([guid]'4c96be40-915c-11cf-99d3-00aa004ae837', [guid]'000214e2-0000-0000-c000-000000000046'))
    $folderView = [IShellBrowser].GetMethod('QueryActiveShellView').Invoke($shellBrowser, @())
    # Uncheck "auto arrange icons" so icons can be moved
    [IFolderView2].GetMethod('SetCurrentFolderFlags').Invoke($folderView, @(1, 0))
    # Note how many icons were displayed before so we can know when the new one appeared
    $iconCount = [IFolderView2].GetMethod('ItemCount').Invoke($folderView, @(0))
    
    # Determine the path for the new shortcut
    $wshShell = New-Object -ComObject WScript.Shell
    $desktopPath = $wshShell.SpecialFolders('Desktop')
    $lnkPath = "$desktopPath\$ShortcutTitle.lnk"
    If (-not (Test-Path $lnkPath)) {
        # If it doesn't already exist, create it with the WScript API
        $shortcut = $wshShell.CreateShortcut($lnkPath)
        $shortcut.TargetPath = $TargetPath
        $shortcut.Arguments = $Arguments
        $shortcut.WorkingDirectory = $WorkingDirectory
        $shortcut.Save()
        # Refresh the desktop and wait for Explorer to add an icon for the new shortcut
        $desktopWindow.Refresh()
        $newIconCount = $iconCount + 1
        $tries = 0
        While ($iconCount -lt $newIconCount -and $tries -lt 30) {
            $iconCount = [IFolderView2].GetMethod('ItemCount').Invoke($folderView, @(0))
            $tries += 1
            Start-Sleep -Milliseconds 100
        }
    }
    
    # Get a representation of the folder that allows reading item names
    $shellFolder = [IFolderView2].GetMethod('GetFolder').Invoke($folderView, @([guid]'000214e6-0000-0000-c000-000000000046'))
    # Iterate over the icons to find the new one
    0..($iconCount - 1) | % {
        # Get the ID and name of this icon
        $pidl = [IFolderView2].GetMethod('Item').Invoke($folderView, @([int]$_))
        $strret = [IShellFolder].GetMethod('GetDisplayNameOf').Invoke($shellFolder, @($pidl, 0x1000))
        $name = ''
        If ([PInvoke]::StrRetToStrW([ref]$strret, $pidl, [ref]$name) -eq 0) {
            If ($name -eq $ShortcutTitle) {
                # If it's the one we made, set its position
                $point = [POINT]::new()
                $point.x = $IconX
                $point.y = $IconY
                [IFolderView2].GetMethod('SelectAndPositionItems').Invoke($folderView, @(1, [IntPtr[]]@($pidl), [POINT[]]@($point), 128))
                # No need to look at the remaining icons - exit the script
                Break
            }
        }
    }
    

    Ele usa o componente de script clássico WScript.Shellpara criar o atalho, se ainda não existir, e usa as APIs COM do shell para localizar e reposicionar o atalho.

    Por exemplo, se esse script grande foi salvo como positionedshortcut.ps1, o comando abaixo criaria um atalho um tanto bobo chamado "Friendly Shell" próximo (1000, 400) que inicia um prompt de comando com uma saudação. Se já existisse um atalho com esse nome, ele seria movido de volta para essa posição, mas não seria alterado.

    powershell -ExecutionPolicy Bypass -c .\positionedshortcut.ps1 -ShortcutTitle 'Friendly Shell' -IconX 1000 -IconY 400 -TargetPath 'C:\Windows\System32\cmd.exe' -Arguments '/k echo Hi there!'
    

    Para definir outras propriedades de atalho, manipule o $shortcutobjeto normalmente. As coordenadas para o novo $pointestão em pixels; se você precisar se adaptar a diferentes tamanhos de tela, também poderá obter a resolução da tela do script .

    • 1

relate perguntas

  • Como ativar o sensor de impressão digital no domínio e no diretório ativo do Linux

  • atalho do shell da área de trabalho no painel lateral do explorer

  • Por que não consigo enviar arquivos do Android para o Windows 10?

  • Abrir com em vários arquivos?

Sidebar

Stats

  • Perguntas 205573
  • respostas 270741
  • best respostas 135370
  • utilizador 68524
  • Highest score
  • respostas
  • Marko Smith

    Como posso reduzir o consumo do processo `vmmem`?

    • 11 respostas
  • Marko Smith

    Baixar vídeo do Microsoft Stream

    • 4 respostas
  • Marko Smith

    O Google Chrome DevTools falhou ao analisar o SourceMap: chrome-extension

    • 6 respostas
  • Marko Smith

    O visualizador de fotos do Windows não pode ser executado porque não há memória suficiente?

    • 5 respostas
  • Marko Smith

    Como faço para ativar o WindowsXP agora que o suporte acabou?

    • 6 respostas
  • Marko Smith

    Área de trabalho remota congelando intermitentemente

    • 7 respostas
  • Marko Smith

    O que significa ter uma máscara de sub-rede /32?

    • 6 respostas
  • Marko Smith

    Ponteiro do mouse movendo-se nas teclas de seta pressionadas no Windows?

    • 1 respostas
  • Marko Smith

    O VirtualBox falha ao iniciar com VERR_NEM_VM_CREATE_FAILED

    • 8 respostas
  • Marko Smith

    Os aplicativos não aparecem nas configurações de privacidade da câmera e do microfone no MacBook

    • 5 respostas
  • Martin Hope
    Saaru Lindestøkke Por que os arquivos tar.xz são 15x menores ao usar a biblioteca tar do Python em comparação com o tar do macOS? 2021-03-14 09:37:48 +0800 CST
  • Martin Hope
    CiaranWelsh Como posso reduzir o consumo do processo `vmmem`? 2020-06-10 02:06:58 +0800 CST
  • Martin Hope
    Jim Pesquisa do Windows 10 não está carregando, mostrando janela em branco 2020-02-06 03:28:26 +0800 CST
  • Martin Hope
    v15 Por que uma conexão de Internet gigabit/s via cabo (coaxial) não oferece velocidades simétricas como fibra? 2020-01-25 08:53:31 +0800 CST
  • Martin Hope
    andre_ss6 Área de trabalho remota congelando intermitentemente 2019-09-11 12:56:40 +0800 CST
  • Martin Hope
    Riley Carney Por que colocar um ponto após o URL remove as informações de login? 2019-08-06 10:59:24 +0800 CST
  • Martin Hope
    zdimension Ponteiro do mouse movendo-se nas teclas de seta pressionadas no Windows? 2019-08-04 06:39:57 +0800 CST
  • Martin Hope
    jonsca Todos os meus complementos do Firefox foram desativados repentinamente, como posso reativá-los? 2019-05-04 17:58:52 +0800 CST
  • Martin Hope
    MCK É possível criar um código QR usando texto? 2019-04-02 06:32:14 +0800 CST
  • Martin Hope
    SoniEx2 Altere o nome da ramificação padrão do git init 2019-04-01 06:16:56 +0800 CST

Hot tag

windows-10 linux windows microsoft-excel networking ubuntu worksheet-function bash command-line hard-drive

Explore

  • Início
  • Perguntas
    • Recentes
    • Highest score
  • tag
  • help

Footer

AskOverflow.Dev

About Us

  • About Us
  • Contact Us

Legal Stuff

  • Privacy Policy

Language

  • Pt
  • Server
  • Unix

© 2023 AskOverflow.DEV All Rights Reserve