2

On Linux, I want to replace a bash script with powershell. The script needs to test a file to determine if it is a symbolic link. In bash, one can use the -L operator:

if [[ -L "/tmp/mysteryfile" ]] ; then ; echo "It is a link" ; fi

How can I do the same in powershell on Linux?

  • Look at the attributes of the file, there a plenty of indicators that it is a symlink. Get-ChildItem filename | Format-List * – Frands Hansen Sep 1 at 19:18
2

On my Ubuntu 19.04 this:

PS> gci /bin/bz*|select Mode,LastWriteTime,Length,Name,Attributes,LinkType|ft -auto

yields

Mode   LastWriteTime     Length Name           Attributes LinkType
----   -------------     ------ ----           ---------- --------
--r--l 04.07.19 14:50:14  38984 bzcat            ReadOnly HardLink
-----l 04.07.19 14:50:14      6 bzcmp        ReparsePoint SymbolicLink
--r--- 04.07.19 14:50:14   2227 bzdiff           ReadOnly 
-----l 04.07.19 14:50:14      6 bzegrep      ReparsePoint SymbolicLink
--r--- 13.08.18 13:29:27   4877 bzexe            ReadOnly 
-----l 04.07.19 14:50:14      6 bzfgrep      ReparsePoint SymbolicLink
--r--- 04.07.19 14:50:14   3641 bzgrep           ReadOnly 
--r--l 04.07.19 14:50:14  38984 bzip2            ReadOnly HardLink
--r--- 04.07.19 14:50:14  14328 bzip2recover     ReadOnly 
-----l 04.07.19 14:50:14      6 bzless       ReparsePoint SymbolicLink
--r--- 04.07.19 14:50:14   1297 bzmore           ReadOnly 

So the Mode l denotes a link, as does the Attribute ReparsePoint denote a SymbolicLink.

But only the LinkType differentiates between Hard-/SymbolicLinks

if((Get-Item "/tmp/mysteryfile").LinkType -eq 'SymbolicLink'){"It is a SymbolicLink"}

or

if($LT=(Get-Item "/tmp/mysteryfile").LinkType){"It is a $LT"}

To see some stats:

PS> gci /bin -rec -force -ea 0|Where LinkType|Group LinkType -NoElement               

Count Name
----- ----
    3 HardLink
  276 SymbolicLink

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.