【问题标题】:Powershell - Create a shortcut with a file as an argumentPowershell - 使用文件作为参数创建快捷方式
【发布时间】:2018-05-02 02:34:50
【问题描述】:

我正在尝试使用 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)。我尝试使用除$Arguments 之外的其他变量名。我试过在参数声明中做[string]$Arguments,在用法中做$Arguments.ToString()

你能帮我看看我做错了什么吗?

编辑 - 感谢 TessellatingHeckler 向我指出,我实际上正在执行此脚本的计算机阻止了这种情况。现在来找出原因...

【问题讨论】:

  • 为我工作。复制您的第二个代码块,将c:\tests 更改为我计算机上存在的文件夹,然后我得到"C:\Program Files\Notepad++\Notepad++.exe" C:\tests\testfile.txt 的快捷方式。你用的是什么环境?操作系统版本、PS 版本,以及您是否在运行之间关闭/重新打开 PS 只是为了检查之前的运行是否有任何问题?
  • 好吧,那就给我上色吧。我已经在我正在处理这个脚本的计算机上关闭了 ISE / 重新启动等,但是现在在我的家用计算机上测试它确实有效。猜猜是时候找出我的主工作站和笔记本电脑(两者)中的愚蠢设置是什么导致了这种情况。感谢您对一个明显浪费的问题的帮助和耐心。

标签: powershell desktop-shortcut


【解决方案1】:

这只是发生在我身上,我发现您的帖子正在寻找解决方案(我在任何地方都找不到)。使您的线路与此等效,最终为我修复了它:

$Shortcut.Arguments = [string]$Arguments

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-04-27
    • 2012-03-30
    • 2018-10-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-12
    • 2021-10-04
    相关资源
    最近更新 更多