我的目标是编写一个简单的 Powershell 脚本,该脚本将采用一个强制参数,该参数必须是快捷方式 (.lnk) 文件的完整文件路径,然后该脚本将解析快捷方式的目标项(文件或目录)并将其复制到脚本的当前工作目录中。
我发现的问题是在测试其目标项指向路径中包含表情符号的文件或文件夹的快捷方式时,例如:
"C:\Movies\• Unidentified\[????????]\Amor, curiosidad, prozak y dudas (2001)\File.mkv
"
首先我尝试过复制项目cmdlet,之后我尝试使用 Windows Shell 脚本中的 Shell.NameSpace + Folder.CopyHere() 方法,如本示例所示:
https://stackoverflow.com/a/33760315/1248295 https://stackoverflow.com/a/33760315/1248295
我最终假装在这个脚本中使用了这种方法,而不是复制项目cmdlet,因为它显示默认的文件进度 UI,因此我更喜欢它。
请注意,我对 PowerShell 的经验不是很丰富,但在这两种情况下复制项目cmdlet 和 CopyHere 方法执行时不会给出任何异常消息,它只是不执行文件复制操作。
如果快捷方式的目标项目的项目路径不包含表情符号字符,则它可以正常工作。
我不确定这是否是某种编码问题。我的默认操作系统编码是 Windows-1252。
我做错了什么以及如何解决这个问题?
# Takes 1 mandatory argument pointing to a shortcut (.lnk) file,
# resolves the shortcut's target item (a file or directory),
# and copies that target item to the specified destination folder
# using Windows default IFileOperation progress UI.
# - File copy method took from here:
# https://stackoverflow.com/a/33760315/1248295
# - "Shell.NameSpace" method and "Folder" object Docs:
# https://learn.microsoft.com/en-us/windows/win32/shell/shell-namespace
# https://learn.microsoft.com/en-us/windows/win32/shell/folder
param (
[Parameter(
Position=0,
Mandatory,
ValueFromPipeline,
HelpMessage="Enter the full path to a shortcut (.lnk) file.")
] [string] $linkFile = "",
[Parameter(
Position=1,
ValueFromPipeline,
HelpMessage="Enter the full path to the destination folder.")
] [string] $destinationFolder = $(Get-Location)
)
$wsShell = New-Object -ComObject WScript.Shell
$shellApp = New-Object -ComObject Shell.Application
$targetItem = $wsShell.CreateShortcut($linkFile).TargetPath
Write-Host [i] Link File..: ($linkFile)
Write-Host [i] Target Item: ($targetItem)
Write-Host [i] Destination: ($destinationFolder)
Write-Host [i] Copying target item to destination folder...
$shellApp.NameSpace("$destinationFolder").CopyHere("$targetItem")
Write-Host [i] Copy operation completed.
#[System.Console]::WriteLine("Press any key to exit...")
#[System.Console]::ReadKey($true)
Exit(0)
UPDATE
我把所有这些都放在param块并且没有任何改变:
[Text.Encoding] $encoding = [Text.Encoding]::UTF8
[console]::InputEncoding = $encoding
[console]::OutputEncoding = $encoding
$OutputEncoding = $encoding
$PSDefaultParameterValues['Out-File:Encoding'] = $encoding
$PSDefaultParameterValues['*:Encoding'] = $encoding