HelperFunctions.psm1
<#
.NOTES -------------------------------------------------------------------------------- Code generated by: SAPIEN Technologies, Inc., PowerShell Studio 2020 v5.7.182 Generated on: 12/9/2020 5:40 PM Generated by: Heather Miller -------------------------------------------------------------------------------- .DESCRIPTION Script generated by PowerShell Studio 2020 #> function global:Test-PathExists { <# .EXTERNALHELP HelperFunctions.psm1-Help.xml #> [CmdletBinding()] param ( [Parameter(Mandatory = $true, Position = 0)] [String]$Path, [Parameter(Mandatory = $true, Position = 1)] [Object]$PathType ) Begin { $VerbosePreference = 'Continue' } Process { Switch ($PathType) { File { If ((Test-Path -Path $Path -PathType Leaf) -eq $true) { Write-Information -MessageData "File: $Path already exists..." } Else { New-Item -Path $Path -ItemType File -Force Write-Verbose -Message "File: $Path not present, creating new file..." } } Folder { If ((Test-Path -Path $Path -PathType Container) -eq $true) { Write-Information -MessageData "Folder: $Path already exists..." } Else { New-Item -Path $Path -ItemType Directory -Force Write-Verbose -Message "Folder: $Path not present, creating new folder" } } } } End { } } function global:Invoke-ZipDirectory { <# .EXTERNALHELP HelperFunctions.psm1-Help.xml #> [CmdletBinding()] param ( [Parameter(Mandatory = $true, ValueFromPipeline = $true, Position = 0)] [String]$zipFileName, [Parameter(Mandatory = $true, ValueFromPipeline = $true, Position = 1)] [String]$sourceDir, [Parameter(ValueFromPipeline = $true, Position = 2)] [String]$ArchiveMode ) Begin { Add-Type -Assembly System.IO.Compression.FileSystem Switch ($ArchiveMode) { "Fast"{ $compressionLevel = [System.IO.Compression.CompressionLevel]::Fastest; Break } "None"{ $compressionLevel = [System.IO.Compression.CompressionLevel]::NoCompression; Break } default{ $compressionLevel = [System.IO.Compression.CompressionLevel]::Optimal } } } Process { [System.IO.Compression.ZipFile]::CreateFromDirectory($sourceDir, $zipFileName, $compressionLevel, $false) } End { } } function global:Invoke-CreateZipFile { <# .EXTERNALHELP HelperFunctions.psm1-Help.xml #> [CmdletBinding()] param ( [Parameter(Mandatory = $true, Position = 0)] [String]$CompressedFileName, [Parameter(Mandatory = $true, Position = 1)] [String]$FileToCompress, [Parameter(Mandatory = $true, Position = 2)] [String]$EntryName, [Parameter(Mandatory = $true, Position = 3)] [String]$ArchiveMode ) Begin { Add-Type -Assembly System.IO.Compression.FileSystem Switch ($ArchiveMode) { "Create" { $objCompressedFile = [System.IO.Compression.ZipFile]::Open($CompressedFileName, [System.IO.Compression.ZipArchiveMode]::Create) } "Read" { $objCompressedFile = [System.IO.Compression.ZipFile]::Open($CompressedFileName, [System.IO.Compression.ZipArchiveMode]::Read) } "Update" { $objCompressedFile = [System.IO.Compression.ZipFile]::Open($CompressedFileName, [System.IO.Compression.ZipArchiveMode]::Update) } } } Process { $compressionLevel = [System.IO.Compression.CompressionLevel]::Optimal $archiveEntry = [System.IO.Compression.ZipFileExtensions]::CreateEntryFromFile($objCompressedFile, $FileToCompress, $EntryName, $compressionLevel) $objCompressedFile.Dispose() } End { } } function global:Invoke-ExpandZipArchive { <# .EXTERNALHELP HelperFunctions.psm1-Help.xml #> [CmdletBinding()] param ( [Parameter(Mandatory = $true, ValueFromPipeline = $true, Position = 0)] [String]$zipFileName, [Parameter(Mandatory = $true, ValueFromPipeline = $true, Position = 1)] [String]$destDirectory ) Begin { Add-Type -Assembly System.IO.Compression.FileSystem } Process { [System.IO.Compression.ZipFile]::ExtractToDirectory($zipFileName, $destDirectory) } End { } } function global:Get-ComputerNameByIP { <# .EXTERNALHELP HelperFunctions.psm1-Help.xml #> [CmdletBinding()] param ( [Parameter(Mandatory = $true, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true, Position = 0)] [Object]$IPAddress ) BEGIN { } PROCESS { If ($IPAddress -and $_) { Throw 'Please use either pipeline or input parameter' Break } ElseIf ($IPAddress) { ([System.Net.Dns]::GetHostbyAddress($IPAddress)).HostName } ElseIf ($_) { [System.Net.Dns]::GetHostbyAddress($_).HostName } Else { $IPAddress = Read-Host "Please supply the IP Address" [System.Net.Dns]::GetHostbyAddress($IPAddress).HostName } } END { } } function global:Get-IPByComputerName { <# .EXTERNALHELP HelperFunctions.psm1-Help.xml #> [CmdletBinding()] param ( [Parameter(Mandatory = $true, ValueFromPipeline = $true, Position = 0)] [String[]]$ComputerName, [Parameter(Mandatory = $true, ValueFromPipeline = $true, Position = 1)] [switch]$IPV6only, [Parameter(Mandatory = $true, ValueFromPipeline = $true, Position = 2)] [switch]$IPV4only ) Begin { $VerbosePreference = 'Continue' Write-Verbose "`n Checking IP Address . . .`n" $i = 0 } #Begin Process { $ComputerName | ForEach-Object { $HostName = $_ Try { $AddressList = @(([net.dns]::GetHostEntry($HostName)).AddressList) } Catch { "Cannot determine the IP Address on $HostName" } IF ($AddressList.Count -ne 0) { $AddressList | ForEach-Object { IF ($IPV6only) { IF ($_.AddressFamily -eq "InterNetworkV6") { New-Object PSObject -Property @{ IPAddress = $_.IPAddressToString ComputerName = $HostName } | Select-Object -Property ComputerName, IPAddress } } IF ($IPV4only) { IF ($_.AddressFamily -eq "InterNetwork") { New-Object PSObject -Property @{ IPAddress = $_.IPAddressToString ComputerName = $HostName } | Select-Object -Property ComputerName, IPAddress } } IF (!($IPV6only -or $IPV4only)) { New-Object PSObject -Property @{ IPAddress = $_.IPAddressToString ComputerName = $HostName } | Select-Object -Property ComputerName, IPAddress } } #IF } #ForEach-Object(IPAddress) } #ForEach-Object(ComputerName) } #Process } function global:Get-MyInvocation { <# .EXTERNALHELP HelperFunctions.psm1-Help.xml #> #Begin function to get $MyInvocation information Return $MyInvocation } function global:Get-MyNewCimSession { <# .NOTES THIS CODE IS MADE AVAILABLE AS IS, WITHOUT WARRANTY OF ANY KIND. THE RISK OF THE USE OR THE RESULTS FROM THE USE OF THIS CODE REMAINS WITH THE USER. .SYNOPSIS Creates new authenticated CIM session on the specified computer .DESCRIPTION Creates new authenticated CIM session on the specified computer using New-CimSession and iterating through session options, default being Ws-Man .PARAMETER ServerName ServerFQDN .PARAMETER Credential PSCredential .OUTPUTS None .EXAMPLE PS> Get-MyNewCimSession -Server <ServerFQDN> -Credential PSCredential #> [CmdletBinding()] Param ( [Parameter(Mandatory = $true, ValueFromPipeline = $true, Position = 0)] [ValidateNotNullorEmpty()] [String]$ServerName, [Parameter(Mandatory = $false, ValueFromPipeline = $true, Position = 1)] [System.Management.Automation.PSCredential]$Credential ) BEGIN { $VerbosePreference = 'Continue' [uint32]$timeout = 60 $so = New-CimSessionOption -Protocol Dcom $Params = @{ ErrorAction = 'Stop' Authentication = 'Negotiate' OperationTimeoutSec = $timeout } If ($PSBoundParameters.ContainsKey('Credential')) { $Params.Add('Credential', $Credential) } } PROCESS { ForEach ($server in $ServerName) { $Params.Add('ComputerName', $server) If ((Test-NetConnection -ComputerName $server -Port 5985).TcpTestSucceeded -eq $true) { Try { Write-Verbose -Message "Attempting to connect to $($server) using WSMAN protocol." -Verbose New-CimSession @Params } Catch { $errorMessage = "{0}: {1}" -f $Error[0], $Error[0].InvocationInfo.PositionMessage Write-Error $errorMessage -ErrorAction Continue } } ElseIf ((Test-NetConnection -ComputerName $server -Port 445).TcpTestSucceeded -eq $true) { $Params.Add('SessionOption', $so) Try { Write-Verbose -Message "Attempting to connect to $($server) using DCOM protocol." -Verbose New-CimSession @Params } Catch { $errorMessage = "{0}: {1}" -f $Error[0], $Error[0].InvocationInfo.PositionMessage Write-Error $errorMessage -ErrorAction Continue } finally { $Params.Remove('SessionOption') } } $Params.Remove('ComputerName') } } } function global:Get-RandomPassword { <# .EXTERNALHELP HelperFunctions.psm1-Help.xml #> [CmdletBinding()] param ( [Parameter(Mandatory = $true, ValueFromPipeline = $true, Position = 0)] [Int32]$length, [Parameter(ValueFromPipeline = $true, Position = 1)] [Boolean]$includeLCase, [Parameter(ValueFromPipeline = $true, Position = 2)] [Boolean]$includeUCase, [Parameter(ValueFromPipeline = $true, Position = 3)] [Boolean]$includeNumbers, [Parameter(ValueFromPipeline = $true, Position = 4)] [Boolean]$includeSpecialChar, [Parameter(ValueFromPipeline = $true, Position = 5)] [Boolean]$noSimilarCharacters ) Begin { # Validate our parameters if ($length -lt 10) { $exception = New-Object Exception "The minimum password length is 10" Throw $exception } if ($includeLCase -eq $false -and $includeUCase -eq $false -and $includeNumbers -eq $false -and $includeSpecialChar -eq $false) { $exception = New-Object Exception "At least one set of included characters must be specified" Throw $exception } } Process { #Available characters $CharsToSkip = [char]"i", [char]"l", [char]"o", [char]"1", [char]"0", [char]"I" $AvailableCharsForPassword = $null; $uppercaseChars = $null for ($a = 65; $a -le 90; $a++) { if ($noSimilarCharacters -eq $false -or [char][byte]$a -notin $CharsToSkip) { $uppercaseChars += ,[char][byte]$a } } $lowercaseChars = $null for ($a = 97; $a -le 122; $a++) { if ($noSimilarCharacters -eq $false -or [char][byte]$a -notin $CharsToSkip) { $lowercaseChars += ,[char][byte]$a } } $digitChars = $null for ($a = 48; $a -le 57; $a++) { if ($noSimilarCharacters -eq $false -or [char][byte]$a -notin $CharsToSkip) { $digitChars += ,[char][byte]$a } } $specialChars = $null $specialChars += [char]"=", [char]"+", [char]"_", [char]"?", [char]"!", [char]"-", [char]"#", [char]"$", [char]"*", [char]"&", [char]"@" $TemplateLetters = $null if ($includeLCase) { $TemplateLetters += "L" } if ($includeUCase) { $TemplateLetters += "U" } if ($includeNumbers) { $TemplateLetters += "N" } if ($includeSpecialChar) { $TemplateLetters += "S" } $PasswordTemplate = @() # Set password template, to ensure that required chars are included do { $myPassTemplate.Clear() for ($loop = 1; $loop -le $length; $loop++) { $myPassTemplate += $TemplateLetters.Substring((Get-Random -Maximum $TemplateLetters.Length), 1) } } while (( (($includeLCase -eq $false) -or ($myPassTemplate -contains "L")) -and (($includeUCase -eq $false) -or ($myPassTemplate -contains "U")) -and (($includeNumbers -eq $false) -or ($myPassTemplate -contains "N")) -and (($includeSpecialChar -eq $false) -or ($myPassTemplate -contains "S"))) -eq $false ) #$PasswordTemplate now contains an array with at least one of each included character type (uppercase, lowercase, number and/or special) foreach ($char in $myPassTemplate) { switch ($char) { L { $Password += $lowercaseChars | Get-Random } U { $Password += $uppercaseChars | Get-Random } N { $Password += $digitChars | Get-Random } S { $Password += $specialChars | Get-Random } } } } End { return $Password } } function global:Get-ReportDate { <# .EXTERNALHELP HelperFunctions.psm1-Help.xml #> #Begin function get report execution date Get-Date -Format "yyyy-MM-dd" } function global:Get-TodaysDate { <# .EXTERNALHELP HelperFunctions.psm1-Help.xml #> #Begin function set Todays date format Get-Date -Format "dd-MM-yyyy" } function global:Test-IsAdmin { <# .EXTERNALHELP HelperFunctions.psm1-Help.xml #> #Begin function to identify members, direct and indirect, of local Administrators group Begin { $principal = [Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent() } Process { $role = [Security.Principal.WindowsBuiltInRole]::Administrator } End { return $principal.IsInRole($role) } } function global:Test-IsValidIPAddress { <# .EXTERNALHELP HelperFunctions.psm1-Help.xml #> [CmdletBinding()] [OutputType([System.Boolean])] param ( [Parameter(Mandatory = $true, Position = 0)] [String]$IP ) Begin { } Process { [System.Net.IPAddress]$IPAddressObject = $null If ([System.Net.IPAddress]::TryParse($IP, [ref]$IPAddressObject) -and $IP -eq $IPAddressObject.tostring()) { $true } Else { $false } } End { } } function global:Test-MyNetConnection { <# .EXTERNALHELP HelperFunctions.psm1-Help.xml #> [CmdletBinding()] param ( [Parameter(Mandatory = $true, Position = 0)] [String]$Server, [Parameter(Position = 1)] [Int32]$Port ) Test-NetConnection -ComputerName $Server -Port $port } function global:Test-RegistryValue { <# .EXTERNALHELP HelperFunctions.psm1-Help.xml #> [CmdletBinding()] [OutputType([System.Boolean])] param ( [Parameter(Mandatory = $true, Position = 0)] [Object]$Path, [Parameter(Mandatory = $true, Position = 1)] [Object]$Value ) Try { Get-ItemProperty -Path $Path -Name $Value -ErrorAction Stop | Out-Null Return $true } Catch { Return $false } } function global:Test-IsGroupMember { <# .SYNOPSIS Verify user's group membership .DESCRIPTION This function uses the .NET DirectorySearcher to search for, locate a group in the defined context and verify whether or not the user specified in the parameters is a member of that group. .PARAMETER user User object to verify .PARAMETER grp Group object to search membership on .EXAMPLE PS C:\> Test-IsGroupMember -user sAMAccountName -group groupName .NOTES THIS CODE IS MADE AVAILABLE AS IS, WITHOUT WARRANTY OF ANY KIND. THE ENTIRE RISK OF THE USE OR THE RESULTS FROM THE USE OF THIS CODE REMAINS WITH THE USER. #> [CmdletBinding()] param ( [Parameter(Mandatory = $true)] $User, [Parameter(Mandatory = $true)] $Group ) begin { $strFilter = "(&(objectClass=Group)(name=" + $Group + "))" $objDomain = New-Object System.DirectoryServices.DirectoryEntry $objSearcher = New-Object System.DirectoryServices.DirectorySearcher } process { $objSearcher.SearchRoot = $objDomain $objSearcher.PageSize = 1000 $objSearcher.Filter = $strFilter $objSearcher.SearchScope = "Subtree" $Results = $objSearcher.FindOne() $objItem = $Results.Properties } end { ([string]$objItem.member).contains($user) } } function global:Get-UTCTime { <# .EXTERNALHELP HelperFunctions.psm1-Help.xml #> #Begin function to get current date and time in UTC format [System.DateTime]::UtcNow } function global:Write-Logfile { <# .EXTERNALHELP HelperFunctions.psm1-Help.xml #> [CmdletBinding()] param ( [Parameter(Mandatory = $true, Position = 0)] [Object]$logEntry, [Parameter(Mandatory = $true, Position = 1)] [Object]$logFile, [Parameter(Position = 2)] [Object]$level ) Begin { $VerbosePreference = 'Continue' Switch ($level) { 1 { $loglevel = "[INFO]: " } 2 { $loglevel = "[WARNING]: " } 3 { $loglevel = "[ERROR]: " } } } Process { Write-Verbose -Message $logentry $now = [DateTime]::UtcNow $timeStamp = Get-Date $now -DisplayHint Time } End { ("{0} [{1}] - {2}" -f $timeStamp, $logLevel, $logEntry) | Out-File -FilePath $logFile -Append } } function global:Add-DataTable { [CmdletBinding()] param ( [Parameter(Mandatory = $true, Position = 0)] [ValidateNotNullOrEmpty()] [String]$TableName = 'TableName', [Parameter(Mandatory = $true, Position = 1)] [ValidateNotNullOrEmpty()] $ColumnArray = 'DataColumnDefinitions' ) begin { $dt = $null $dt = New-Object System.Data.DataTable("$TableName") } process { foreach ($col in $ColumnArray) { [void]$dt.Columns.Add([System.Data.DataColumn]$col.ColumnName.ToString(), $col.DataType) } } end { return, $dt } } function global:Get-FQDNfromDN { <# .EXTERNALHELP HelperFunctions.psm1-Help.xml #> [CmdletBinding()] [OutputType([String])] param ( [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] [string]$DistinguishedName ) begin { } process { if ([string]::IsNullOrEmpty($DistinguishedName) -eq $true) { return $null } $domainComponents = $DistinguishedName.ToString().ToLower().Substring($DistinguishedName.ToString().ToLower().IndexOf("dc=")).Split(",") for ($i = 0; $i -lt $domainComponents.count; $i++) { $domainComponents[$i] = $domainComponents[$i].Substring($domainComponents[$i].IndexOf("=") + 1) } $fqdn = [string]::Join(".", $domainComponents) } end { return [string]$fqdn } } function global:Get-DNfromFQDN { <# .EXTERNALHELP HelperFunctions.psm1-Help.xml #> [CmdletBinding()] [OutputType([String])] param ( [Parameter(Mandatory = $true, Position = 0, ValueFromPipeline = $false)] [string]$domainFQDN ) begin { $colSplit = $domainFQDN.Split(".") $FQDNdepth = $colSplit.length $DomainDN = "" } process { for ($i = 0; $i -lt ($FQDNdepth); $i++) { if ($i -eq ($FQDNdepth - 1)) { $Separator = "" } else { $Separator = "," } [string]$DomainDN += "DC=" + $colSplit[$i] + $Separator } } end { return [string]$DomainDN } } function global:Get-ComputerUptime { <# .EXTERNALHELP HelperFunctions.psm1-Help.xml #> [CmdletBinding()] [OutputType([String])] param ( [Parameter(Mandatory = $true, Position = 0, ValueFromPipeline = $false)] [string]$ComputerName ) $OperatingSystem = Get-WmiObject Win32_OperatingSystem -ComputerName $ComputerName -NameSpace 'root\cimV2' -ErrorAction SilentlyContinue $LastBootUpTime = $OperatingSystem.LastBootUpTime $Uptime = (Get-Date) - [System.Management.ManagementDateTimeconverter]::ToDateTime($LastBootTime) "Days: $($Uptime.Days); Hours: $($Uptime.Hours); Minutes: $($Uptime.Minutes); Seconds: $($Uptime.Seconds)" return [string]$Uptime } function global:Get-UserFromSID { <# .EXTERNALHELP HelperFunctions.psm1-Help.xml #> [CmdletBinding()] param ( [Parameter(Position = 0, Mandatory = $true, HelpMessage = "Enter the SID to query.")] [string]$strSID ) begin { $objSID = New-Object System.Security.Principal.SecurityIdentifier($strSID) } process { $objUser = $objSID.Translate([System.Security.Principal.NTAccount]) } end { $objUser.Value } } $aliases = @() New-Alias -Name fnTest-NetConnection -Value global:Test-MyNetConnection New-Alias -Name fnTest-IsValidIPAddress -Value global:Test-IsValidIPAddress New-Alias -Name fnTest-RegistryValue -Value global:Test-RegistryValue New-Alias -Name Create-ZipArchive -Value global:Invoke-ZipDirectory New-Alias -Name Create-ZipFile -Value global:Invoke-CreateZipFile New-Alias -Name Expand-ZipArchive -Value global:Invoke-ExpandZipArchive New-Alias -Name fnNew-CimSession -Value global:Get-MyNewCimSession New-Alias -Name fnUTC-Now -Value global:Get-UTCTime New-Alias -Name UTC-Now -Value global:Get-UTCTime New-Alias -Name fnGet-ReportDate -Value global:Get-ReportDate New-Alias -Name fnGet-TodaysDate -Value global:Get-TodaysDate New-Alias -Name fnCheck-Path -Value global:Test-PathExists New-Alias -Name Check-Path -Value global:Test-PathExists New-Alias -Name fnGet-MyInvocation -Value global:Get-MyInvocation New-Alias -Name fnWrite-LogFile -Value global:Write-LogFile New-Alias -Name Make-Table -Value global:Add-DataTable New-Alias -Name fnMake-Table -Value global:Add-DataTable $aliases = "fnTest-NetConnection", "Create-ZipArchive", "Create-ZipFile", "Expand-ZipArchive", "fnTest-IsValidIPAddress", "fnTest-RegistryValue", "fnNew-CimSession", "fnUTC-Now", "UTC-Now", "fnGet-ReportDate", "fnGet-TodaysDate", "fnCheck-Path", "Check-Path", "fnGet-MyInvocation", "fnWrite-LogFile", "Make-Table", "fnMake-Table" Export-ModuleMember -Function '*' -Alias $aliases |