Powershell - 创建一个以文件作为参数的快捷方式

时间:2018-05-02 02:34:51

标签: powershell desktop-shortcut

我试图在PowerShell脚本中自动创建Windows中的快捷方式。我创建了一个函数来使这更容易,因为我需要在脚本运行时在几个地方传递类似的快捷方式,但是每当我尝试传入一个参数来打开一个特定的文件时,Arguments字段就会被删除。

如果我这样做:

Function MakeAShortcut($RunPath, $Arguments, $ShortcutName, $ShortcutLocation){
    $WScriptShell = New-Object -ComObject WScript.Shell
    $Shortcut = $WScriptShell.CreateShortcut($ShortcutLocation + $ShortcutName + '.lnk')
    $Shortcut.Targetpath = -join($RunPath,"\Notepad++.exe")
    $Shortcut.Arguments = "C:\tests\testfile.txt"
    $Shortcut.WorkingDirectory = $RunPath
    $Shortcut.IconLocation = -join($RunPath,"\Notepad++.exe",", 0")
    $Shortcut.Save()

    Write-Host "`nShortcut created at "$ShortcutLocation$ShortcutName'.lnk'
}

$DefaultFileName = "C:\tests\testfile.txt"
$Runapppath = "C:\Program Files\Notepad++"

MakeAShortcut $Runapppath $DefaultFileName "ShortcutTEST" "c:\tests\"

然后脚本将输出正确运行程序的快捷方式(在本例中为Notepad ++)和使用快捷方式加载的默认文件(testfile.txt)。

但是,如果我这样做:

Function MakeAShortcut($RunPath, $Arguments, $ShortcutName, $ShortcutLocation){
    $WScriptShell = New-Object -ComObject WScript.Shell
    $Shortcut = $WScriptShell.CreateShortcut($ShortcutLocation + $ShortcutName + '.lnk')
    $Shortcut.Targetpath = -join($RunPath,"\Notepad++.exe")
    $Shortcut.Arguments = $Arguments
    $Shortcut.WorkingDirectory = $RunPath
    $Shortcut.IconLocation = -join($RunPath,"\Notepad++.exe",", 0")
    $Shortcut.Save()

    Write-Host "`nShortcut created at "$ShortcutLocation$ShortcutName'.lnk'
}

$DefaultFileName = "C:\tests\testfile.txt"
$Runapppath = "C:\Program Files\Notepad++"

MakeAShortcut $Runapppath $DefaultFileName "ShortcutTEST" "c:\tests\"

然后它只是完全丢弃$Shortcut.Arguments字段(无论我将$DefaultFileName作为变量还是显式字符串提供)并创建仅运行程序的快捷方式(在本例中为Notepad ++)

我尝试过三次引用传递到$DefaultFileName位置的值。我曾尝试强调冒号等字符。如果我另外传入一些内容(例如:$Shortcut.Arguments = '-noPlugins ' + $Arguments它只会追加添加(-noPlugins)。我尝试使用除{{之外的其他变量名。 1}}。我尝试在参数声明中使用$Arguments并在使用中尝试[string]$Arguments

你能帮我知道我做错了吗?

编辑 - 感谢TessellatingHeckler向我指出,这与我实际上正在执行此脚本的计算机有关,这阻止了这一点。现在找出原因......

1 个答案:

答案 0 :(得分:0)

这只是对我而言,我发现您的帖子正在寻找解决方案(我在任何地方都找不到)。使您的行与此等效,最终为我解决了此问题:

$Shortcut.Arguments = [string]$Arguments

因此出于某种原因,需要使用强制类型转换为变量分配正确的类型。