阅读目录 + 使用 PowerShell 创建快捷方式

时间:2021-07-28 21:08:50

标签: powershell shortcut

大家。我试图找出一种方法来读取 Windows 中目录的内容并查找具有特定文件扩展名的文件(在本例中为“.hod”),然后将每个文件的快捷方式创建到“C:\Users”中\公共\桌面。'

以下是我迄今为止在 PowerShell 中测试过的示例(我知道它看起来非常糟糕)。我很感激任何输入。谢谢。

$shortcutfiles = dir "C:\C:\IBM-Shortcuts\*.hod"
$DestinationDir = "C:\Users\Public\Desktop"
foreach ($shortcutfile in $shortcutfiles ) {
$TargetPath = Get-ChildItem "C:\IBMiACS-Shortcuts" -Filter *.hod -Recurse | % { $_.FullName }
$BaseName = Get-ChildItem "C:\IBMiACS-Shortcuts" -Filter *.hod -Recurse | % { $_.BaseName }
$WshShell = New-Object -comObject WScript.Shell
$Shortcut = $WshShell.CreateShortcut("$DestinationDir" & "$BaseName"+lnk)
$Shortcut.TargetPath = "$TargetPath"
$Shortcut.Save()
}

1 个答案:

答案 0 :(得分:1)

这里有几点需要注意:

  • 使用完整的 cmdlet 名称而不是别名,这是为了清楚起见。
    • Get-Childitem 而不是 dir
    • ... | Foreach-Object { ... 而不是 ... | % ...
  • 仅迭代文件夹内容一次并在循环内引用 $_ 变量,而不是在循环内循环
  • 如果一个变量只被使用一次,那么不要费心将它存储在它自己的变量中
    • $Destination 不再使用
  • 按照基本格式对代码进行缩进 rules
  • 正如@mklement0 提到的,在管道之前只执行一次 $WshShell = New-Object -comObject WScript.Shell 是值得的。
$WshShell = New-Object -comObject WScript.Shell

Get-ChildItem "C:\IBM-Shortcuts\*.hod" | Foreach-Object {
    $Shortcut = $WshShell.CreateShortcut("C:\Users\Public\Desktop\$($_.BaseName).lnk")
    $Shortcut.TargetPath = $_.FullName
    $Shortcut.Save()
}

其他一些注意事项:

  • 在第 1 行,您引用了 "C:\C:\IBM-Shortcuts\*.hod",其中包含太多的 C:\
  • 您对 $TargetPath = Get-ChildItem "C:\IBMiACS-Shortcuts" -Filter *.hod -Recurse | % { $_.FullName } 的使用不是为 targetpath 的当前迭代设置 $Shortcutfile,而是返回 "C:\IBMiACS-Shortcuts" 中所有文件路径的列表
  • 了解 foreach 循环的基础知识 here