Search code examples
powershellsymlink

PowerShell dir show all symlink targets like Command Prompt


When you use dir in Command Prompt cmd.exe you get

C:\path\to\somewhere> dir
2022-10-03  20:17    <DIR>          .
2022-10-03  19:54    <DIR>          ..
2022-10-03  20:16    <SYMLINKD>     link [..\target\]

But when you try the same in PowerShell you get

PS C:\path\to\somewhere> dir
Mode                 LastWriteTime         Length Name
----                 -------------         ------ ----
d----l        2022-10-03     20:16                link

How do you make PowerShell also show all the link targets inside a directory like Command Prompt?


Solution

  • It depends on the Powershell version. Remember that dir is just an alias for Get-ChildItem, and pre-PS 5, GCI simply didn't include properties for linktype or target.

    For PS 5+, this works:

    Get-ChildItem -Path "C:\temp\" -Force |
       Where-Object { $_.LinkType -ne $null } |
       ft FullName,Attributes,Linktype,Target
    
    FullName                  Attributes LinkType     Target
    --------                  ---------- --------     ------
    C:\temp\hard Directory, ReparsePoint SymbolicLink {C:\Temp\temp\text.txt}
    C:\temp\j    Directory, ReparsePoint Junction     {c:\temp\tmp\actss}
    C:\temp\soft Directory, ReparsePoint SymbolicLink {C:\Temp\Log4j}
    

    For PS 4, with no Linktype we need to check ReparsePoints for a match and we only get the output below:

    Get-ChildItem -Path "C:\temp\" -Force |
       Where-Object { $_.LinkType -ne $null -or $_.Attributes -match "ReparsePoint" } |
       ft FullName,Attributes,Linktype,Target -auto
    
    FullName                  Attributes Linktype Target
    --------                  ---------- -------- ------
    C:\temp\J    Directory, ReparsePoint
    C:\temp\soft Directory, ReparsePoint
    C:\temp\hard   Archive, ReparsePoint
    

    So in the latter instance, you're best off shelling out to cmd /c dir as mentioned previously.