Parduz
Parduz

Reputation: 602

Windows Powershell: check if a symlink is "broken"

This is the part of a script which create symlinks in system folders depending on special names of the directory being parsed.

$linkTarget = Join-Path -Path $folder["SystemFolder"] -ChildPath $subfolder.Name
if (-not (Test-Path -Path $linkTarget)) {
    Create-Symlink -SourcePath $subfolder.FullName -TargetPath $linkTarget
} else {
    Write-Host "$linkTarget already exists" -ForegroundColor Yellow
}

($folder["SystemFolder"] is from the hashtable which associate my own "special names" with system folder paths.)

For example, if the current folder name is "S:\MyStuff\_PData" and $subfolder.Name is "My Folder", the script will create a symlink "My Folder" in C:\ProgramData (so "C:\ProgramData\My Folder\" will be valid path, and will shows what's in "S:\MyStuff_PData\My Folder").

I'm am not a Powershell expert, and I've been able to check if the symlink $subfolder.Name already exists by "collecting" various samples and answers and learning from those.

But I need also to check if the link is still valid (i mean: if it still points to $subfolder.Name), and "repair" it if not. How can i do this?

Upvotes: 0

Views: 38

Answers (1)

Ctznkane525
Ctznkane525

Reputation: 7465

Assuming you have 2 folders:

Source: C:\Test\Test1 (The S Drive in your case)

Link: C:\Test\Test2 (The ProgramData in your case)

Your Link has a property to access the Source folder, called Target.

(Get-Item -Path "C:\Test\Test2").Target

  • This gives you the source path, which you can check for equality.

I wouldn't do this unless you have confirmed the linkTarget folder exists, but this would be the way to confirm everything is setup properly:

(Get-Item -Path $linkTarget).Target -eq $subfolder.FullName

I think putting this in full context:

$linkTarget = Join-Path -Path $folder["SystemFolder"] -ChildPath $subfolder.Name

# Check If Link Folder Exists
if (-not (Test-Path -Path $linkTarget)) {

    # Doesn't Exist, Create It
    Create-Symlink -SourcePath $subfolder.FullName -TargetPath $linkTarget
} else {

    # Check If Symlink Exists and Matches - Otherwise could be a regular folder or unmatching symlink
    if (Get-Item -Path $linkTarget).Target -ne $subfolder.FullName)
    {
        # Delete Folder - This is Setup Incorrectly
        Remove-Item $linkTarget -Force

        # Recreate Symlink
        Create-Symlink -SourcePath $subfolder.FullName -TargetPath $linkTarget
    }
    else
    {
        Write-Host "$linkTarget already exists" -ForegroundColor Yellow
    }

    
}

Upvotes: 1

Related Questions