PowerShell Scripts
(Updated: 2019-09-13)
Show Saved WiFi Passwords
# Run PowerShell as Administrator, copy and paste code below with Wireless card enabled.
(netsh wlan show profiles) | 
Select-String "\:(.+)$" |
%{$name=$_.Matches.Groups[1].Value.Trim(); $_} | 
%{(netsh wlan show profile name="$name" key=clear)}  |
Select-String "Key Content\W+\:(.+)$" | 
%{$pass=$_.Matches.Groups[1].Value.Trim(); $_} |
%{[PSCustomObject]@{ PROFILE_NAME=$name;PASSWORD=$pass }} | 
Format-Table -AutoSize 
# Receiving an error on Windows 7, is because doesn't cast as an array before
# attempting to index, this code should work
(netsh wlan show profiles) | 
Select-String "\:(.+)$" | 
%{$name=$_.Matches | 
% {$_.Groups[1].Value.Trim()}; $_} |%{(netsh wlan show profile name="$name" key=clear)} | Select-String "Key Content\W+\:(.+)$" | 
%{$pass=$_.Matches |
% {$_.Groups[1].Value.Trim()}; $_} | 
%{[PSCustomObject]@{ PROFILE_NAME=$name;PASSWORD=$pass }} |
Format-Table -AutoSize
 
List Users by Last Logon
$Servername = Read-Host 'Enter server name?' 
# Check Os Version 
$OSCheck = (Get-WmiObject -comp $Servername  -class Win32_OperatingSystem ).caption 
#get the current directory location
$scriptPath = split-path -parent $MyInvocation.MyCommand.Definition
$FilePath = "$scriptPath\Userinfo1.csv"  
ForEach ($Item in $Servername) 
{ 
# Check OS version 
    If ($OSCheck  -notmatch "server 2003" )
    { 
    # Setup Global Variables
    $ppath1 = "$Item\c$\users"
  
    #gets the subdirectories in the current directory and generate CSV Out Put File.
    Get-Childitem \\$ppath1\*  | select-object Name ,LastWriteTime  | sort LastWriteTime -descending |Export-CSV $FilePath 
    } 
 
        Else 
 
        {
        # Setup Global Variables 
         $ppath1 = "$Item\c$\Documents and Settings"
         #gets the subdirectories in the current directory and change the date format to MMDDYYYY , generate CSV Out Put File.
            Get-ChildItem \\$ppath1\*  | Select-Object Name,{$_.LastWriteTime.toString("MM-dd-yyyy hh:mm")}  |Export-CSV $FilePath  
        } 
Write-host "Challenge Completed !  !" 
}
 
Show Folder Sizes
$LogFile = "C:\Users\Jason Knappenberger\Desktop\DailyFileWatch.csv"
$Path = "C:\Users\Jason Knappenberger\Desktop"
$Result = [PSCustomObject]@{
    Path = $Path
    Date = Get-Date -Format "dd/MM/yyyy"
    Size = "{0:N2} MB" -f ((Get-ChildItem $Path -Recurse | Measure-Object Length -Sum).Sum / 1mb)
}
$Result | Export-Csv $LogFile -NoTypeInformation
$Path = "C:\Users\Jason Knappenberger\Documents">
$Result = [PSCustomObject]@{
    Path = $Path
    Date = Get-Date -Format "dd/MM/yyyy"
    Size = "{0:N2} MB" -f ((Get-ChildItem $Path -Recurse | Measure-Object Length -Sum).Sum / 1mb)
}
$Result | Export-Csv $LogFile -Append -NoTypeInformation
 
Install Java
# For 32 bit Java
$JavaFile = [pscustomobject]@{
    JavaVersion = ''
    FileName = ''
    DownloadURL =  $((Invoke-WebRequest 'http://www.java.com/en/download/manual.jsp').links | where innerHTML -like "Windows Offline" | select href).href
} 
# for 64 bit Java
$JavaFile = [pscustomobject]@{
    JavaVersion = ''
    FileName = ''
    DownloadURL =  $((Invoke-WebRequest 'http://www.java.com/en/download/manual.jsp').links | where innerHTML -like "Windows Offline (64-bit)" | select href).href
} 
function CheckHistory ($fileurl,$path){
    $history=Get-Content "$path"
    $r = $false
    Foreach ($historicurl in $history){
        if ($historicurl -eq $fileurl){
            $r = $true
        }
    }
    return $r
}
$JavaFile.FileName = "tempinstaller$(get-date -Format yyMMddmm).exe"
Invoke-WebRequest $JavaFile.DownloadURL -OutFile ("$TempDownloadLocation\"+ $JavaFile.FileName) -ev $DLErr
if($DLErr){Exit}
$TempFileName = $JavaFile.FileName
$JavaFile.JavaVersion = get-item ("$TempDownloadLocation\"+ $JavaFile.FileName) | select -ExpandProperty versioninfo | select -ExpandProperty productversion
$JavaFile.FileName = "jre1."+(((Select-String -Pattern '[0-9]u[0-9]+' -InputObject (get-item ("$TempDownloadLocation\$TempFileName")   | select -ExpandProperty versioninfo | select -ExpandProperty originalfilename)) |
ForEach-Object -Process {
  $_.Matches
} |
ForEach-Object -Process {
  $_.Value
}) -replace 'u', '.0_')
Rename-Item -Path "$TempDownloadLocation\$TempFileName" -NewName ($JavaFile.FileName+".exe")
if(Test-Path -path ("$TempDownloadLocation\"+$JavaFile.FileName+".exe")){
    add-content "$TempDownloadLocation\javahistorylog.log" $JavaFile.DownloadURL
}
$MsiFilePathTemp = "$env:LOCALAPPDATA\Oracle\Java\" -replace 'Local', 'LocalLow'
Start-Process -FilePath ("$TempDownloadLocation\"+$JavaFile.FileName+".exe") -ArgumentList '/s'
while(!(Test-Path ("$MsiFilePathTemp\"+$JavaFile.FileName+"\"+$JavaFile.FileName+".msi")))
{
  Start-Sleep -Seconds 1.5
}
Copy-Item -Path ("$MsiFilePathTemp\"+$JavaFile.FileName+"\"+$JavaFile.FileName+".msi") -Destination $MsiFilePathOut -Force -ErrorVariable $CDR
if($CDR){
    exit
}
Get-Process -Name $JavaFile.FileName | Stop-Process
While (Get-Process -Name $JavaFile.FileName -ErrorAction SilentlyContinue)
{
  Start-Sleep -Seconds 2
}
Remove-Item -Path ("$TempDownloadLocation\"+$JavaFile.FileName+".exe") -Force
$MSIFile = ("$MsiFilePathOut\"+$JavaFile.FileName+".msi")
 
Update Java
param([switch] $UninstallFirst,
      [switch] $UninstallOnly,
      [switch] $NoInstall,
      [switch] $Force32bit)
$ErrorActionPreference = 'Stop'
$Script:LogFile      = 'JavaUpdate.log'
$Script:ConfigFile   = 'JavaUpdate.config.txt'
$Script:LastId32File = 'JavaUpdateLastID32.txt'
$Script:LastId64File = 'JavaUpdateLastID64.txt'
## Author: Joakim Svendsen, Copyright 2013, all rights reserved.
## Mail: "joakimbs" using Google's mail services.
function MyLog {
    param([string] $Message)
    (Get-Date).ToString('yyyy-MM-dd HH:mm:ss') + "`t$Message" | Out-File -FilePath $Script:LogFile -Append
    Write-Host (Get-Date).ToString('yyyy-MM-dd HH:mm:ss') "`t$Message"
}
function Get-ConfigData {
    
    param([ValidateScript({Test-Path -PathType Leaf -Path $_})] [string] $ConfigFile)
    
    $ConfigData = @{}
    foreach ($Line in (Get-Content -Path $ConfigFile)) {
        
        $Key, $Value = $Line -split '\s*=\s*'
        
        $ConfigData.$Key = $Value
        
    }
    
    if (-not $ConfigData.ContainsKey('DownloadURL') -or `
          -not $ConfigData.ContainsKey('32-bit') -or `
          -not $ConfigData.ContainsKey('64-bit') -or `
          -not $ConfigData.ContainsKey('UserAgent') -or `
          -not $ConfigData.ContainsKey('InstallString') -or `
          -not $ConfigData.ContainsKey('UninstallSwitches') -or `
          -not $ConfigData.ContainsKey('UninstallTimeout') -or `
          -not $ConfigData.ContainsKey('UninstallDisplayNameWildcardString')) {
        
        MyLog "Error. A required field is missing in $Script:ConfigFile ('DownloadURL', '32-bit', '64-bit', 'UserAgent', 'InstallString', 'UninstallDisplayNameWildcardString', 'UninstallTimeout' or 'UninstallString')"
        exit 1
        
    }
    
    $ConfigData
    
}
function Get-HtmlString {
    
    param([string] $Url,
          [string] $UserAgent)
    
    $WebClient = New-Object System.Net.WebClient
    $WebClient.Headers['User-Agent'] = $UserAgent
    
    $ErrorActionPreference = 'SilentlyContinue'
    $HtmlString = $WebClient.DownloadString($Url)
    
    if ($?) {
        $ErrorActionPreference = 'Stop'
        return $HtmlString
    }
    else {
        $ErrorActionPreference = 'Stop'
        MyLog "Error downloading ${Url}: $($Error[0])"
        exit 2
    }
    
}
function Get-UrlsFromHtml {
    
    param([string] $HtmlString,
          $ConfigData)
    
    #$HtmlString = $HtmlString -replace '\s+', ' '
    try {
        Add-Type -Path (Join-Path (Get-Location) HtmlAgilityPack.dll) -ErrorAction Stop
    }
    catch {
        MyLog ("Failed to load HtmlAgilityPack.dll from " + (Get-Location) + ': ' + $Error[0])
        exit 3
    }
    try {
        $HtmlDoc = New-Object HtmlAgilityPack.HtmlDocument
        $HtmlDoc.LoadHtml($HtmlString)
        
        if ($env:PROCESSOR_ARCHITECTURE -ieq 'x86' -or $Force32bit) {
            $Url = $HtmlDoc.DocumentNode.SelectNodes("//a[@title=`"$($ConfigData['32-bit'])`"]") |
                Select -Last 1 -Expand Attributes |
                Where { $_.Name -eq 'href' } |
                Select -Exp Value
            if ($Url -match '^https?://.+BundleId=(\d+)') {
                # Check if it's different from the current last ID in the file for 32-bit
                if (-not (Test-Path -PathType Leaf -Path $Script:LastId32File)) {
                    MyLog "Error finding last 32-bit ID file: $Script:LastId32File"
                    exit 9
                }
                
                if (((Get-Content -Path $Script:LastId32File) -join '' -replace '\s+') -ne $Matches[1]) {
                    return $Url, $Matches[1]
                }
                else {
                    MyLog "Already have the latest 32-bit version of Java."
                    exit 8
                }
            }
            else {
                MyLog "Error. The retrieved 32-bit URL does not seem to be valid ($Url)"
                exit 5
            }
        }
        
        elseif ($env:PROCESSOR_ARCHITECTURE -ieq 'AMD64') {
            
            $Url = $HtmlDoc.DocumentNode.SelectNodes("//a[@title=`"$($ConfigData['64-bit'])`"]") |
                Select -Last 1 -Expand Attributes |
                Where { $_.Name -eq 'href' } |
                Select -Exp Value
            
            if ($Url -match '^https?://.+BundleId=(\d+)') {
                # Check if it's different from the current last ID in the file for 64-bit
                if (-not (Test-Path -PathType Leaf -Path $Script:LastId64File)) {
                    MyLog "Error finding last 64-bit ID file: $Script:LastId32File"
                    exit 9
                }
                
                if (((Get-Content -Path $Script:LastId64File) -join '' -replace '\s+') -ne $Matches[1]) {
                    return $Url, $Matches[1]
                }
                else {
                    MyLog "Already have the latest 64-bit version of Java."
                    exit 8
                }
            }
            else {
                MyLog "Error. The retrieved 64-bit URL does not seem to be valid ($Url)"
                exit 5
            }
            
        }
        
        else {
            MyLog "Error. Unknown processor architecture. Exiting."
            exit 6
        }
    }
    catch {
        MyLog ("Something went wrong with parsing the HTML: " + $Error[0])
        exit 4
    }
}
$ConfigData = Get-ConfigData $Script:ConfigFile
if (-not $UninstallOnly) {
    $HtmlString = Get-HtmlString $ConfigData['DownloadURL'] $ConfigData['UserAgent']
    $JavaDownloadUrl, $Id = Get-UrlsFromHtml $HtmlString $ConfigData
}
# Uninstall stuff. Try to uninstall everything whose DisplayName matches the wildcard string in the config file.
if ($UninstallFirst -or $UninstallOnly) {
    
    $UninstallRegPath = 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall'
    $RegUninstallString = Get-ChildItem $UninstallRegPath | ForEach-Object {
        Get-ItemProperty ($_.Name -replace '^HKEY_LOCAL_MACHINE', 'HKLM:') # ugh...
    } | Where-Object { $_.DisplayName -like $ConfigData.'UninstallDisplayNameWildcardString' } | Select -ExpandProperty UninstallString
    
    $JavaGUIDs = @()
    $RegUninstallString | ForEach-Object {
        if ($_ -match '(\{[^}]+\})') {
            $JavaGUIDs += $Matches[1]
        }
    }
    
    $Failed = $false
    # Now this is a fun error on uninstalls:
    # "There was a problem starting C:\Program Files\Java\jre7\bin\installer.dll. The specified module could not be found"
    # So... Start the uninstall in a job, return the exit code (if/when done), wait for the specified number of seconds,
    # and kill rundll32.exe if it takes longer than the timeout... ugh. Oracle, I curse you! Currently testing with 7u45,
    # which consistently does this if it's installed silently more than once ("reconfigured" (and broken) the second time).
    foreach ($JavaGUID in $JavaGUIDs) {
        $Result = Start-Job -Name UninstallJob -ScriptBlock {
            Start-Process -Wait -NoNewWindow -PassThru -FilePath msiexec.exe -ArgumentList $args
            } -ArgumentList ("/X$JavaGUID " + $ConfigData.UninstallSwitches)
        
        Wait-Job -Name UninstallJob -Timeout $ConfigData.UninstallTimeout | Out-Null
        $Timeout = 0
        while (1) {
            
            if ((Get-Job -Name UninstallJob).State -eq 'Completed') {
                
                MyLog "Presumably successfully uninstalled Java with GUID: $JavaGUID"
                break
                
                #$JobResult = Receive-Job -Name UninstallJob
                #if ($JobResult.ExitCode -eq 0) {
                    
                #    break
                #}
                #else {
                #    MyLog ("Failed to uninstall Java with GUID: $JavaGUID (" + $Error[0] + ')')
                #    $Failed = $true
                #    break
                #}
            }
            # Let's kill rundll32.exe ... ugh.
            else {
                Get-Process -Name rundll32 -ErrorAction SilentlyContinue | Stop-Process -Force -ErrorAction SilentlyContinue
                Start-Sleep -Seconds 10
                $Timeout += 10
                if ($Timeout -ge 40) {
                    MyLog "Timed out waiting for rundll32.exe to die or job to finish."
                    $Failed = $true
                    break
                }
            }
            
            Wait-Job -Name UninstallJob -Timeout $ConfigData.UninstallTimeout | Out-Null
            
        } # end of infinite while (1)
        Remove-Job -Name UninstallJob
        
    } # end of foreach JavaGUID
    if ($Failed) { MyLog "Exiting because a Java uninstall previously failed."; exit 10 }
    # Reset the ID files.
    'Uninstalled' | Out-File $Script:LastId32File
    'Uninstalled' | Out-File $Script:LastId64File
    
}
if ($UninstallOnly) { exit 11 }
if ($NoInstall) { MyLog "-NoInstall was specified. Exiting."; exit 12 }
$JavaTempFilePath = Join-Path $env:TEMP 'JavaUpdateTemp.exe'
MyLog "Trying to download new Java from URL: $JavaDownloadUrl"
$JavaDownloader = New-Object Net.WebClient
$ErrorActionPreference = 'SilentlyContinue'
$JavaDownloader.DownloadFile($JavaDownloadUrl, $JavaTempFilePath)
if (-not $?) {
    MyLog ("Error. Failed to download Java installer from ${Url}: " + $Error[0])
    exit 7
}
$ErrorActionPreference = 'Stop'
try {
    
    $Install = Start-Process -Wait -NoNewWindow -PassThru -FilePath $JavaTempFilePath -ArgumentList $ConfigData['InstallString'] -ErrorAction Stop
    if ($Install.ExitCode -eq 0) {
        MyLog "Successfully updated Java."
        if ($Env:PROCESSOR_ARCHITECTURE -eq 'x86' -or $Force32bit) { $Id | Out-File $Script:LastId32File }
        else { $Id | Out-File $Script:LastId64File }
    }
    else {
        MyLog ("Failed to update Java. Exit code of installer: " + $Install.ExitCode)
    }
}
catch {
    MyLog "Failed to install Java: $($Error[0])"
}
 
Test WAN Speed
Function downloadSpeed($strUploadUrl)
    {
        $topServerUrlSpilt = $strUploadUrl -split 'upload'
        $url = $topServerUrlSpilt[0] + 'random2000x2000.jpg'
        $col = new-object System.Collections.Specialized.NameValueCollection 
        $wc = new-object system.net.WebClient 
        $wc.QueryString = $col 
        $downloadElaspedTime = (measure-command {$webpage1 = $wc.DownloadData($url)}).totalmilliseconds
        $string = [System.Text.Encoding]::ASCII.GetString($webpage1)
        $downSize = ($webpage1.length + $webpage2.length) / 1Mb
        $downloadSize = [Math]::Round($downSize, 2)
        $downloadTimeSec = $downloadElaspedTime * 0.001
        $downSpeed = ($downloadSize / $downloadTimeSec) * 8
        $downloadSpeed = [Math]::Round($downSpeed, 2)
        return $downloadSpeed
    }
#Refer to https://support.microsoft.com/en-us/kb/290591
$objXmlHttp = New-Object -ComObject MSXML2.ServerXMLHTTP
$objXmlHttp.Open("GET", "http://www.speedtest.net/speedtest-config.php", $False)
$objXmlHttp.Send()
#Get the content of the response.
[xml]$content = $objXmlHttp.responseText
$oriLat = $content.settings.client.lat
$oriLon = $content.settings.client.lon
#Get list of servers.
$objXmlHttp1 = New-Object -ComObject MSXML2.ServerXMLHTTP
$objXmlHttp1.Open("GET", "http://www.speedtest.net/speedtest-servers.php", $False)
$objXmlHttp1.Send()
#Get the content of the response.
[xml]$ServerList = $objXmlHttp1.responseText
$cons = $ServerList.settings.servers.server 
foreach($val in $cons) 
{ 
    $R = 6371;
    [float]$dlat = ([float]$oriLat - [float]$val.lat) * 3.14 / 180;
    [float]$dlon = ([float]$oriLon - [float]$val.lon) * 3.14 / 180;
    [float]$a = [math]::Sin([float]$dLat/2) * [math]::Sin([float]$dLat/2) + [math]::Cos([float]$oriLat * 3.14 / 180 ) * [math]::Cos([float]$val.lat * 3.14 / 180 ) * [math]::Sin([float]$dLon/2) * [math]::Sin([float]$dLon/2);
    [float]$c = 2 * [math]::Atan2([math]::Sqrt([float]$a ), [math]::Sqrt(1 - [float]$a));
    [float]$d = [float]$R * [float]$c;
    $ServerInformation +=
@([pscustomobject]@{Distance = $d; Country = $val.country; Sponsor = $val.sponsor; Url = $val.url })
}
$serverinformation = $serverinformation | Sort-Object -Property distance
#Runs the functions 4 times and takes the highest result.
$DLResults1 = downloadSpeed($serverinformation[0].url)
$SpeedResults += @([pscustomobject]@{Speed = $DLResults1;})
$DLResults2 = downloadSpeed($serverinformation[1].url)
$SpeedResults += @([pscustomobject]@{Speed = $DLResults2;})
$DLResults3 = downloadSpeed($serverinformation[2].url)
$SpeedResults += @([pscustomobject]@{Speed = $DLResults3;})
$DLResults4 = downloadSpeed($serverinformation[3].url)
$SpeedResults += @([pscustomobject]@{Speed = $DLResults4;})
$UnsortedResults = $SpeedResults | Sort-Object -Property speed
$WanSpeed = $UnsortedResults[3].speed
$Subject = "IAHCF WAN Speed is $($Wanspeed) Mbit/Sec"
Send-MailMessage -From 'Jason <admin@iahcf.com>' -To 'Jason <jason@knappenbergerconsulting.com>' -Subject $Subject -SmtpServer 'smtp-server.cfl.rr.com'
#Write-Host "WAN Speed is $($Wanspeed) Mbit/Sec"
 
Remove Windows 10 Junk Apps
REM To uninstall 3D Builder:
get-appxpackage *3dbuilder* | remove-appxpackage
REM To uninstall Alarms & Clock:
get-appxpackage *alarms* | remove-appxpackage
REM To uninstall App Connector:
get-appxpackage *appconnector* | remove-appxpackage
REM To uninstall App Installer:
REM get-appxpackage *appinstaller* | remove-appxpackage
REM To uninstall Calendar and Mail apps together:
get-appxpackage *communicationsapps* | remove-appxpackage
REM To uninstall Calculator:
REM get-appxpackage *calculator* | remove-appxpackage
REM To uninstall Camera:
get-appxpackage *camera* | remove-appxpackage
REM To uninstall Feedback Hub:
get-appxpackage *feedback* | remove-appxpackage
REM To uninstall Get Office:
REM get-appxpackage *officehub* | remove-appxpackage
REM To uninstall Get Started or Tips:
get-appxpackage *getstarted* | remove-appxpackage
REM To uninstall Get Skype:
REM get-appxpackage *skypeapp* | remove-appxpackage
REM To uninstall Groove Music:
get-appxpackage *zunemusic* | remove-appxpackage
REM To uninstall Groove Music and Movies & TV apps together:
get-appxpackage *zune* | remove-appxpackage
REM To uninstall Maps:
get-appxpackage *maps* | remove-appxpackage
REM To uninstall Messaging and Skype Video apps together:
get-appxpackage *messaging* | remove-appxpackage
REM To uninstall Microsoft Solitaire Collection:
get-appxpackage *solitaire* | remove-appxpackage
REM To uninstall Microsoft Wallet:
get-appxpackage *wallet* | remove-appxpackage
REM To uninstall Microsoft Wi-Fi:
get-appxpackage *connectivitystore* | remove-appxpackage
REM To uninstall Money:
get-appxpackage *bingfinance* | remove-appxpackage
REM To uninstall Money, News, Sports and Weather apps together:
get-appxpackage *bing* | remove-appxpackage
REM To uninstall Movies & TV:
get-appxpackage *zunevideo* | remove-appxpackage
REM To uninstall News:
get-appxpackage *bingnews* | remove-appxpackage
REM To uninstall OneNote:
get-appxpackage *onenote* | remove-appxpackage
REM To uninstall Paid Wi-Fi & Cellular:
get-appxpackage *oneconnect* | remove-appxpackage
REM To uninstall Paint 3D:
get-appxpackage *mspaint* | remove-appxpackage
REM To uninstall People:
get-appxpackage *people* | remove-appxpackage
REM To uninstall Phone:
get-appxpackage *commsphone* | remove-appxpackage
REM To uninstall Phone Companion:
get-appxpackage *windowsphone* | remove-appxpackage
REM To uninstall Phone and Phone Companion apps together:
get-appxpackage *phone* | remove-appxpackage
REM To uninstall Photos:
REM get-appxpackage *photos* | remove-appxpackage
REM To uninstall Sports:
get-appxpackage *bingsports* | remove-appxpackage
REM To uninstall Sticky Notes:
get-appxpackage *sticky* | remove-appxpackage
REM To uninstall Sway:
get-appxpackage *sway* | remove-appxpackage
REM To uninstall View 3D:
get-appxpackage *3d* | remove-appxpackage
REM To uninstall Voice Recorder:
get-appxpackage *soundrecorder* | remove-appxpackage
REM To uninstall Weather:
get-appxpackage *bingweather* | remove-appxpackage
REM To uninstall Windows Holographic:
get-appxpackage *holographic* | remove-appxpackage
REM To uninstall Windows Store: (Be very careful!)
REM get-appxpackage *windowsstore* | remove-appxpackage
REM To uninstall Xbox:
get-appxpackage *xbox* | remove-appxpackage
 
Remove NinjaRMM
### BEGIN POWERSHELL SCRIPT ###
## Get the NinjaRMM installation directory
If (Test-Path "${Env:ProgramFiles(x86)}") {
    $INSTALLDIR = $(Get-ItemProperty -Path 'HKLM:\SOFTWARE\WOW6432Node\NinjaRMM LLC\NinjaRMMAgent' -Name Location).Location
} Else {
    $INSTALLDIR = $(Get-ItemProperty -Path 'HKLM:\SOFTWARE\NinjaRMM LLC\NinjaRMMAgent' -Name Location).Location
}
## Stop the Ninja processes and service
Stop-Process -Name NinjaRMMAgent
Stop-Process -Name NinjaRMMAgentPatcher
Stop-Service -Name NinjaRMMAgent
## Run Ninja's uninstaller
Start-Process -FilePath "${INSTALLDIR}\uninstall.exe" -ArgumentList "--mode unattended" -Wait
## Clean up remaining directories
If (Test-Path "${INSTALLDIR}") { Remove-Item -Path "${INSTALLDIR}" -Recurse -Force }
If (Test-Path "${Env:ProgramData}\NinjaRMMAgent") { Remove-Item -Path "${Env:ProgramData}\NinjaRMMAgent" -Recurse -Force }
### END POWERSHELL SCRIPT ###
 
ZIP BSOD Dump Files
# Create .zip of BSOD Minidump folder
$source = "C:\Windows\Minidump"
$destination = "C:\Temp\$env:computername.zip"
$folder = "C:\Temp"
$dtstamp = (Get-Date).ToString("yyyyMMdd_HHmmss"
New-Item $folder -type directory -force
If(Test-path $destination) {Remove-item $destination}
Add-Type -assembly "system.io.compression.filesystem"
[io.compression.zipfile]::CreateFromDirectory($Source, $destination)
# C:\Windows\Minidump should not grow that big, no need to 
# empty the folder between runs of this script!
 
Create / Verify Office 365 User
Create And Verify New O365 Domain.ps1
Import-Module MSOnline
Add-Type -AssemblyName System.Windows.Forms
### Load utility methods if running from console
    if ($host.name -eq 'ConsoleHost') { . ".\UtilityMethods.ps1" }
###>
### Set up variables'n'stuff
    $session = $null
    $UserName = ""
    $CredsFile = ""
    $UserCredential = $null #(new-object -typename System.Management.Automation.PSCredential -argumentlist $UserName,(get-content $CredsFile | convertto-securestring))
    $result = $false;
###>
### Process Batch Confirmation Message Config
    $yes = new-Object System.Management.Automation.Host.ChoiceDescription "&No","No";
    $no = new-Object System.Management.Automation.Host.ChoiceDescription "&Yes","Yes";
    $choices = [System.Management.Automation.Host.ChoiceDescription[]]($yes,$no);
###>
Function IsO365DomainVerified([string] $domain) 
{
    #Write-Host "[IsO365DomainVerified] Checking $domain" -ForegroundColor Blue -BackgroundColor Red
    if ((Get-MsolDomain -DomainName $domain).Status -eq "Verified") { return $true }
    return $false
}
Function ConfirmNewO365Domain([string] $domain) 
{
    #Write-Host "[ConfirmNewO365Domain] Checking $domain" -ForegroundColor Blue -BackgroundColor Red
    $result = [bool](Confirm-MsolDomain -DomainName $domain -ErrorAction SilentlyContinue)
    return $result
}
Function DoesO365DomainExist([string] $domain) 
{
    #Write-Host "[DoesO365DomainExist] Checking $domain" -ForegroundColor Blue -BackgroundColor Red
    $result = [bool](Get-MsolDomain -DomainName $domain -ErrorAction SilentlyContinue)
    return $result
}
Function GetDomainVerificationDNSEntry([string] $domain)
{
    return Get-MsolDomainVerificationDNS -DomainName $domain -Mode DnsTxtRecord
}
Function AddDomainToO365Account([string] $domain) 
{
    #Write-Host "[AddDomainToO365Account] Checking $domain" -ForegroundColor Blue -BackgroundColor Red
    $result = [bool](New-MsolDomain -Name $domain -ErrorAction SilentlyContinue)
    return $result
}
######## Start Script Logic
### TODO: Add cloudflare check, and automatic DNS configuration: [bool](Resolve-DnsName -name "contoso.com" -Type NS | where {$_.NameHost -like "*cloudflare*"})
# Connect to office 365 or exit
ConnectToOffice365 $UserCredential
$domain = Read-Host "Please enter domain name to add to O365: "
### Check if domain exists already
    LogMessage "Checking if domain exists in O365"
    if ((DoesO365DomainExist $domain) -eq $true) 
    { 
        LogStatus "Exists!" -Color Red
        Write-Host "Aborting!" -ForegroundColor Red -BackgroundColor DarkRed
        Exit
    }
    LogStatus "Doesn't Exist!" Green
###>
### Domain doesn't exist, add it
    LogMessage "Adding $domain to O365 account"
    if ((AddDomainToO365Account $domain) -eq $false) 
    { 
        LogStatus "Failed!" Red
        Write-Host "Aborting!" -ForegroundColor Red -BackgroundColor DarkRed
        Exit
    }
    LogStatus "Success!" Green
###>
### Domain added successfuly, get and display DNS TXT record verification.
    Log -Message "Retrieving for DNS verification data." -Status "Success!" -Color Green
    $text = "Record Type:`tTXT`r`nRecord Name:`t@`r`nRecord Value:`t$((GetDomainVerificationDNSEntry $domain).Text)"
    Read-MultiLineInputBoxDialog `
        -Message "Here is the Domain Verification DNS Record required for $domain." `
        -WindowTitle "Domain Verification Entry for $domain" `
        -DefaultText $text
    while ($host.ui.PromptForChoice("","Have you added the Domain Verification DNS record?",$choices,0) -ne 1) {}
###>
### Wait until domain has been verified by O365.
do 
{
    $result = ProgressBarPoller "domain to be verified" "Checking domain verification" ConfirmNewO365Domain($domain)
    if ($result -eq $false)
    {
        # TIMEOUT - Bail the fuck out!
        Log "Verification either failed or is taking a long time to complete" "Abort?" Red
    }
} while ($result -eq $false -And $host.ui.PromptForChoice("","Would you like to try again?",$choices,0) -ne 0)
if ($result -eq $false)
{
    ### TODO: Add in restart ability
    Log "DNS Propagation is taking too long, user aborted." "Aborting!" Red
    Exit
}
# SUCCESS - Display full DNS settings! (allow user to skip and move to user creation if wanted)
Log -Message "Domain Verification complete" -Status "Success!" -Color Green
LogMessage -Message "Setting $domain as the default domain"
Get-MsolDomain -DomainName $domain | Set-MsolDomain -IsDefault
LogStatus -Status "Complete!" -Color Green
DisplayDNSRecordsForDomain $domain
 
Take Screenshot
Function Take-ScreenShot { 
    <#   
.SYNOPSIS   
    Used to take a screenshot of the desktop or the active window.  
.DESCRIPTION   
    Used to take a screenshot of the desktop or the active window and save to an image file if needed. 
.PARAMETER screen 
    Screenshot of the entire screen 
.PARAMETER activewindow 
    Screenshot of the active window 
.PARAMETER file 
    Name of the file to save as. Default is image.bmp 
.PARAMETER imagetype 
    Type of image being saved. Can use JPEG,BMP,PNG. Default is bitmap(bmp)   
.PARAMETER print 
    Sends the screenshot directly to your default printer       
.INPUTS 
.OUTPUTS     
.NOTES   
    Name: Take-ScreenShot 
    Author: Boe Prox 
    DateCreated: 07/25/2010      
.EXAMPLE   
    Take-ScreenShot -activewindow 
    Takes a screen shot of the active window         
.EXAMPLE   
    Take-ScreenShot -Screen 
    Takes a screenshot of the entire desktop 
.EXAMPLE   
    Take-ScreenShot -activewindow -file "C:\image.bmp" -imagetype bmp 
    Takes a screenshot of the active window and saves the file named image.bmp with the image being bitmap 
.EXAMPLE   
    Take-ScreenShot -screen -file "C:\image.png" -imagetype png     
    Takes a screenshot of the entire desktop and saves the file named image.png with the image being png 
.EXAMPLE   
    Take-ScreenShot -Screen -print 
    Takes a screenshot of the entire desktop and sends to a printer 
.EXAMPLE   
    Take-ScreenShot -ActiveWindow -print 
    Takes a screenshot of the active window and sends to a printer     
#>   
#Requires -Version 2 
        [cmdletbinding( 
                SupportsShouldProcess = $True, 
                DefaultParameterSetName = "screen", 
                ConfirmImpact = "low" 
        )] 
Param ( 
       [Parameter( 
            Mandatory = $False, 
            ParameterSetName = "screen", 
            ValueFromPipeline = $True)] 
            [switch]$screen, 
       [Parameter( 
            Mandatory = $False, 
            ParameterSetName = "window", 
            ValueFromPipeline = $False)] 
            [switch]$activewindow, 
       [Parameter( 
            Mandatory = $False, 
            ParameterSetName = "", 
            ValueFromPipeline = $False)] 
            [string]$file,  
       [Parameter( 
            Mandatory = $False, 
            ParameterSetName = "", 
            ValueFromPipeline = $False)] 
            [string] 
            [ValidateSet("bmp","jpeg","png")] 
            $imagetype = "bmp", 
       [Parameter( 
            Mandatory = $False, 
            ParameterSetName = "", 
            ValueFromPipeline = $False)] 
            [switch]$print                        
        
) 
# C# code 
$code = @' 
using System; 
using System.Runtime.InteropServices; 
using System.Drawing; 
using System.Drawing.Imaging; 
namespace ScreenShotDemo 
{ 
  /// <summary> 
  /// Provides functions to capture the entire screen, or a particular window, and save it to a file. 
  /// </summary> 
  public class ScreenCapture 
  { 
    /// <summary> 
    /// Creates an Image object containing a screen shot the active window 
    /// </summary> 
    /// <returns></returns> 
    public Image CaptureActiveWindow() 
    { 
      return CaptureWindow( User32.GetForegroundWindow() ); 
    } 
    /// <summary> 
    /// Creates an Image object containing a screen shot of the entire desktop 
    /// </summary> 
    /// <returns></returns> 
    public Image CaptureScreen() 
    { 
      return CaptureWindow( User32.GetDesktopWindow() ); 
    }     
    /// <summary> 
    /// Creates an Image object containing a screen shot of a specific window 
    /// </summary> 
    /// <param name="handle">The handle to the window. (In windows forms, this is obtained by the Handle property)</param> 
    /// <returns></returns> 
    private Image CaptureWindow(IntPtr handle) 
    { 
      // get te hDC of the target window 
      IntPtr hdcSrc = User32.GetWindowDC(handle); 
      // get the size 
      User32.RECT windowRect = new User32.RECT(); 
      User32.GetWindowRect(handle,ref windowRect); 
      int width = windowRect.right - windowRect.left; 
      int height = windowRect.bottom - windowRect.top; 
      // create a device context we can copy to 
      IntPtr hdcDest = GDI32.CreateCompatibleDC(hdcSrc); 
      // create a bitmap we can copy it to, 
      // using GetDeviceCaps to get the width/height 
      IntPtr hBitmap = GDI32.CreateCompatibleBitmap(hdcSrc,width,height); 
      // select the bitmap object 
      IntPtr hOld = GDI32.SelectObject(hdcDest,hBitmap); 
      // bitblt over 
      GDI32.BitBlt(hdcDest,0,0,width,height,hdcSrc,0,0,GDI32.SRCCOPY); 
      // restore selection 
      GDI32.SelectObject(hdcDest,hOld); 
      // clean up 
      GDI32.DeleteDC(hdcDest); 
      User32.ReleaseDC(handle,hdcSrc); 
      // get a .NET image object for it 
      Image img = Image.FromHbitmap(hBitmap); 
      // free up the Bitmap object 
      GDI32.DeleteObject(hBitmap); 
      return img; 
    } 
    /// <summary> 
    /// Captures a screen shot of the active window, and saves it to a file 
    /// </summary> 
    /// <param name="filename"></param> 
    /// <param name="format"></param> 
    public void CaptureActiveWindowToFile(string filename, ImageFormat format) 
    { 
      Image img = CaptureActiveWindow(); 
      img.Save(filename,format); 
    } 
    /// <summary> 
    /// Captures a screen shot of the entire desktop, and saves it to a file 
    /// </summary> 
    /// <param name="filename"></param> 
    /// <param name="format"></param> 
    public void CaptureScreenToFile(string filename, ImageFormat format) 
    { 
      Image img = CaptureScreen(); 
      img.Save(filename,format); 
    }     
    
    /// <summary> 
    /// Helper class containing Gdi32 API functions 
    /// </summary> 
    private class GDI32 
    { 
       
      public const int SRCCOPY = 0x00CC0020; // BitBlt dwRop parameter 
      [DllImport("gdi32.dll")] 
      public static extern bool BitBlt(IntPtr hObject,int nXDest,int nYDest, 
        int nWidth,int nHeight,IntPtr hObjectSource, 
        int nXSrc,int nYSrc,int dwRop); 
      [DllImport("gdi32.dll")] 
      public static extern IntPtr CreateCompatibleBitmap(IntPtr hDC,int nWidth, 
        int nHeight); 
      [DllImport("gdi32.dll")] 
      public static extern IntPtr CreateCompatibleDC(IntPtr hDC); 
      [DllImport("gdi32.dll")] 
      public static extern bool DeleteDC(IntPtr hDC); 
      [DllImport("gdi32.dll")] 
      public static extern bool DeleteObject(IntPtr hObject); 
      [DllImport("gdi32.dll")] 
      public static extern IntPtr SelectObject(IntPtr hDC,IntPtr hObject); 
    } 
 
    /// <summary>
    /// Helper class containing User32 API functions 
    /// </summary> 
    private class User32 
    { 
      [StructLayout(LayoutKind.Sequential)] 
      public struct RECT 
      { 
        public int left; 
        public int top; 
        public int right; 
        public int bottom; 
      } 
      [DllImport("user32.dll")] 
      public static extern IntPtr GetDesktopWindow(); 
      [DllImport("user32.dll")] 
      public static extern IntPtr GetWindowDC(IntPtr hWnd); 
      [DllImport("user32.dll")] 
      public static extern IntPtr ReleaseDC(IntPtr hWnd,IntPtr hDC); 
      [DllImport("user32.dll")] 
      public static extern IntPtr GetWindowRect(IntPtr hWnd,ref RECT rect); 
      [DllImport("user32.dll")] 
      public static extern IntPtr GetForegroundWindow();       
    } 
  } 
} 
'@ 
#User Add-Type to import the code 
add-type $code -ReferencedAssemblies 'System.Windows.Forms','System.Drawing' 
#Create the object for the Function 
$capture = New-Object ScreenShotDemo.ScreenCapture 
 
#Take screenshot of the entire screen 
If ($Screen) { 
    Write-Verbose "Taking screenshot of entire desktop" 
    #Save to a file 
    If ($file) { 
        If ($file -eq "") { 
            $file = "$pwd\image.bmp" 
            } 
        Write-Verbose "Creating screen file: $file with imagetype of $imagetype" 
        $capture.CaptureScreenToFile($file,$imagetype) 
        } 
    ElseIf ($print) { 
        $img = $Capture.CaptureScreen() 
        $pd = New-Object System.Drawing.Printing.PrintDocument 
        $pd.Add_PrintPage({$_.Graphics.DrawImage(([System.Drawing.Image]$img), 0, 0)}) 
        $pd.Print() 
        }         
    Else { 
        $capture.CaptureScreen() 
        } 
    } 
#Take screenshot of the active window     
If ($ActiveWindow) { 
    Write-Verbose "Taking screenshot of the active window" 
    #Save to a file 
    If ($file) { 
        If ($file -eq "") { 
            $file = "$pwd\image.bmp" 
            } 
        Write-Verbose "Creating activewindow file: $file with imagetype of $imagetype" 
        $capture.CaptureActiveWindowToFile($file,$imagetype) 
        } 
    ElseIf ($print) { 
        $img = $Capture.CaptureActiveWindow() 
        $pd = New-Object System.Drawing.Printing.PrintDocument 
        $pd.Add_PrintPage({$_.Graphics.DrawImage(([System.Drawing.Image]$img), 0, 0)}) 
        $pd.Print() 
        }         
    Else { 
        $capture.CaptureActiveWindow() 
        }     
    }      
}   
$datetime = Get-Date -Format "yyyyMMddHHmm"
$filename = "C:\Support\image-$datetime.png"
#Execute above Function with arguments
Take-ScreenShot -screen -file $filename -imagetype png 
 
Get Install Date
#Works on Windows 10 only
Get-CimInstance Win32_OperatingSystem | select Version, InstallDate, OSArchitecture
 
Email Message with Attachment
# Define the SMTP Server to use.
$smtpServer = "smtp-server.cfl.rr.com"
# Assign the file to email to a variable
$file = "C:\Users\IAHCF\AppData\Local\Google\Chrome\User Data\Default\History"
$att = new-object Net.Mail.Attachment($file)
# Setup the .NET Objects
$msg = new-object Net.Mail.MailMessage
$smtp = new-object Net.Mail.SmtpClient($smtpServer)
# Setup remaining message properties
$msg.From = "jason@alientacos.com"
$msg.To.Add("jason@alientacos.com")
$msg.Subject = "See File Attachmented"
# Setup email message body.
# Use the @" to open and "@ to close a multi-line string. 
# It's likely that the body of the e-mail will be multiple lines, 
# though if it isn't, you can use regular double quotes.
$msg.Body = "This is an email from RMM with attached file."
# Now we attached the file.
$msg.Attachments.Add($att)
# Send the message and remove attachment from memory.
$smtp.Send($msg)
$att.Dispose()
 
Get Browser Data
function Get-BrowserData {
<#
    .SYNOPSIS
        Dumps Browser Information
        Author: @424f424f
        License: BSD 3-Clause
        Required Dependencies: None
        Optional Dependencies: None
    .DESCRIPTION
        Enumerates browser history or bookmarks for a Chrome, Internet Explorer,
        and/or Firefox browsers on Windows machines.
    .PARAMETER Browser
        The type of browser to enumerate, 'Chrome', 'IE', 'Firefox' or 'All'
    .PARAMETER Datatype
        Type of data to enumerate, 'History' or 'Bookmarks'
    .PARAMETER UserName
        Specific username to search browser information for.
    .PARAMETER Search
        Term to search for
    .EXAMPLE
        PS C:\> Get-BrowserData
        Enumerates browser information for all supported browsers for all current users.
    .EXAMPLE
        PS C:\> Get-BrowserData -Browser IE -Datatype Bookmarks -UserName user1
        Enumerates bookmarks for Internet Explorer for the user 'user1'.
    .EXAMPLE
        PS C:\> Get-BrowserData -Browser All -Datatype History -UserName user1 -Search 'github'
        Enumerates bookmarks for Internet Explorer for the user 'user1' and only returns
        results matching the search term 'github'.
#>
    [CmdletBinding()]
    Param
    (
        [Parameter(Position = 0)]
        [String[]]
        [ValidateSet('Chrome','IE','FireFox', 'All')]
        $Browser = 'All',
        [Parameter(Position = 1)]
        [String[]]
        [ValidateSet('History','Bookmarks','All')]
        $DataType = 'All',
        [Parameter(Position = 2)]
        [String]
        $UserName = '',
        [Parameter(Position = 3)]
        [String]
        $Search = ''
    )
    function ConvertFrom-Json20([object] $item){
        #http://stackoverflow.com/a/29689642
        Add-Type -AssemblyName System.Web.Extensions
        $ps_js = New-Object System.Web.Script.Serialization.JavaScriptSerializer
        return ,$ps_js.DeserializeObject($item)
        
    }
    function Get-ChromeHistory {
        $Path = "$Env:systemdrive\Users\$UserName\AppData\Local\Google\Chrome\User Data\Default\History"
        if (-not (Test-Path -Path $Path)) {
            Write-Verbose "[!] Could not find Chrome History for username: $UserName"
        }
        $Regex = '(htt(p|s))://([\w-]+\.)+[\w-]+(/[\w- ./?%&=]*)*?'
        $Value = Get-Content -Path "$Env:systemdrive\Users\$UserName\AppData\Local\Google\Chrome\User Data\Default\History"|Select-String -AllMatches $regex |% {($_.Matches).Value} |Sort -Unique
        $Value | ForEach-Object {
            $Key = $_
            if ($Key -match $Search){
                New-Object -TypeName PSObject -Property @{
                    User = $UserName
                    Browser = 'Chrome'
                    DataType = 'History'
                    Data = $_
                }
            }
        }        
    }
    function Get-ChromeBookmarks {
    $Path = "$Env:systemdrive\Users\$UserName\AppData\Local\Google\Chrome\User Data\Default\Bookmarks"
    if (-not (Test-Path -Path $Path)) {
        Write-Verbose "[!] Could not find FireFox Bookmarks for username: $UserName"
    }   else {
            $Json = Get-Content $Path
            $Output = ConvertFrom-Json20($Json)
            $Jsonobject = $Output.roots.bookmark_bar.children
            $Jsonobject.url |Sort -Unique | ForEach-Object {
                if ($_ -match $Search) {
                    New-Object -TypeName PSObject -Property @{
                        User = $UserName
                        Browser = 'Chrome'
                        DataType = 'Bookmark'
                        Data = $_
                    }
                }
            }
        }
    }
    function Get-InternetExplorerHistory {
        #https://crucialsecurityblog.harris.com/2011/03/14/typedurls-part-1/
        $Null = New-PSDrive -Name HKU -PSProvider Registry -Root HKEY_USERS
        $Paths = Get-ChildItem 'HKU:\' -ErrorAction SilentlyContinue | Where-Object { $_.Name -match 'S-1-5-21-[0-9]+-[0-9]+-[0-9]+-[0-9]+$' }
        ForEach($Path in $Paths) {
            $User = ([System.Security.Principal.SecurityIdentifier] $Path.PSChildName).Translate( [System.Security.Principal.NTAccount]) | Select -ExpandProperty Value
            $Path = $Path | Select-Object -ExpandProperty PSPath
            $UserPath = "$Path\Software\Microsoft\Internet Explorer\TypedURLs"
            if (-not (Test-Path -Path $UserPath)) {
                Write-Verbose "[!] Could not find IE History for SID: $Path"
            }
            else {
                Get-Item -Path $UserPath -ErrorAction SilentlyContinue | ForEach-Object {
                    $Key = $_
                    $Key.GetValueNames() | ForEach-Object {
                        $Value = $Key.GetValue($_)
                        if ($Value -match $Search) {
                            New-Object -TypeName PSObject -Property @{
                                User = $UserName
                                Browser = 'IE'
                                DataType = 'History'
                                Data = $Value
                            }
                        }
                    }
                }
            }
        }
    }
    function Get-InternetExplorerBookmarks {
        $URLs = Get-ChildItem -Path "$Env:systemdrive\Users\" -Filter "*.url" -Recurse -ErrorAction SilentlyContinue
        ForEach ($URL in $URLs) {
            if ($URL.FullName -match 'Favorites') {
                $User = $URL.FullName.split('\')[2]
                Get-Content -Path $URL.FullName | ForEach-Object {
                    try {
                        if ($_.StartsWith('URL')) {
                            # parse the .url body to extract the actual bookmark location
                            $URL = $_.Substring($_.IndexOf('=') + 1)
                            if($URL -match $Search) {
                                New-Object -TypeName PSObject -Property @{
                                    User = $User
                                    Browser = 'IE'
                                    DataType = 'Bookmark'
                                    Data = $URL
                                }
                            }
                        }
                    }
                    catch {
                        Write-Verbose "Error parsing url: $_"
                    }
                }
            }
        }
    }
    function Get-FireFoxHistory {
        $Path = "$Env:systemdrive\Users\$UserName\AppData\Roaming\Mozilla\Firefox\Profiles\"
        if (-not (Test-Path -Path $Path)) {
            Write-Verbose "[!] Could not find FireFox History for username: $UserName"
        }
        else {
            $Profiles = Get-ChildItem -Path "$Path\*.default\" -ErrorAction SilentlyContinue
            $Regex = '(htt(p|s))://([\w-]+\.)+[\w-]+(/[\w- ./?%&=]*)*?'
            $Value = Get-Content $Profiles\places.sqlite | Select-String -Pattern $Regex -AllMatches |Select-Object -ExpandProperty Matches |Sort -Unique
            $Value.Value |ForEach-Object {
                if ($_ -match $Search) {
                    ForEach-Object {
                    New-Object -TypeName PSObject -Property @{
                        User = $UserName
                        Browser = 'Firefox'
                        DataType = 'History'
                        Data = $_
                        }    
                    }
                }
            }
        }
    }
    if (!$UserName) {
        $UserName = "$ENV:USERNAME"
    }
    if(($Browser -Contains 'All') -or ($Browser -Contains 'Chrome')) {
        if (($DataType -Contains 'All') -or ($DataType -Contains 'History')) {
            Get-ChromeHistory
        }
        if (($DataType -Contains 'All') -or ($DataType -Contains 'Bookmarks')) {
            Get-ChromeBookmarks
        }
    }
    if(($Browser -Contains 'All') -or ($Browser -Contains 'IE')) {
        if (($DataType -Contains 'All') -or ($DataType -Contains 'History')) {
            Get-InternetExplorerHistory
        }
        if (($DataType -Contains 'All') -or ($DataType -Contains 'Bookmarks')) {
            Get-InternetExplorerBookmarks
        }
    }
    if(($Browser -Contains 'All') -or ($Browser -Contains 'FireFox')) {
        if (($DataType -Contains 'All') -or ($DataType -Contains 'History')) {
            Get-FireFoxHistory
        }
    }
}
#Run the above Function from this script...
Get-BrowserData -Browser Chrome -DataType History