Scripts/UpdateSymlink.ps1


function CmxUpdateSymlink
{
    [CmdletBinding()]
    param()

    $currentUserInstallationDir = [Environment]::GetFolderPath('MyDocuments') + '\WindowsPowerShell\Modules\CmxModule'
    Write-Host "CurrentUserInstallationDir = $currentUserInstallationDir"

    Write-Host 'try to remove the current symlink'
    $latestPath = $currentUserInstallationDir + '\LATEST'

    if(Test-Path -Path $latestPath -PathType Container)
    {
        $latestItem = Get-Item $latestPath
        $isSymlinkDefined = $latestItem.LinkType -eq "SymbolicLink"
        if($isSymlinkDefined)
        {
            Write-Host 'found symlink, delete it'
            $latestItem.Delete()
            Write-Host 'symlink deleted'
        }
        else
        {
            Write-Host 'no symlink found to delete'
        }
    }

    Write-Host 'now find the latest version folder'
    # $latestVersionFolder = ((Get-ChildItem $currentUserInstallationDir).Name) | Sort-Object | Select-Object -Last 1

    $latestVersion = (Get-ChildItem $currentUserInstallationDir).Name | Foreach-Object { [System.Version]::Parse($_) } | Sort-Object | Select-Object -Last 1
    $latestVersionFolder = $latestVersion.ToString()

    if($null -ne $latestVersionFolder)
    {
        Write-Host "Found LatestVersionFolder = $latestVersionFolder"
        Write-Host "get full path to this version folder"
        $pathToLatestModule = $currentUserInstallationDir + '\' + $latestVersionFolder
        
        if(Test-Path -Path $pathToLatestModule -PathType Container)
        {
            Write-Host 'the path to the version folder exists, so try to make the symlink'
            New-Item -ItemType SymbolicLink -Path $latestPath -Target $pathToLatestModule | Out-Null
        }
        else
        {
            Write-Host "the path to the version folder does not exists, cannot make a symlink"
        }
    }
    else
    {
        Write-Host "there is no latest version folder, cannot make the symlink "
    }
}