Symlinks are heavily used in Linux/Unix environments to provide an abstraction for file and directory locations and with the introduction of symbolic links in Vista/Win7/Windows 2008 we can take advantage of this handy little feature. One use case for symlinks in Linux scripting is to setup a link to a script file and then based on the file name from which the script is called provide alternate code execution paths. This is a bit of an advanced scripting technique which I thought would be interesting to reproduce in PowerShell/Windows. Keep in mind, there are other ways to accomplish the same desired outcome in PowerShell including reusing functions…
Let’s take a look at an example. First create a PowerShell script called Test-SymLink.ps1 as follows:
function Test-SymLink { $scriptName = [system.io.path]::GetFilename($myinvocation.ScriptName) if ($scriptName -eq 'link1.ps1') {Write-Host "$scriptName -- Do Stuff"} elseif ($scriptName -eq 'link2.ps1') {Write-Host "$scriptName -- Do Other Stuff"} } Test-SymLink
Then create two symlinks to the Test-SymLink.ps1 script file using the mklink.exe utility from the regular cmd.exe window run as administrator:
Next within PowerShell call the script using the two symlinks:
u00@Z003 C:\Users\u00\bin>.\link1.ps1 link1.ps1 -- Do Stuff u00@Z003 C:\Users\u00\bin>.\link2.ps1 link2.ps1 -- Do Other Stuff
As you can see the function resolved the “[system.io.path]::GetFilename($myinvocation.ScriptName)” to the name of the link which then allows you to take different code paths. This could make for some obscure code, so if you use this technique be sure to comment your script.