【发布时间】: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