问题
In powershell, you use cd dir
to go into the directory dir
.
But if dir
is a shortcut to a directory, cd dir
and cd dir.lnk
both give an error, saying that the directory doesn't exist.
So how do I follow that shortcut?
(In Linux cd dir
just works. In Windows, I've got no idea)
回答1:
Using the shell com-object, you can get the target path and from there, do what you wish. Get-ShortcutTargetPath
function Get-ShortcutTargetPath($fileName) {
$sh = New-Object -COM WScript.Shell
$targetPath = $sh.CreateShortcut($fileName).TargetPath
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($sh) | Out-Null
return $targetPath
}
$file = 'Path\to\Filename.lnk'
$TargetPath = Get-shortcutTargetPath($file)
if (Test-Path -PathType Leaf $TargetPath) {
$TargetPath = Split-Path -Path $TargetPath
}
Set-Location $TargetPath
回答2:
In Windows 10 cd directory_name or cd dir* if you only want part of the name assuming no other directories start with the same dir*.
来源:https://stackoverflow.com/questions/46276418/how-to-follow-a-shortcut-in-powershell