Functions/Validations/Test-FileExists.ps1
<#
.SYNOPSIS Checks if file exists. .DESCRIPTION Checks if file exists. Returns true or false only. Use parameter ComputerName to test a local path on a remote computer. .EXAMPLE Test-FileExists -Path 'C:\temp\test.txt' .EXAMPLE Test-FileExists -Path 'C:\temp\test.txt' -GiveErrorIfNotExists # runs into error action stop if not exists .EXAMPLE Test-FileExists -Path 'C:\temp\test.txt' -GiveErrorIfExists # runs into error action stop if exists .EXAMPLE Test-FileExists -Path 'C:\temp\test.txt' -ComputerName 'remoteserver01' # Tests path '\\remoteserver01\c$\temp\test.txt'. .PARAMETER Path FilePath to check .PARAMETER GiveErrorIfNotExists Switch to determine if error must be given when file does not exists. .PARAMETER GiveErrorIfExists Switch to determine if error must be given when file exists. #> function Test-FileExists { [cmdletbinding()] [OutputType([bool])] [Alias('Check-FileExists')] param ( [parameter(Mandatory=$true)] [string] $FilePath, [parameter(Mandatory=$false)] [string] $ComputerName, [switch] $GiveErrorIfNotExists, [switch] $GiveErrorIfExists ) PROCESS { if([string]::IsNullOrEmpty($ComputerName) -eq $false){ $FilePath = Convert-LocalPathToUncPath -Path $FilePath -MachineName $ComputerName } if (Test-Path $FilePath -PathType Leaf){ if ($GiveErrorIfExists) { Write-Error (" File exists: $FilePath ") -ErrorAction Stop } else { return $true } } elseif ($GiveErrorIfNotExists) { Write-Error (" File does not exist: $FilePath ") -ErrorAction Stop } $false } } Export-ModuleMember -Function Test-FileExists -Alias Check-FileExists |