<# Start of Functions #>
$DefaultDRAServer = "hickam.dra.us.af.mil"
$514Printers = "ptfm-qs-514v"
$LogonByUser = "\\ptfm-stm-san3v\UserLogonLogs\ByUser"
Function Get-FunctionVersion
    {
        $Version = Get-ChildItem $PSScriptRoot\Gates-Functions.ps1
        $Version = $Version.LastWriteTime
        $Month = $Version.Month
        $Day = $Version.Day
        $Year = $Version.Year
        $Hour = $Version.Hour
        $Minute = $Version.Minute
        $Format =@()
        $Format = ($Month,$Day,$Year,$Hour,$Minute)
        $c = $Format.Count
        For ($i = 0; $i -lt $c; $i++)
            {
                [String]$test = $Format[$i]
                $test = $test.PadLeft(2,'0')
                $Format[$i] = $test
            }
        $Month = $Format[0]
        $Day = $Format[1]
        $Year = $Format[2]
        $Hour = $Format[3]
        $Minute = $Format[4]
        $i = $null
        $Version = "$Month.$Day.$Year.$Hour.$Minute"
        Return $Version
    }
Function Clone-UserGroups ($PrimaryUser,$CloneUser)
    {
        # Get the user and their group memberships
        $PGroups = Get-ADUser -Identity $PrimaryUser -Properties MemberOf
        $CGroups = Get-ADUser -Identity $CloneUser -Properties MemberOf

        #Initialize PrimaryUser_Groups,ClonedUser_Groups arrays
        $PrimaryUser_Groups = @()
        $CloneUser_Groups = @()
        #$Difference = @()

        # Iterate through each group and add it to the hash table
        foreach ($Group in $PGroups.MemberOf)
            {
                $GroupName = ((Get-ADGroup $Group).DistinguishedName).split(",")
                If ($GroupName.IndexOf("OU=McGuire AFB") -ne -1)
                    {
                        $PrimaryUser_Groups += (Get-ADGroup $Group).Name
                    }
            }
       
        foreach ($Group in $CGroups.MemberOf)
            {
                $GroupName = ((Get-ADGroup $Group).DistinguishedName).split(",")
                If ($GroupName.IndexOf("OU=McGuire AFB") -ne -1)
                    {
                        $CloneUser_Groups += (Get-ADGroup $Group).Name
                    }
            }

        ForEach ($Group in $PrimaryUser_Groups)
            {
                If (($CloneUser_Groups.IndexOf($group) -eq -1))
                    {
                        $Difference += $Group + ","
                    }
            }
       
        $len = $Difference.length - 1
        $Difference = $Difference.substring(0,$len)
        Add-Member2Group -User $CloneUser -Group "$Difference"
        $Name = (get-aduser $CloneUser).Name
        Write-Host "$Name has been added to the following groups:`r`n$Difference"
       

    }
Function Create-Shortcut ($TargetPath,$ShortcutPath,$ShortcutName)
    {
        $shell = New-Object -ComObject WScript.Shell
        $shortcut = $shell.CreateShortCut("$ShortcutPath\$ShortcutName")
        $shortcut.TargetPath = $TargetPath
        $shortcut.Save()
    }
Function Create-UDrive ($User,$Organization)
    {
        $Folder = (get-aduser $User).Name
        $UDrivePath = "\\ptfm-stm-san3v\U_Drives\$Organization"
        $U = (Get-ADUser $User)
        $ADAccount = $U.SID.Translate([System.Security.Principal.NTAccount])
        If ((Test-Path $UDrivePath) -eq $false)
            {
                Write-Host "No $UDrivePath Folder Exists!"
                Exit
            }
        $Test = Find-UDrive $User
        If ($Test -eq $null)
            {
                $NewFolder = (New-Item -Path $UDrivePath -Name $Folder -ItemType directory).FullName
                Add-NTFSAccess -Path $NewFolder -Account $ADAccount -AccessRights Modify -AccessType Allow 
                Set-User -User $User -Property HomeDrive -Value 'U:'
                Set-User -User $User -Property HomeDirectory -Value "$NewFolder"
                Start-Pause -Message1 "$NewFolder has been created for $User" -Message2 "Creating U-Drive" -Seconds 3
            }
        Else
            {
                Write-Host "This user has a U-Drive located at $Test"
            }
    }
Function Find-UDrive($User)
    {
        If ($user -eq $null){Return $null}
        $Match = (get-aduser $User).Name
        $UDrivePath = "\\ptfm-stm-san3v\U_Drives\76ARS,\\ptfm-stm-san3v\U_Drives\78ARS,\\ptfm-stm-san3v\U_Drives\514MSG,\\ptfm-stm-san3v\U_Drives\514MXG,\\ptfm-stm-san3v\U_Drives\514OG,\\ptfm-stm-san3v\U_Drives\514WG,\\ptfm-stm-san3v\U_Drives\714 AMXS,\\ptfm-stm-san3v\U_Drives\732AS"
        $UDrivePath = $UDrivePath.Split(",")
        $UDrive = @()
        ForEach ($P in $UDrivePath)
            {
                $UDrive += Get-ChildItem "$P"
            }
        $index = $UDrive.Name.IndexOf($Match)
        If ($index -eq -1) {$Result = $null} Else {$Result = ($UDrive[$index]).FullName}
        Return $Result
    }
Function Get-Model
    {
         $Model = (Get-CimInstance -ClassName Win32_ComputerSystem).Model
         Return $Model
    }
Function Backup-Favorites
    {
        $User = $env:username
        $Desktop = Get-DesktopFolder
        $UserFolder = "C:\users\$User"
        $Favorites = @()
        $FavoritesSaveFolder = "$Desktop\My Favorites"
        If ((Test-Path $FavoritesSaveFolder) -eq $False) {New-Item -Path $FavoritesSaveFolder -ItemType Directory | Out-Null} 
        $Favorites += "$UserFolder\AppData\Local\Google\Chrome\User Data\Default\bookmarks"        #Chrome
        $Favorites += "$UserFolder\AppData\Local\Microsoft\Edge\User Data\Default\bookmarks"       #Edge
        $Favorites += "$UserFolder\Favorites\*.*"                                                  #Internet Explorer
        $Favorites += "$UserFolder\AppData\Roaming\Mozilla\FireFox\Profiles\*.*"                   #FireFox
        ForEach ($Item in $Favorites)
            {
                $Folder = (Get-Item $Item).DirectoryName
                If ($Folder -eq $null) {$Folder = ((Get-Item $Item).Parent).FullName | Sort-Object -Unique}
                If ((Test-Path $Folder) -eq $True) 
                    {
                        $MakeFolder = $Folder.Replace("C:\users\","")
                        $NewFolderName = "$FavoritesSaveFolder\$MakeFolder"
                        If ((Test-Path $NewFolderName) -eq $False) {New-Item -Path "$NewFolderName" -ItemType Directory | Out-Null}
                    }
                Copy-Item "$Item" "$NewFolderName" -Recurse -Force
                
            }
        Start-Pause -Message1 "Backup Complete" -Message2 "Congratulations" -Seconds 2
    }
Function Pop-array ($array,$index) 
    {
        $pop = $array[$index]
        $c = $index - 1
        $d = $index + 1
        $e = $array.count-1
        If ($index -ne 0) 
            {
                If ($index -ne $e) 
                    {
                        $before,$after = $array[0..$c],$array[$d..$e]
                    }
                Else
                    {
                        $before,$after = $array[0..$c],$null
                    }
            }
        Else
            {
                $before,$after = $null,$array[$d..$e]
            }
        $array = $before
        $array += $after
        $array += $pop
        return $array
    }
Function Get-Macaddress ($SerialNumber, $ComputerName)
    {
        $ComputerName = $ComputerName.toUpper()
        $ComputerName = $ComputerName.replace("PTFML-","").replace("PTFMW-","").replace("PTFMT-","")
        $MAC_Address_File = "\\ptfm-stm-san3v\514MSG\514MSG-G\514SCO\MAC Address\MAC Address Populated (Repaired).xlsX"
        $MAC = Import-Excel $MAC_Address_File
        IF ($SerialNumber -ne $null) {$M = ($MAC | Where-Object {$_.'SERIAL NUMBER' -EQ $SerialNumber}).'MAC ADDRESS'}
        Else {IF ($ComputerName -ne $null){$M = ($MAC | Where-Object {$_.'SERIAL NUMBER' -like "*$ComputerName*"}).'MAC ADDRESS'}}
        Return $M
    }
Function Get-EmailAddress ($Name)
    {
        $X = $Name.Split(",")
        [string]$First = $X[1].Trim()
        [string]$Last = $X[0].Trim()
        $Name = "$Last`.$First*"
        Return (Get-ADUser -SearchBase "OU=McGuire AFB Users,OU=McGuire AFB,OU=AFCONUSWEST,OU=Bases,DC=AREA52,DC=AFNOAPPS,DC=USAF,DC=MIL" -Filter 'Name -like $Name' -Properties emailaddress).emailaddress
    }
Function Get-DODID ($Name)
    {
        $X = $Name.Split(",")
        [string]$First = $X[1].Trim()
        [string]$Last = $X[0].Trim()
        $Name = "$Last`.$First*"
        Return (Get-ADUser -SearchBase "OU=McGuire AFB Users,OU=McGuire AFB,OU=AFCONUSWEST,OU=Bases,DC=AREA52,DC=AFNOAPPS,DC=USAF,DC=MIL" -Filter 'Name -like $Name' -Properties emailaddress,EmployeeType).SamAccountName
    }
Function Get-userPrincipalName ($Name)
    {
        $X = $Name.Split(",")
        [string]$First = $X[1].Trim()
        [string]$Last = $X[0].Trim()
        $Name = "$Last`.$First*"
        Return (Get-ADUser -SearchBase "OU=McGuire AFB Users,OU=McGuire AFB,OU=AFCONUSWEST,OU=Bases,DC=AREA52,DC=AFNOAPPS,DC=USAF,DC=MIL" -Filter 'Name -like $Name' -Properties emailaddress,EmployeeType).UserPrincipalName
    }
Function Get-InstalledModules ($ModuleName,[switch]$exist)
    {
        $Modules =  "C:\windows\system32\WindowsPowerShell\v1.0\modules"
        $Modules = Get-ChildItem $Modules | Select-Object Name
        If (!($exist))
            {
                Return $Modules
            }
        Else
            {
                If ($ModuleName -ne $null)
                    {
                        $test = $Modules.Name -contains $ModuleName
                        Return $test.toString()   
                    }
                Esle
                    {
                        
                        Return "No module name specified"
                    }
            }
    }
Function Show-AdminStatus
    {
        $ID = [System.Security.Principal.WindowsIdentity]::GetCurrent()
        $P = New-Object System.Security.Principal.WindowsPrincipal($ID)
        If ($P.IsInRole([System.Security.Principal.WindowsBuiltInRole]::Administrator))
            {
                Return "True"
            }
        Else
            {
                Return "False"
            }
    }
Function Get-BitLockerKey ($ComputerName)
    {
        $LocationofBitlockerKeys = "\\ptfm-stm-san3v\514MSG\514MSG-G\514SCO\Hard Drive Encryption"
        $KeyInventory = Get-ChildItem "$LocationofBitlockerKeys\03 - Laptop Win 10","$LocationofBitlockerKeys\04 - Desktop Win 10","$LocationofBitlockerKeys\05 - Tablet Win 10"
        If ($ComputerName -eq $null)
            {
                $ComputerName = Read-Host "What is the computername?"
            }
        $Folder =  $KeyInventory.name.indexof("$ComputerName")
        If ($Folder -eq -1)
            {
                Start-Pause "Computer Name does not Exist" -seconds 3
                Return -1
            }
        $Key = $KeyInventory[$Folder].fullname
        $File = (Get-ChildItem $key)
        
        If ($File.Count -gt 1)
            {
                $File = $File | Sort-Object {$_.LastWriteTime} -Descending #Sort the array by Last Time File was written to
                $File = $File[0].FullName
            }
        Else
            {
                $File = $File.FullName
            }
        $File = Get-Content "$File"
        $i = $File.indexof("      Password:")
        If ($i -eq -1)
            {
                $i = $File.indexof("Recovery Key:")    
            }
        $Key = $File[$i + 1]
        $Key = $Key.Substring(8,55)
        Return $Key
        
    }
Function Get-DesktopFolder
    {
        $D = [System.Environment]::GetFolderPath([System.Environment+SpecialFolder]::Desktop)
        Return $D
    }
Function Copy-Item2RemoteComputer ($File,$RemotePath,$Computername)
    {
        copy-item -Path $File -recurse  -Destination $RemotePath -ToSession (New-PSSession -ComputerName $Computername)
    }
Function Add-Member2Group ($User,$Group,$Server)
    {
        $User = $User.Split(",")
        $Group = $Group.Split(",")
        ForEach ($Person in $User)
            {
                $U = Get-ADUser $Person
                $P = $U.Name
                If ($Server -eq $null -or $Server -eq "") {$Server = "lackland.dra.us.af.mil"} #Default DRA Server
                ForEach ($G in $Group)
                    {
                        Add-DRAGroupMembers -Identifier "$G" -User $P -DRARestServer $Server -DRARestPort 8755 -DRAHostServer $Server -DRAHostPort 11192 -Domain "AREA52.afnoapps.usaf.mil"
                    }
            }
    }
Function Find-UserLogon($User)
    {
        $test = get-childItem $LogonByUser
        $testx = $test.name
        $i = $testx.indexof($User)
        $Output = Get-Content $test[$i].FullName
        Start-Pause $Output
    }
Function Get-LastLogOn($Computer)
    {
       $test = get-adcomputer $Computer -Properties Location
       Return $test.Location 
    }
Function Get-IADate($user)
    {
        [datetime]$test = ((Get-ADUser $User -Properties IATrainingDate).IATrainingDate).AddDays(1)
        Write-Host (Get-ADUser $User).Name, "IA date is $test"
        Return $test
    }
Function Reset-Computer ($Computer,$Server)
    {
        $Computers = $Computer.replace(" ","").split(",")

        ForEach ($Comp in $Computers)
            {
                If ($Server -eq $null -or $Server -eq "") {$Server = $DefaultDRAServer} #Default DRA Server
                Reset-DRAComputer -DRARestServer $Server -DRARestPort 8755 -DRAHostServer $Server -DRAHostPort 11192 -Domain "AREA52.afnoapps.usaf.mil" -Identifier $Comp -Force
            }
    }
Function Test-EnabledComputer($Computer)
    {
        Try
            {
                $test = Get-ADComputer $Computer -ErrorAction Stop
            }
        Catch
            {
                Start-Pause "Computer Doesn't Exist!"
                Return "Doesn't Exist"
            }
            If ($test.Enabled -eq 'True')
                {
                    Start-Pause "$Computer is enabled"
                    Return "Enabled"
                }
            Else
                {
                    $Choice = "Yes,No"
                    $Choice = $Choice.split(',')
                    $Selection = Get-Menu -Selections $Choice -MenuHeader "Computer is disabled, would you like to enable it?" -LabelText "Please make a choice" -Default "Yes"
                    If ($Selection -eq 'Yes')
                        {
                            Set-Computer -Computer $Computer -Property 'Enabled' -Value 'True'
                            Return "Enabled"
                        }
                    Else
                        {
                            Start-Pause "$Computer is disabled"
                            Return "Disabled"
                        }
                }
    }

Function ADD-GroupMember ($Group,$User,$Server)
    {
        If ($Server -eq $null -or $Server -eq "") {$Server = $DefaultDRAServer} #Default DRA Server
        $U = Get-ADUser $User
        $User = $U.Name
        ADD-DRAGroupMembers -DRARestServer $Server -DRARestPort 8755 -DRAHostServer $Server -DRAHostPort 11192 -Domain "AREA52.afnoapps.usaf.mil" -Identifier $Group -Users $User

    }
Function Set-ComputerDescription($Computer,$Description,$Server)
    {
        If ($Description -eq $null)
            {
                $Description = Read-Host "Please Enter Description for $Computer : "
            }
        $Computers = $Computer.split(",")
        $count = $Computers.count
        $i = 1
        If ($Server -eq $null -or $Server -eq "") {$Server = $DefaultDRAServer} #Default DRA Server
        ForEach ($Computer in $Computers)
            {
                $Percent = ($i/$count) * 100
                Show-ProgressBar -Activity "Setting $Computer's Description to $Description" -PercentComplete $Percent
                Try
                    {
                        Set-DRAComputer -Properties @{Description=$Description} -DRARestServer $Server -DRARestPort 8755 -DRAHostServer $Server -DRAHostPort 11192 -Domain "AREA52.afnoapps.usaf.mil" -Identifier $Computer -Force -ErrorAction STOP
                    }
                Catch
                    {
                        Write-Host "Couldn't set $Computer's description"
                    }
                $i++
            }
    }

Function Set-User ($User,$Property,$Value,$Server)
    {
        $Users = $User.split(",")
        $count = $Users.count
        $i = 1
        ForEach($User in $Users)
            {
                $Percent = ($i/$count) * 100
                Show-ProgressBar -Activity "Setting $User Property $Property to $Value" -PercentComplete $Percent
                $U = Get-ADUser $User
                $User = $U.Name
                if ($Server -eq $null -or $Server -eq "") {$Server = "lackland.dra.us.af.mil"} #Default DRA Server
                Try
                    {
                        Set-DRAUser -DRARestServer $Server -Properties @{$Property=$Value} -DRARestPort 8755 -DRAHostServer $Server -DRAHostPort 11192 -Domain "AREA52.afnoapps.usaf.mil"  -Identifier $User -ErrorAction STOP
                    }
                Catch
                    {
                        Write-Host "Could not Set $User $Property to $Value"
                    }
                $i++
            }
    }
Function Set-Computer ($Computer,$Property,$Value,$Server)
    {
        If ($Server -eq $null -or $Server -eq "") {$Server = $DefaultDRAServer} #Default DRA Server
        $Computers = $Computer.split(",")
        $count = $Computers.count
        $i = 1
        ForEach ($Computer in $Computers)
            {
                $Percent = ($i/$count) * 100
                Show-ProgressBar -Activity "Setting $Computer Property $Property to $Value" -PercentComplete $Percent
                
                Try
                    {
                        Set-DRAComputer -DRARestServer $Server -Properties @{$Property=$Value} -DRARestPort 8755 -DRAHostServer $Server -DRAHostPort 11192 -Domain "AREA52.afnoapps.usaf.mil"  -Identifier $Computer -ErrorAction STOP
                    }
                Catch
                    {
                        Write-Host "Could not set $Computer Property $Property value to $Value"
                    }
                $i++
            }
        
    }
Function Send-Message ($Computername,$Message,$Duration,$Sessionname)
    {
        If ($Duration -eq $null) {$Duration = 0}
        $Computers = $Computername.Split(",")
        $count = $Computers.Count
        $i = 1
        ForEach ($Computername in $Computers)
            {
                $Percent = ($i/$count) * 100
                Show-ProgressBar -Activity "Sending $Computername a message" -PercentComplete $Percent
                Try 
                    {
               
                       start-process "C:\Windows\system32\msg.exe" " /Server:$Computername $Sessionname /Time:$Duration $Message" -ErrorAction SilentlyContinue -NoNewWindow
                    }
                Catch
                    {
                        Write-Host "Could Not find computer"
                    }
                $i++
            }
    }
Function Get-LoggedOnUsers ($ComputerName)
    {
        $n = Get-wmiObject -ComputerName $ComputerName -Class Win32_ComputerSystem | Select-Object UserName
        $n = $n.UserName
        Return $n
    }
Function Get-Computer_UserIsLoggedInto ($Username)
    {
       #$computers = Get-ADComputer -Filter {Name -Like "*PTFM*"} | Select-Object Name
       $computers = Get-ADComputer -SearchBase 'OU=McGuire AFB Computers,OU=McGuire AFB,OU=AFCONUSWEST,OU=Bases,DC=AREA52,DC=AFNOAPPS,DC=USAF,DC=MIL' -Filter {(enabled -eq 'True') -and (Name -Like "*PTFM*")} | Select-Object Name
       $count = $computers.Count
       
       ForEach ($computer in $computers)
        {
            $i++
            $percent = ($i/$count) * 100
            $test = $computer.name
            progressbar -Activity "Searching $test to see if $Username is logged on" -PercentComplete $Percent
            $status = Get-ComputerStatus $test
            If ($status -eq "Online")
                {
                    $User = Get-LoggedOnUsers -ComputerName $test
                    If ($User -eq "AREA52\$Username")
                        {
                            Return $computer
                        }
                }
                
        } 
    }
Function Get-ComputerStatus ($Computername)
    {
        Try
            {
                Test-Connection -BufferSize 32 -Count 1 -ComputerName $Computername -ErrorAction Stop | Out-Null
                Return "Online"
            }
        Catch
            {
                Return "Offline"
            }
    }
Function Get-LoggedOnUsers
    {
        Param(
            [string] $Account,
            [switch]   $Logoff
            )
        $User = $null
        $Users = quser
        $max = $Users.Count
        $LOUsers = @()
        For ($i = 0; $i -lt $max; $i++)
            {
                if ($i -ne 0)
                    {
                        $Line = $Users[$i]
                        If ($Line.substring(0,1) -eq ">")
                            {
                                $CurrentLoggedOnUser = $i - 1
                            }
                        $Username = $Line.Substring(1,22)
                        $SessionName = $Line.Substring(23,19)
                        $ID = $Line.Substring(42,2)
                        $State = $Line.Substring(45,8)
                        $IDLETime = $Line.Substring(54,10)
                        $LogonTime = $Line.Substring(64,19)
                        $User = New-Object PSObject
                        $User | Add-Member -MemberType NoteProperty -Name 'Username' -Value $Username.TrimStart().TrimEnd()
                        $User | Add-Member -MemberType NoteProperty -Name 'Session Name' -Value $SessionName.TrimStart().TrimEnd()
                        $User | Add-Member -MemberType NoteProperty -Name 'ID' -Value $ID.TrimStart().TrimEnd()
                        $User | Add-Member -MemberType NoteProperty -Name 'State' -Value $State.TrimStart().TrimEnd()
                        $User | Add-Member -MemberType NoteProperty -Name 'Idle Time' -Value $IDLETime.TrimStart().TrimEnd()
                        $User | Add-Member -MemberType NoteProperty -Name 'Logon Time' -Value $LogonTime.TrimStart().TrimEnd()

                        $LOUsers += $User
                        $User = ""

                    }
            }
        
        If (!($LOUsers.'Username' -contains $Account))
            {
                If ($Account -ne "")
                    {
                        Start-Pause "$Account is not logged on" -Seconds 2
                    }
            }
        Else
            {
                $index = $LOUsers.'Username'.indexOf($Account)
                $UserID = $LOUsers[$index].'ID'
                If ($index -eq $CurrentLoggedOnUser)
                    {
                        Start-Pause "User is currently logged on, Can't logg off!" -Seconds 2
                        $Logoff = $null
                    }
                If ($Logoff.IsPresent -eq 'True')
                    {
                        logoff $UserID
                    }
            }
        
        Return $LOUsers
    }
Function Set-permission ($Folder,$Group,$Permission)
    {
        $ACL = Get-Acl $Folder
        $AccessRule = New-Object System.Security.AccessControl.FileSystemAccessRule($Group,$Permisson,"ContainerInherit,Objectinherit","none","Allow")
        $ACL.AddAccessRule($AccessRule)
        Set-Acl $Folder $ACL
    }
<# NIC Functions#>
Function Test-IsWLANinRange ($NameofWLAN)
    {
        $APs = $null
        $WLANS = netsh wlan  show network  mode=bssid | Select-String SSID
        $NumberOfAPs = ($WLANS.Count)/2
        $APs = @()
        $max = $WLANS.Count
        For ($i = 0; $i -le $max; $i++)
            {
                If (($i % 2) -eq 0)
                    {
                        $AP = $WLANS[$i]
                
                        if ($AP -ne $null)
                            {
                                $AP = $AP.ToString()
                                $c = $AP.IndexOf(":") + 2
                                $Junk = $AP.substring(0,$c)
                                $AP = $AP.replace($Junk,"")
                                $APs += $AP
                            }
                    }
            }
        If ($APs -contains $NameofWLAN)
            {
                Return 'True'
            }
        Else
            {
                return 'False'
            }
    }
Function Export-WiFi_Profile ($NetworkName,$ExportFolder)
    {
        Start-process "netsh wlan export profile `"$NetworkName`" key=clear folder=`"$ExportFolder`""
    }
Function Connect-WiFi_Network ($WiFiProfile)
    {
        Write-Host "`"$WiFiProfile`""
        Start-Process "netsh" "wlan add profile filename=`"$WiFiProfile`""
    }
Function Disable-Adapter ($adapter)
    {
        Disable-NetAdapter -Name $adapter -Confirm:$false
    }
Function Enable-Adapter ($adapter)
    {
        Enable-NetAdapter -Name $adapter -Confirm:$false
    }
<#Mount Network Drives #>
Function Get-FreeDriveLetter
    {
        $DriveLetters = "ZYXWVUTSRQPONMLKJIHGFED".ToCharArray()
        $UsedDriveLetters = Get-PSDrive | Select-Object Name
        $UsedDriveLetters = $UsedDriveLetters.Name
        ForEach ($Letter in $DriveLetters)
             {
                If (!($UsedDriveLetters -contains $Letter))
                    {
                        Return $Letter
                        
                    }                            
             }
    }
Function Remove-OfflineDrives ($UNC)
    {
        $OfflineDrives = Get-SmbMapping | Where-Object {$_.Status -eq "Unavailabe" -and $_.RemotePath -eq $UNC}
        ForEach ($Drive in $OfflineDrives)
            {
                $Name = $Drive.LocalPath.Substring(0,1)
                Remove-PSDrive -Name $Name
            }
    }
Function Test-NetworkDrive ($UNC,$Count)
    {
        $NetworkDrives = Get-SmbMapping | Where-Object {$_.Status -eq "OK"}
        If ($Count -eq $null){$Count = 1}
        $RemotePaths = $NetworkDrives.RemotePath
        ForEach ($P in $RemotePaths)
            {
                If ($P -eq $UNC)
                    {
                        $i++
                    }
            }
        
        If ($i -ge $Count)
            {
                Return 'True'
            }
        Else
            {
                Return 'False'
            }
    }
Function Mount-NetworkDrive ($DriveName,$UNC,$Count,[Switch]$auto)
    {
        If ((Test-NetworkDrive -UNC $UNC -Count $Count) -eq 'True')
            {
                Return "A mapped drive already exists to this network path"
            }
        $FirstFreeDriveLetter = Get-FreeDriveLetter
        
        If ($auto)
            {
                $DriveName = Get-FreeDriveLetter
                
            }
        
        Try
            {
                New-PSDrive -Name $DriveName -PSProvider FileSystem -Root $UNC -Scope Global -Persist -ErrorAction STOP
            }
        Catch
            {
                Write-Host "Could not mount drive"
            }
    }

Function Dismount-NetworkDrive ($DriveName)
    {
        Remove-PSDrive -Name $DriveName -Scope Global
    }
Function Test-GroupMemberShip ($Group,$User)
    {
        $List = @()
        Try
            {
                $Members = Get-ADGroupMember $Group -Recursive -ErrorAction STOP
            }
         Catch
                    {
                        Set-Clipboard -Value "514fss.scoclientservicecenter@us.af.mil"
                        pause -Message1 "While Active Directory appears to be installed, it is not functioning at this time. Unfortunately we can not continue. If you continue to get this error contact 514 SCO at `(609`)754-5217." -Message2 "Active Directory Error!"
                        exit
                    }
        ForEach ($Member in $Members)
            {
                $List += $Member.Name
            }
        $User = (Get-ADUser $User).Name
        If ($List -contains $User)
            {
                Return "True"
            }
        Else
            {
                Return "False"
            }
    }
Function New-User ($Username,$Password)
    {
        $Password = ConvertTo-SecureString $Password -AsPlainText -Force
        $Credentials = New-Object System.Management.Automation.PSCredential ($Username, $Password)
        Return $Credentials
    }

Function Get-ComputerDescription
    {
        $Description = Get-WmiObject -Class Win32_OperatingSystem | Select Description
        $Description = $Description.Description
        Return $Description    
    }
Function Get-Unit
    {
        $X = Get-ComputerDescription
        $Len = $X.Length
        $comma = $X.IndexOf(',') + 1
        $X = $X.Substring($comma,$Len - $comma)
        $comma = $X.IndexOf(',')
        $X = $X.Substring(0,$comma)
        $X = $X.Trim()
        Return $X

    }

Function Get-SerialNumber
    {
        $x = Get-WmiObject Win32_BIOS | Select-Object SerialNumber
        Return $x.serialNumber
    }
Function Set-ComputerName ($Name)
    {
        Write-Output "Computername will be set to $Name"
        (Get-WmiObject win32_computersystem).Rename($Name)
    }

Function Read-CSV ($CSVFile)
    {
        $CSV = Get-Content $CSVFile
        $CSVArray = @()
        $Count = $CSV.Count        
        For ($i = 0; $i -lt $Count; $i++)
            {
                $Percent = ($i/$CSV.Count) * 100
                $Percent = [math]::Round($Percent)
                progressbar -Activity "Reading Data from file" -PercentComplete $Percent

                if ($i -eq 0)
                    {
                        $Lables = $CSV[0]
                        $Lables = $Lables.Replace('"','')
                        $Lables = $Lables.Split(',')
                        $Columns = $Lables.Count - 1
                    }
                Else
                    {
                        $Line = New-Object PSObject
                        $Row = $CSV[$i]
                        $Row = $Row.Replace('"','')
                        $Row = $Row.Split(',')
                        For ($n = 0; $n -le $Columns; $n++)
                            {
                                #write-host "Label is equal to $Lables[$n] ."
                                if ($Lables[$n] -ne $null -or $Lables[$n] -ne "")
                                    {
                                        $Line | Add-Member -MemberType NoteProperty -Name $Lables[$n] -Value $Row[$n]
                                    }
                               
                            }
                        $CSVArray += $Line
                            
                    }
                
                
                
            }
        Return $CSVArray
    }
Function Get-ExcelFiles ($ExcelFile,$key)
    {
        $Line = $null
        $CSVTable = $null
        $CSVTable = @{}
        $Excel = New-Object -ComObject Excel.Application
        $WorkBook = $Excel.Workbooks.Open("$ExcelFile")
        $WorkSheet = $WorkBook.Worksheets.Item(1) #Select the first work sheet
        $lastRow = $WorkSheet.UsedRange.rows.count
        $lastColumn = $WorkSheet.UsedRange.columns.count
        #Write-Host "There are $lastColumn Columns and $LastRow Rows"
        For ($n=1;$n -le $lastRow; $n++)
            {
                $Percent = ($n/$LastRow) * 100
                $Percent = [math]::Round($Percent)
                progressbar -Activity "Reading Data from file" -PercentComplete $Percent
                For ($i=1;$i-le $lastColumn; $i++)
                    {
                        If ($i -lt $lastColumn)
                            {
                                $Line = $Line + $WorkSheet.Cells.Item($n,$i).Text + ","
                            }
                        Else
                            {
                                $Line = $Line + $WorkSheet.Cells.Item($n,$i).Text
                                
                            }
                    }
                If ($n -eq 1)
                    {
                        $Headings=$Line.Split(",")
                        $X_Max = $Headings.count
                        #$HeadingsKey = $Headings.indexof($key)
                        $Line=""
                    }
                Else
                    {
                        $Line = $Line.Split(",")
                        $Row = New-Object PSObject
                        For ($x = 0; $x -le $X_Max; $x++)
                            {
                                If ($Headings[$x] -ne $null)
                                    {
                                        If (!($Headings[$x] -eq ""))
                                            {
                                                #Write-Host "Hit"
                                                #$Line[$x] = " "
                                                $Row | Add-Member -MemberType NoteProperty -Name $Headings[$x] -Value $Line[$x]
                                            }
                                        
                                    }
                            }
                    }
                
                If ($Row -ne $null)
                    {
                        $CSVTable[$n-1] = $Row
                        $Row = $null
                        $Line=""
                    }
            }

        $WorkBook.Close()
        $Excel.Quit()
        Return $CSVTable
    }
Function Open-ExcelFile ($ExcelFile)
    {
        $Line = $null
        $CSVTable = $null
        $CSVTable = @()
        $Excel = New-Object -ComObject Excel.Application
        $WorkBook = $Excel.Workbooks.Open("$ExcelFile")
        $WorkSheet = $WorkBook.Worksheets.Item(1) #Select the first work sheet
        $lastRow = $WorkSheet.UsedRange.rows.count
        $lastColumn = $WorkSheet.UsedRange.columns.count
        For ($n=1;$n -le $lastRow; $n++)
            {
                $Percent = ($n/$LastRow) * 100
                $Percent = [math]::Round($Percent)
                progressbar -Activity "Reading Data from file" -PercentComplete $Percent
                For ($i=1;$i-le $lastColumn; $i++)
                    {
                        If ($i -lt $lastColumn)
                            {
                                $Line = $Line + $WorkSheet.Cells.Item($n,$i).Text + ","
                            }
                        Else
                            {
                                $Line = $Line + $WorkSheet.Cells.Item($n,$i).Text
                            }
                    }
                $CSVTable[$n] = $Line
                $CSVTable[$n] = $CSVTable[$n].Split(",")
                $Line=""
            }

        $WorkBook.Close()
        $Excel.Quit()
        Return $CSVTable
    }
Function Compare-Array ($Array1, $Array2)
    {
        $TotalElements = $Array1.count
        forEach ($Element in $Array2)
            {
                If ($Array1 -contains $Element)
                    {
                        $Match++
                    }
            }
        $percentage = (($Match/$TotalElements) * 100)
        $percentage = [Math]::Round($percentage,2)
        Return $percentage
    }
Function New-Varibles ($Varibles)
    {
        ForEach ($Varible in $Varibles)
            {
                $Varible = $Varible.Split("=")
                New-Variable -Name $Varible[0] -Value $Varible[1] -Force -Scope script
            }
    }
Function Get-Ownership ($Folder)
    {
        takeown /F $Folder /R /D Y
    }
Function Get-DriveLetter ($Label)
    {
        Try
            {
                $DriveLetter = Get-Volume -FileSystemLabel $Label -ErrorAction Ignore
            }
        Catch
            {
                $DriveLetter = $null
            }
        
        If ($DriveLetter -ne $null)
            {
                $DriveLetter = $DriveLetter.DriveLetter + ":"
            }
        Return $DriveLetter
    }

Function Copy-ItemExplorer 
    {
        param(
                [string]$source,
                [string]$destination,
                [int]$CopyFlags
            ) 
        
        
        $objShell = New-Object -ComObject 'Shell.Application'    
        $objFolder = $objShell.NameSpace((gi $destination).FullName)
        $objFolder.CopyHere((gi $source).FullName,$CopyFlags)
    }

Function New-GUI_TextBox ($Input_Type,$banner,$FormX,$Formy,$OkX,$Oky,$CanX,$CanY,$TextX,$TextY,$Multi){

    ### Creating the form with the Windows forms namespace
    Add-Type -AssemblyName System.Windows.Forms
    Add-Type -AssemblyName System.Drawing
    $form = New-Object System.Windows.Forms.Form
    $form.Text = $banner ### Text to be displayed in the title
    $form.Size = New-Object System.Drawing.Size($FormX,$FormY) ### Size of the window
    $form.StartPosition = 'CenterScreen'  ### Optional - specifies where the window should start
    $form.FormBorderStyle = [System.Windows.Forms.FormBorderStyle]::FixedToolWindow  ### Optional - prevents resize of the window
    $form.Topmost = $true  ### Optional - Opens on top of other windows

    ### Adding an OK button to the text box window
    $OKButton = New-Object System.Windows.Forms.Button
    $OKButton.Location = New-Object System.Drawing.Point($OkX,$OkY) ### Location of where the button will be
    $OKButton.Size = New-Object System.Drawing.Size(75,23) ### Size of the button
    $OKButton.Text = 'OK' ### Text inside the button
    $OKButton.DialogResult = [System.Windows.Forms.DialogResult]::OK
    $form.AcceptButton = $OKButton
    $form.Controls.Add($OKButton)

    ### Adding a Cancel button to the text box window
    $CancelButton = New-Object System.Windows.Forms.Button
    $CancelButton.Location = New-Object System.Drawing.Point($CanX,$CanY) ### Location of where the button will be
    $CancelButton.Size = New-Object System.Drawing.Size(75,23) ### Size of the button
    $CancelButton.Text = 'Cancel' ### Text inside the button
    $CancelButton.DialogResult = [System.Windows.Forms.DialogResult]::Cancel
    $form.CancelButton = $CancelButton
    $form.Controls.Add($CancelButton)

    ### Putting a label above the text box
    $label = New-Object System.Windows.Forms.Label
    $label.Location = New-Object System.Drawing.Point(10,10) ### Location of where the label will be
    $label.AutoSize = $True
    $Font = New-Object System.Drawing.Font("Arial",12,[System.Drawing.FontStyle]::Bold) ### Formatting text for the label
    $label.Font = $Font
    $label.Text = $Input_Type ### Text of label, defined by the parameter that was used when the function is called
    $label.ForeColor = 'Red' ### Color of the label text
    $form.Controls.Add($label)

    ### Inserting the text box that will accept input
    $textBox = New-Object System.Windows.Forms.TextBox
    $textBox.Location = New-Object System.Drawing.Point(10,40) ### Location of the text box
    $textBox.Size = New-Object System.Drawing.Size($TextX,$TextY) ### Size of the text box
    $textBox.Multiline = $Multi ### Allows multiple lines of data
    $textbox.AcceptsReturn = $Multi ### By hitting enter it creates a new line
    $textBox.ScrollBars = "Vertical" ### Allows for a vertical scroll bar if the list of text is too big for the window
    $form.Controls.Add($textBox)

    $form.Add_Shown({$textBox.Select()}) ### Activates the form and sets the focus on it
    $result = $form.ShowDialog() ### Displays the form 

    ### If the OK button is selected do the following
    if ($result -eq [System.Windows.Forms.DialogResult]::OK)
    {
        ### Removing all the spaces and extra lines
        $x = $textBox.Lines | Where{$_} | ForEach{ $_.Trim() }
        ### Putting the array together
        $array = @()
        ### Putting each entry into array as individual objects
        $array = $x -split "`r`n"
        ### Sending back the results while taking out empty objects
        Return $array | Where-Object {$_ -ne ''}
    }

    ### If the cancel button is selected do the following
    if ($result -eq [System.Windows.Forms.DialogResult]::Cancel)
    {
        Write-Host "User Canceled" -BackgroundColor Red -ForegroundColor White
        Write-Host "Press any key to exit..."
        $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
        Exit
    }

}
Function Show-ProgressBar
    {
        param(
                [string]$Activity,
                [int]$PercentComplete
             )   
        $MOD = ($PercentComplete % 10)
        If ($MOD -eq 0)
            {
                Write-Progress -Activity $Activity -PercentComplete $PercentComplete
            }
    }

#ProgressBar $Activity $PercentComplete

Function Get-TDate
    {
        $Date = Get-Date
        $Day = $Date.Day
        $Month = $Date.Month
        $Month = (Get-Culture).DateTimeFormat.GetAbbreviatedMonthName($Month)
        $Year = $Date.Year
        Return "$Day $Month $Year"
    }
Function Start-Pause ($Message1, $Message2, $Seconds) 
    {
        If ($Seconds -eq $null) {$Seconds = 0}
        $Shell = New-Object -ComObject "WScript.Shell"
        $Button = $Shell.Popup($Message1, $Seconds, $Message2, 0)
        Return
    }
Function Pause-Script ($Message1, $Message2, $Seconds) 
    {
        If ($Seconds -eq $null) {$Seconds = 0}
        $Shell = New-Object -ComObject "WScript.Shell"
        $Button = $Shell.Popup($Message1, $Seconds, $Message2, 0)
        Return
    }
Function Get-File
    {
        param (
                  [string]$Filter,
                  [string]$path
              )
        If ($path -eq ""){$path='Desktop'}
        Add-Type -AssemblyName System.Windows.Forms
        $FileBrowser = New-Object System.Windows.Forms.OpenFileDialog -Property @{ 
        InitialDirectory = [Environment]::GetFolderPath($path)
        Filter = $Filter
        }
        
        $null = $FileBrowser.ShowDialog()
        Return $FileBrowser.FileName
    }
Function Get-ExcelFile ($ExcelFile)
    {
        $CSVTable = @{}
        $Excel = New-Object -ComObject Excel.Application
        $WorkBook = $Excel.Workbooks.Open("$ExcelFile")
        $WorkSheet = $WorkBook.Worksheets.Item(1) #Select the first work sheet
        $lastRow = $WorkSheet.UsedRange.rows.count
        $lastColumn = $WorkSheet.UsedRange.columns.count

        for ($n=1;$n -le $lastRow; $n++)
            {
                $Percent = ($n/$LastRow) * 100
                $Percent = [math]::Round($Percent)
                progressbar -Activity "Reading Data from file" -PercentComplete $Percent
                for ($i=1;$i-le $lastColumn; $i++)
                    {
                        If ($i -lt $lastColumn)
                            {
                                $Line = $Line + $WorkSheet.Cells.Item($n,$i).Text + ","
                            }
                        Else
                            {
                                $Line = $Line + $WorkSheet.Cells.Item($n,$i).Text
                            }
                    }
                $CSVTable[$n] = $Line
                $CSVTable[$n] = $CSVTable[$n].Split(",")
                $Line=""
            }

        $WorkBook.Close()
        $Excel.Quit()
        $AddDRAComputer = @()
        #Return $CSVTable
        $Record = $CSVTable.Count
        For ($i=2; $i -le $Record; $i++)
            {
                $Percent = ($i/$Record) * 100
                $Percent = [math]::Round($Percent)
                progressbar -Activity "Processing Data from file" -PercentComplete $Percent

                $Row = New-Object PSObject
                $Row | Add-Member -MemberType NoteProperty -Name "Cust Nbr" -Value $CSVTable[$i][0] 
                $Row | Add-Member -MemberType NoteProperty -Name "Item Desc" -Value $CSVTable[$i][1]
                $Row | Add-Member -MemberType NoteProperty -Name "Loc" -Value $CSVTable[$i][2]
                $Row | Add-Member -MemberType NoteProperty -Name "Mfr" -Value $CSVTable[$i][3]
                $Row | Add-Member -MemberType NoteProperty -Name "Model" -Value $CSVTable[$i][4]
                $Row | Add-Member -MemberType NoteProperty -Name "Serial Nbr" -Value $CSVTable[$i][5]
                $Row | Add-Member -MemberType NoteProperty -Name "Sub Loc" -Value $CSVTable[$i][6]
                $Row | Add-Member -MemberType NoteProperty -Name "REPLACED" -Value $CSVTable[$i][7]
                $Row | Add-Member -MemberType NoteProperty -Name "S/N" -Value $CSVTable[$i][8]
                $Row | Add-Member -MemberType NoteProperty -Name "MAC ADDRESSr" -Value $CSVTable[$i][9]
                $Row | Add-Member -MemberType NoteProperty -Name "REMARKS" -Value $CSVTable[$i][10]
                
                $AddDRAComputer += $Row
                $Row = $null
            }
        Return $AddDRAComputer
    }
Function Save-FileName
    {  
        param
              (
                [string]$filter,
                [string]$path
              ) 
        [System.Reflection.Assembly]::LoadWithPartialName("System.windows.forms") |
        Out-Null
        If ($path -eq ""){$path='Desktop'}
        $SaveFileDialog = New-Object System.Windows.Forms.SaveFileDialog
        #$SaveFileDialog.initialDirectory = $path
        $SaveFileDialog.filter = $Filter
        $SaveFileDialog.ShowDialog() | Out-Null
        $SaveFileDialog.filename
        
    }
Function Get-Folder
    {  
        param
              (
                [string]$Description,
                [string]$Root
              ) 
        [System.Reflection.Assembly]::LoadWithPartialName("System.windows.forms") |
        Out-Null
        If ($Root -eq "" -or $Root -eq $null){$Root = 'Desktop'}
        $SaveFolderDialog = New-Object System.Windows.Forms.FolderBrowserDialog
        $SaveFolderDialog.RootFolder = $Root
        $SaveFolderDialog.Description = $Description
        $SaveFolderDialog.ShowDialog() | Out-Null
        
        Return $SaveFolderDialog.SelectedPath
        
    }
Function Get-Menu
    {
        param(
                $Selections,
                [string]$MenuHeader,
                [string]$LabelText,
                [string]$Default,
                [String]$MultipleSelections
             )
 
        IF ($Path.length -eq 0) {$Path = $PSScriptRoot}
        Add-Type -AssemblyName System.Windows.Forms
        Add-Type -AssemblyName System.Drawing

        $form = New-Object System.Windows.Forms.Form
        $form.Text = $MenuHeader
        $form.Size = New-Object System.Drawing.Size(450,300)
        $form.StartPosition = 'CenterScreen'

        $okButton = New-Object System.Windows.Forms.Button
        $okButton.Location = New-Object System.Drawing.Point(75,220)
        $okButton.Size = New-Object System.Drawing.Size(75,23)
        $okButton.Text = 'OK'
        $okButton.DialogResult = [System.Windows.Forms.DialogResult]::OK
        $form.AcceptButton = $okButton
        $form.Controls.Add($okButton)

        $cancelButton = New-Object System.Windows.Forms.Button
        $cancelButton.Location = New-Object System.Drawing.Point(150,220)
        $cancelButton.Size = New-Object System.Drawing.Size(75,23)
        $cancelButton.Text = 'Cancel'
        $cancelButton.DialogResult = [System.Windows.Forms.DialogResult]::Cancel
        $form.CancelButton = $cancelButton
        $form.Controls.Add($cancelButton)

        $label = New-Object System.Windows.Forms.Label
        $label.Location = New-Object System.Drawing.Point(10,20)
        $label.Size = New-Object System.Drawing.Size(280,20)
        $label.Text = $LabelText
        $form.Controls.Add($label)

        $listBox = New-Object System.Windows.Forms.ListBox
        $listBox.Location = New-Object System.Drawing.Point(10,40)
        $listBox.Size = New-Object System.Drawing.Size(400,20)
        $listBox.Height = 180
        If ($MultipleSelections) { $listBox.SelectionMode = 'MultiExtended'}
        
        $Max = $Selections.Count
        $Checkboxes = @()
        $y = 20
        
        For ($I = 1; $I -le $Max; $I++)
            {
                [void] $listBox.Items.Add($Selections[$I-1])
                
            }
        # $groupBox.size = New-Object System.Drawing.Size(200,(40*$checkboxes.Count))
        
        $form.Controls.Add($listBox)
        $form.Topmost = $true
        $result = $form.ShowDialog()

        If ($result -eq [System.Windows.Forms.DialogResult]::OK)
            {
        
                $Selected = $listBox.SelectedItems
            }
        If ($result -eq [System.Windows.Forms.DialogResult]::Cancel)
            {
        
                Exit
            }

        If ($Selected -eq $null){$Selected = $Default}
        
        
        Return $Selected

    }
Function Get-Bldg ($LocString)
    {
        $Index = $LocString.IndexOf("B")
        $Start = $Index+1
        $End = 4
        $X = $LocString.SubString($Start,$End)
        Return $X
    }

Function Get-Rm ($LocString)
    {
        $Index = $LocString.IndexOf("R")
        $Start = $Index+1
        $End = $LocString.Length - $Start
        $X = $LocString.SubString($Start,$End)
        Return $X
    }
Function Get-ComputerName($Name, $CType)
    {
        $CT = @{
                    "DESKTOP" = "W";
                    "NOTEBOOK" = "L";
                    "TABLET" = "T"
                }
        $Start = ($Name.Length - 9)
        $End = 9
        Return "PTFM"+$CT[$CType] +"-"+$Name.SubString($Start,$End)
    }
Function Display-ComputerName
    {
        $ComputerName = $env:COMPUTERNAME
        Return $ComputerName
    }
Function Get-SerialNumber
    {
        $SerialNumber = (Get-WmiObject Win32_BIOS | Select-Object SerialNumber).SerialNumber
        Return $SerialNumber
    }
Function Get-MAC ([switch]$colon)
    {
        $AdapterNames = Get-NetAdapter | Where-Object {$_.status -eq "UP"}
        If ($AdapterNames -eq $null)
            {
                $EthernetAdapter = "NO CONNECTION"
            }
        Else
            {
                $AdapterNames = $AdapterNames.Name
                $EthernetAdapter = (Get-Netadapter -Name $AdapterNames).MacAddress
            }
        If ($colon.IsPresent -eq $True) {$EthernetAdapter = $EthernetAdapter.replace("-",":")}
        Return $EthernetAdapter
    }
Function Get-SCOInfo
    {
        $SerialNumber = Get-SerialNumber
        $ComputerName = Display-ComputerName
        $EthernetAdapter = Get-MAC
        $Model = Get-Model
        $Info = "Computer Model: $Model;Serial Number: $SerialNumber;Computer Name: $ComputerName;MAC ADDRESS  : $EthernetAdapter".Replace(";","`r`n")
        Start-Pause -Message1 $Info -Message2 "Your Computer Info:" 
    }
Function Export-CSVFile ($Array,$File)
    {
         $Array | Export-Csv $File -NoTypeInformation -force -Append
    }
Function Get-OfflinePrinter
    {
        Try 
            {
                $OffLine_Printers = Invoke-Command -computername PTFM-QS-514V -ErrorAction Stop -ScriptBlock {
                        $OffLine_Printers = @()
                        $Printers = Get-Printer
                        $Activity = 'Finding Offline Printers'
                        $NumOfPrinters = $Printers.count
                        $i = 0 #Initialize incrementor
                        ForEach ($Printer in $Printers)
                            {
                                $i++
                                $PercentComplete = ($i/$NumOfPrinters) * 100 #Calculate number of printers scanned
                                Write-Progress -Activity $Activity -PercentComplete $PercentComplete
                                $PrinterJob = Get-PrintJob -PrinterName $Printer.Name 
                                ForEach ($Job in $PrinterJob)
                                    {
                
                                        If ($Job.JobStatus -like "*Error*" -eq 'True')
                                            {
                                                $OffLine_Printers += $Printer
                                                break
                                            }
                                    }
        
        
                            }
                        Return $OffLine_Printers
        
                    }
            }
        Catch
            {
                Start-Pause "PTFM-QS-514V is offline" -second 5
                break
            } 
        $File = "\\ptfm-stm-san3v\514MSG\514MSG-G\514SCO\IP Printers\514Printers.xlsx"
        $Printers = Import-Excel $File
        $MACS = @()
        ForEach($Printer in $OffLine_Printers)
            {
                $MAC = ($Printers | Where-Object {$_.ShareName -eq $Printer.ShareName}).'MAC Address'
                $MACS += $MAC
            }
        $WhiteList = @()
        $max = $MACS.Count
        For ($i = 0;$i -lt $max; $i++)
            {
                $MAC = $MACS[$i]
                If ($MAC -ne $null)
                    {
                        $Row = New-Object PSObject
                        $Row | Add-Member -MemberType NoteProperty -Name "MACAddress" -Value $MAC 
                        $Row | Add-Member -MemberType NoteProperty -Name "EndPointPolicy" -Value "" 
                        $Row | Add-Member -MemberType NoteProperty -Name "IdentityGroup" -Value 'PRINTERS'
                        $Row | Add-Member -MemberType NoteProperty -Name "PortalUser.GuestType" -Value ""
                        $Row | Add-Member -MemberType NoteProperty -Name "Description" -Value "Workstation"
                        $Row | Add-Member -MemberType NoteProperty -Name "PortalUser.Location" -Value ""
                        $Row | Add-Member -MemberType NoteProperty -Name "PortalUser.GuestStatus" -Value ""
                        $Row | Add-Member -MemberType NoteProperty -Name "StaticAssignment" -Value "TRUE"
                        $Row | Add-Member -MemberType NoteProperty -Name "User-Name" -Value $MAC
                        $Row | Add-Member -MemberType NoteProperty -Name "DeviceRegistrationStatus" -Value ""
                        $Row | Add-Member -MemberType NoteProperty -Name "PortalUser.CreationType" -Value ""
                        $Row | Add-Member -MemberType NoteProperty -Name "AUPAccepted" -Value ""
                        $Row | Add-Member -MemberType NoteProperty -Name "PortalUser.EmailAddress" -Value ""
                        $Row | Add-Member -MemberType NoteProperty -Name "PortalUser.PhoneNumber" -Value ""
                        $Row | Add-Member -MemberType NoteProperty -Name "FirstName" -Value ""
                        $Row | Add-Member -MemberType NoteProperty -Name "ip" -Value ""
                        $Row | Add-Member -MemberType NoteProperty -Name "Device Type" -Value "Device Type#All Device Types"
                        $Row | Add-Member -MemberType NoteProperty -Name "host-name" -Value ""
                        $Row | Add-Member -MemberType NoteProperty -Name "StaticGroupAssignment" -Value "TRUE"
                        $Row | Add-Member -MemberType NoteProperty -Name "MDMEnrolled" -Value ""
                        $Row | Add-Member -MemberType NoteProperty -Name "MDMOSVersion" -Value ""
                        $Row | Add-Member -MemberType NoteProperty -Name "PortalUser.LastName" -Value ""
                        $Row | Add-Member -MemberType NoteProperty -Name "PortalUser.GuestSponsor" -Value ""
                        $Row | Add-Member -MemberType NoteProperty -Name "EmailAddress" -Value ""
                        $Row | Add-Member -MemberType NoteProperty -Name "PortalUser" -Value ""
                        $Row | Add-Member -MemberType NoteProperty -Name "PortalUser.FirstName" -Value ""
                        $Row | Add-Member -MemberType NoteProperty -Name "BYODRegistration" -Value ""
                        $Row | Add-Member -MemberType NoteProperty -Name "MDMServerName" -Value ""
                        $Row | Add-Member -MemberType NoteProperty -Name "LastName" -Value ""
                        $Row | Add-Member -MemberType NoteProperty -Name "MDMServerID" -Value ""
                        $Row | Add-Member -MemberType NoteProperty -Name "Location" -Value ""
                        $WhiteList += $Row
                        $Row = $null
                    }
            }
        $WhiteList | Export-Csv -Path "\\ptfm-stm-san3v\514AMW\514AMW-S\514 Share\514 SCO Tools\Offline Printers\Offline_Printers_WhiteList.csv" -NoTypeInformation -Force
        $OffLine_Printers.Name | Out-File "\\ptfm-stm-san3v\514AMW\514AMW-S\514 Share\514 SCO Tools\Offline Printers\514_Offline_Printers.txt" -Force
    }
<# End of Functions #>