大家。我试图找出一种方法来读取 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()
}
答案 0 :(得分:1)
这里有几点需要注意:
Get-Childitem
而不是 dir
... | Foreach-Object { ...
而不是 ... | % ...
$_
变量,而不是在循环内循环$Destination
不再使用$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()
}
其他一些注意事项:
"C:\C:\IBM-Shortcuts\*.hod"
,其中包含太多的 C:\
。$TargetPath = Get-ChildItem "C:\IBMiACS-Shortcuts" -Filter *.hod -Recurse | % { $_.FullName }
的使用不是为 targetpath
的当前迭代设置 $Shortcutfile
,而是返回 "C:\IBMiACS-Shortcuts"
中所有文件路径的列表foreach
循环的基础知识 here