Super User is a question and answer site for computer enthusiasts and power users. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I am using powershell and I have a shortcut to my destination directory in the current directory. I want to change the current directory to the one pointed to by the shortcut. Logically what I want to do is:

cd your-files-here.lnk

and wind up where over that points. What I get instead is:

Set-Location : Cannot find path 'your-files-here.lnk' because it does not exist.
At C:\Windows\system32\WindowsPowerShell\v1.0\Modules\pscx\Modules\CD\Pscx.CD.psm1:111 char:17
+                 Set-Location <<<<  $path -UseTransaction:$UseTransaction
    + CategoryInfo          : ObjectNotFound: (your-files-here.lnk:String) [Set-Location], ItemNotFoundException
    + FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.SetLocationCommand

I tried

ii your-files-here.lnk

But this opens an explorer window instead of changing the current directory.

share|improve this question
up vote 2 down vote accepted

You may add this to your Microsoft.PowerShell_profile.ps1 file. The cd command will then work as desired.

remove-item alias:cd -force
function cd($target)
{
    if($target.EndsWith(".lnk"))
    {
        $sh = new-object -com wscript.shell
        $fullpath = resolve-path $target
        $targetpath = $sh.CreateShortcut($fullpath).TargetPath
        set-location $targetpath
    }
    else {
        set-location $target
    }
}
share|improve this answer

Unfortunately, Windows does not make it easy to work with shortcuts. This should work:

$sh = New-Object -COM WScript.Shell
cd $sh.CreateShortcut('your-files-here.lnk').TargetPath
share|improve this answer
    
This works where the target is a conventional local path, but in at least one case, the shortcut is pointing to a UNC path. In this case, TargetPath is empty. – Matthew Scouten Feb 23 '12 at 19:08
    
That is odd, I have .lnk shortcuts to UNC paths and the .Targetpath property has the path in it. I even tried taking one and making the targetpath empty and it wouldn't save that way. – EBGreen Feb 23 '12 at 19:17
    
Never mind. I was doing something else wrong. Works fine. – Matthew Scouten Feb 23 '12 at 19:23
    
You should tell us what was wrong so future generations can benefit! – uSlackr Feb 23 '12 at 21:47
    
In short: CreateShortcut wants an absolute path. – Matthew Scouten Feb 28 '12 at 20:34

Is the shortcut a necessity?

You could use a Windows link for this. See mklink /? for more information on Windows links/junction points.

share|improve this answer
    
I am not the one who decided on shortcuts. – Matthew Scouten Feb 23 '12 at 19:33

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .