TM-ValidationUtility.psm1

using namespace System.IO
using namespace System.Management.Automation
try {
    Add-Type -ErrorAction Stop -TypeDefinition @'
using System;
using System.IO;
using System.Management.Automation;
using System.Text.RegularExpressions;
namespace Validation {
 
    #region Exceptions
 
    public class PathNotFound : IOException {
        public PathNotFound() :base() { }
        public PathNotFound(string message) :base(message) { }
    }
 
    public class PathFound : IOException {
        public PathFound() :base() { }
        public PathFound(string message) :base(message) { }
    }
 
    public class InvalidFormat : Exception {
        public InvalidFormat() :base() { }
        public InvalidFormat(string message) :base(message) { }
    }
 
    #endregion Exceptions
 
    #region ValidatePathExistsAttribute
 
    public enum PathType {
        File,
        Folder,
        Any,
        None
    }
 
    public class ValidatePathExistsAttribute : ValidateArgumentsAttribute {
        private PathType _pathType = PathType.Any;
 
        public ValidatePathExistsAttribute() { }
        public ValidatePathExistsAttribute(PathType pathType ) { _pathType = pathType ; }
 
        protected override void Validate(object obj, EngineIntrinsics engineIntrinsics) {
            string path = string.Empty;
            if (obj is FileSystemInfo) {
                path = ((FileSystemInfo)obj).FullName;
            } else {
                path = obj.ToString( ) ?? string.Empty;
            }
 
            // Check if path exists.
            bool fileExists = File.Exists(path);
            bool directoryExists = Directory.Exists(path);
 
            // Build Exception Message String
            string msg = (
                (_pathType != PathType.Any && _pathType != PathType.None)
                    ? "Path"
                    : Enum.GetName(typeof(PathType), _pathType
            ) +
            '"' + path + '"' +
            (
                (_pathType == PathType.None)
                    ? "already exists!"
                    : "does not exist!")
            );
 
            // Validate path
            if (string.IsNullOrWhiteSpace(path)) {
                throw new ArgumentNullException("Argument cannot be null or whitespace");
            } else if (
                (_pathType == PathType.Any) &&
                (fileExists == false) &&
                (directoryExists == false)
            ) {
                throw new PathNotFound(msg);
            } else if (_pathType == PathType.Folder && directoryExists == false) {
                throw new DirectoryNotFoundException(msg);
            } else if (_pathType == PathType.File && fileExists == false) {
                throw new FileNotFoundException(msg);
            } else if (_pathType == PathType.None && (fileExists || directoryExists)) {
                throw new PathFound(msg);
            }
        }
    }
 
    #endregion ValidatePathExistsAttribute
 
    public class ValidateIPv4FormatAttribute : ValidateArgumentsAttribute {
        private static Regex _regex = new Regex(@"^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$");
 
        public ValidateIPv4FormatAttribute() { }
 
        protected override void Validate(object obj, EngineIntrinsics engineIntrinsics) {
            if ((obj is string) == false) {
                throw new InvalidOperationException("Cannot validate non-string arguments.");
            } else if (string.IsNullOrWhiteSpace(obj.ToString())) {
                throw new ArgumentNullException("Argument cannot be null or whitespace");
            } else if (_regex.IsMatch(obj.ToString()) == false) {
                throw new InvalidFormat(string.Format("Invalid format for '{0]'. Does not match Gist Uri format.", obj));
            }
        }
    }
 
    public class ValidateGistUriFormatAttribute : ValidateArgumentsAttribute {
        private static Regex _regex = new Regex(@"^(https://gist\.github\.com/[[a-zA-Z0-9-_]+|https://api\.github\.com/gists)/[a-zA-Z0-9]{32}$");
 
        public ValidateGistUriFormatAttribute() { }
 
        protected override void Validate(object obj, EngineIntrinsics engineIntrinsics) {
            if ((obj is string) == false) {
                throw new InvalidOperationException("Cannot validate non-string arguments.");
            } else if (string.IsNullOrWhiteSpace(obj.ToString())) {
                throw new ArgumentNullException("Argument cannot be null or whitespace");
            } else if (_regex.IsMatch(obj.ToString()) == false) {
                throw new InvalidFormat(string.Format("Invalid format for '{0]'. Does not match Gist Uri format.", obj));
            }
        }
    }
}
'@

} catch {
    if ($_.Exception.Message -notmatch "Cannot add type\. The type name 'Validation\..*' already exists\."){
        throw
    }
}