SQL Clone
SQLServerCentral is supported by Redgate
Log in  ::  Register  ::  Not logged in

Using Symlinks in PowerShell Scripts

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"}

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.

Chad Miller

Chad Miller is a Senior Manager of Database Administration at Raymond James Financial. Chad has worked with Microsoft SQL Server since 1999 and has been automating administration tasks using Windows Powershell since 2007. Chad is the Project Coordinator/Developer of the Powershell-based Codeplex project SQL Server PowerShell Extensions (SQLPSX). Chad leads the Tampa Powershell User Group and is a frequent speaker at users groups, SQL Saturdays and Code Camps.


No comments.

Leave a Comment

Please register or log in to leave a comment.