PowerShell может создать ярлык без имени - PullRequest
0 голосов
/ 22 октября 2018

Это намеренно, что можно создать ярлык без имени?(С помощью графического интерфейса это невозможно)

enter image description here

Я не могу установить горячую клавишу для ярлыка URL, хотя это возможно с помощью графического интерфейса пользователя.Это ошибка или намеренная ошибка?

Код в основном такой же, как в New-Shortcut

Вывод на консоль:

FullName         : C:\Stuff\.lnk    
Arguments        :
Description      :
Hotkey           :
IconLocation     : ,0
RelativePath     :
TargetPath       : C:\WINDOWS\explorer.exe
WindowStyle      : 0
WorkingDirectory :

Это моя функция:

function New-Shortcut {
param 
(
    # Full path of the shortcut
    [Parameter(Mandatory=$true)]
    [System.IO.FileInfo] $FullPath,
    # Path to the target
    [Parameter(Mandatory=$true)]
    [string] $TargetPath,
    # Arguments for the shortcut
    [Parameter(Mandatory=$false)]
    [string] $Arguments = $null,
    # Description if needed
    [Parameter(Mandatory=$false)]
    [string] $Description = $null,
    # Hotkey if needed
    [Parameter(Mandatory=$false)]
    [string] $HotKey = $null,
    # Working directory if it differs from the shortcut directory
    [Parameter(Mandatory=$false)]
    [string] $WorkingDirectory = $null,
    # Windows style (minimized, maximized, ...)
    [Parameter(Mandatory=$false)]
    [int] $WindowStyle = $null,
    # Path to an icon if needed
    [Parameter(Mandatory=$false)]
    [string] $IconPath = $null,
    # Run as admin configuration
    [Parameter(Mandatory=$false)]
    [switch] $RunAsAdmin  = $null
)

Write-Debug "Check if '$FullPath' is valid ([character]:[\[character/digit]+]* + [.lnk | .url]."
if (!($FullPath.Extension -match "(\.lnk|\.url)"))
{
    Write-Debug "'$FullPath' is no valid 'lnk' or 'url' shortcut."
    Write-Error -Message "'$FullPath' not valid (no valid shortcut type)." -Category InvalidArgument `
                -CategoryTargetName $FullPath -CategoryTargetType $FullPath.GetType() `
                -ErrorId "NoValidShortcutPath" -ErrorAction Stop
}
Write-Debug "'$FullPath' is a valid 'lnk' or 'url' shortcut."

# Define Shortcut Properties
$WshShell = New-Object -ComObject WScript.Shell
$Shortcut = $WshShell.CreateShortcut($FullPath)

$Shortcut.TargetPath = $TargetPath

# Create directory for shortcut if it not exist
if(!(Test-Path $FullPath.Directory))
{
    Write-Verbose ("Directory '{0}' does not exist, creating it..." -f $FullPath.Directory)
    New-Item -Path $FullPath.Directory -ItemType Directory | Out-Null
}

if ($FullPath.Extension -eq ".url")
{
    Write-Verbose "Creating new shortcut '$FullPath' pointing at '$TargetPath'."
    $Shortcut.Save()
    Write-Debug "Shortcut '$FullPath' pointing at '$TargetPath' created!"
    return $Shortcut
}

$Shortcut.Arguments = $Arguments
$Shortcut.Description = $Description
$Shortcut.WorkingDirectory = $WorkingDirectory
$Shortcut.WindowStyle = $WindowStyle
$Shortcut.HotKey = $HotKey

If ($IconPath)
{
    Write-Debug "Set icon to path '$IconPath'..."
    $Shortcut.IconLocation = $IconPath 
    Write-Debug "Icon path set."
}

Write-Verbose "Creating new shortcut '$FullPath' pointing at '$TargetPath'."
$Shortcut.Save()
Write-Debug "Shortcut '$FullPath' pointing at '$TargetPath' created!"

if ($RunAsAdmin)
{
    $bytes = [System.IO.File]::ReadAllBytes($FullPath)
    $bytes[0x15] = $bytes[0x15] -bor 0x20 #set byte 21 (0x15) bit 6 (0x20) ON
    [System.IO.File]::WriteAllBytes($FullPath, $bytes)
}

return $Shortcut
}

По крайней мере, я хочу, чтобы мой первый вопрос был опубликован.

Вот мой модульный тест, адаптированный к ситуации, в которой я могу создать ярлыкбез имени:

New-Shortcut -FullPath "C:\tmp\.lnk" -TargetPath "explorer.exe" -Verbose | 
            Should be $true #Should throw "'$invalidPath' not valid (no valid shortcut type)."
            #Test-Path $invalidPathIsNotInvalid | Should Be $false

Из-за моего испытания я вступил в борьбу, которую я пытался объяснить здесь.Но, как сказал LotPings, похоже, что ярлык называется «.lnk», что необычно, но действительно.

Похоже, он уже ответил на мой вопрос:)

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...