"DoesItemExist" Checks if the registry key, registry entry, file, or directory exists

Topics: Archive - Toolkit Extensions
Dec 4, 2013 at 6:51 PM
Edited Dec 6, 2013 at 6:54 PM
Spacing looks a bit weird on CodePlex. Pasted it straight out of Notepad++.
Function DoesItemExist{
<#
    .SYNOPSIS
        Check if the item exists. Can check directories, files, registry keys, registry entries.
        Returns $true or $false.
    .PARAMETER Path
        The path to the file, directory, registry key, or registry value that you want to see if it exists.
    .PARAMETER regEntry
        Name of the registry entry you want to check.
    .EXAMPLE
        DoesItemExist -Path "C:\Windows\Temp\Test\"
    .EXAMPLE
        DoesItemExist -Path "C:\Windows\Temp\Install.log"
    .EXAMPLE
        DoesItemExist -Path "HKLM:\Software\Microsoft\Windows NT\CurrentVersion\"
    .EXAMPLE
        DoesItemExist -Path "HKLM:\Software\Microsoft\Windows NT\CurrentVersion\" -regEntry "RegisteredOrganization"
#>
    param(
        [Parameter(Mandatory=$true, HelpMessage="Path to file, directory, or registry key.")]
        [ValidateNotNullOrEmpty()]
        [String[]]
        $Path,
        [Parameter(Mandatory=$false, HelpMessage="Registry entry")]
        [ValidateNotNullOrEmpty()]
        $regEntry = $null
    )
    if($regEntry -ne $null){
        if (Test-Path $Path) {
            $Key = Get-Item -LiteralPath $Path
            if ($Key.GetValue($regEntry, $null) -ne $null) {
                Write-Log -Text "[DoesItemExist] Registry entry: $regEntry exists."
                $true
            } else {
                Write-Log -Text "[DoesItemExist] Registry entry: $regEntry does not exist."
                $false
            }
        } else {
            Write-Log -Text "[DoesItemExist] Registry path to $regEntry does not exist."
            $false
        }
    }
    else{
        $Item = Get-ItemProperty $Path -ErrorVariable Error -ErrorAction SilentlyContinue
        if([IO.File]::Exists($Path) -eq "True"){
            Write-Log -Text "[DoesItemExist] File exists at: $Path"
            $true
        }
        elseif([IO.Directory]::Exists($Path) -eq "True"){
            Write-Log -Text "[DoesItemExist] Directory $Path exists."
            $true
        }
        elseif($Error.Count -eq 0){
            Write-Log -Text "[DoesItemExist] Registry path at $Path exists."
            $true
        }
        else {
            Write-Log -Text "[DoesItemExist] Item: $Path does not exist."
            $false
        }
        $Error.Clear()
    }
}
Dec 6, 2013 at 3:51 PM
Thanks, that is very useful. Quick thing, in the SYNOPSIS Section you have "DoesFileExist" not "DoesItemExist "
Dec 6, 2013 at 6:56 PM
Woops! Thanks for pointing that out. It's fixed now.
Dec 20, 2013 at 9:04 PM
Would be great with some 'live' cases where you use this.. to inspire the rest of us :)