gpt4 book ai didi

powershell - Powershell-使用文件作为参数创建快捷方式

转载 作者:行者123 更新时间:2023-12-02 23:54:07 25 4
gpt4 key购买 nike

我正在尝试在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向我指出,这与计算机有关,实际上我在执行此脚本时就避免了这种情况。现在找出原因...

最佳答案

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

$Shortcut.Arguments = [string]$Arguments

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

关于powershell - Powershell-使用文件作为参数创建快捷方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50126373/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com