【发布时间】:2019-05-20 23:38:29
【问题描述】:
我正在尝试制作一个脚本,用于在桌面上创建多个可执行文件的快捷方式。因为负责创建快捷方式的代码将被多次使用,并且在其他脚本中我决定将它放入一个函数中。
逻辑很简单:
- 定义函数
- 在单独的数组中定义快捷方式的目标文件(我在示例中使用
notepad.exe和cmd.exe) - 定义快捷方式的预期路径
我正在尝试使用嵌套的 foreach 循环来遍历目标文件和快捷方式路径数组,但它没有正确生成快捷方式。也许有更好的方法来遍历我没有看到的程序(很有可能,因为我生病了并且脑雾很重)。
脚本至少可以处理一个快捷方式。
我尝试在函数之外运行函数代码。当我从数组中删除命令提示符时,记事本的快捷方式已正确创建。
function CreateShortcuts {
[CmdletBinding()]
Param(
[Parameter(Mandatory = $true, Position = 0)]
[System.String]$ShortcutPath,
[Parameter(Mandatory = $true, Position = 1)]
[System.String]$TargetFile,
[Parameter(Mandatory = $false, Position = 2)]
[System.String]$ShortcutArgs
)
$objShell = New-Object -ComObject WScript.Shell
$objShortcut = $objShell.CreateShortcut($ShortcutPath)
$objShortcut.TargetPath = $TargetFile
$objShortcut.Save()
}
$TargetFiles = "$env:SystemRoot\System32\notepad.exe", "$env:SystemRoot\System32\cmd.exe"
$ShortcutPaths = "$env:Public\Desktop\Notepad.lnk", "$env:Public\Desktop\Command Prompt.lnk"
foreach ($ShortcutPath in $ShortcutPaths) {
foreach ($TargetFile in $TargetFiles) {
CreateShortcuts -ShortcutPath $ShortcutPath -TargetFile $TargetFile
}
}
预期的输出是记事本的快捷方式和命令提示符出现在桌面上并链接到预期的程序。相反,会发生两个快捷方式链接到cmd.exe。
【问题讨论】:
-
您正在运行 CreateShortcuts 4 次,最后两次指向 cmd.exe。
-
旁注:使用 Com 对象时,请务必在使用完它们后进行清理。
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($objShell) | Out-Null; [System.GC]::Collect(); [System.GC]::WaitForPendingFinalizers(); $objShell = $null
标签: powershell foreach shortcut