tom42tools.psm1

function DeployMe() {
    <#
    .SYNOPSIS
    Downloads .ps1 and runs it as admin
    .DESCRIPTION
    Used for system reinstalls, it downloads .ps1 and runs it as admin, it will also record restore folder
    Downloads .ps1 and runs it as admin
    .PARAMETER URL
    URL to a .ps1 files
    .PARAMETER Restorefolder
    Where the old install backup files were movied to
    .EXAMPLE
    PS C:\> DeployMe 'https://www.website.com/file.ps1'
    Downloads .ps1 and runs it as admin
    .EXAMPLE
    PS C:\> DeployMe -URL 'https://www.website.com/file.ps1'
    Downloads .ps1 and runs it as admin
    .EXAMPLE
    PS C:\> DeployMe 'https://www.website.com/file.ps1' 'e:\restore'
    Downloads .ps1 and runs it as admin, saves 'e:\restore' to file named "~\restore.dir"
    .EXAMPLE
    PS C:\> DeployMe -URL 'https://www.website.com/file.ps1' -Restorefolder 'e:\restore'
    Downloads .ps1 and runs it as admin, saves 'e:\restore' to file named "~\restore.dir"
[int] $Gap = 200
    iex (irm https://t0m.pw/StartMeUp)
    #>

    [CmdletBinding()]
    param(
        [Parameter()]
        [string]
        $URL = "https://raw.githubusercontent.com/go2tom42/Quagaars/master/TESTING/matrix.ps1",

        [Parameter()]
        [string]
        $Restorefolder = 'NA'
    )
    if (isURIWeb $URL) {
        if (-not $Restorefolder -eq "NA") {
            Write-Output $restorefolder | out-file -FilePath "~\restore.dir"
        }
        iex (irm $url)

    } elseif (isURIFile $URL) {
        if (-not $Restorefolder -eq "NA") {
            Write-Output $restorefolder | out-file -FilePath "~\restore.dir"
        }
        iex (irm $url)

    } else {
        Write-Host 'NOT VALID URL'
        Pause
    }
    
}

function isURIWeb($address) {
    $uri = $address -as [System.URI]
    $null -ne $uri.AbsoluteURI -and $uri.Scheme -match '[http|https]'
}
function isURIFile($address) {
    $uri = $address -as [System.URI]
    $null -ne $uri.AbsoluteURI -and $uri.Scheme -match '[File|file]'
}

function Get-BAFile() {
    <#
    .SYNOPSIS
    Downloads files requiring Basic Authorization
    .DESCRIPTION
    Downloads files requiring Basic Authorization
    .PARAMETER URL
    URL to file
    .PARAMETER Path
    Path to save file
    .PARAMETER User
    Username
    .PARAMETER Pass
    Password
    .EXAMPLE
    PS C:\> Get-BAFile 'https://remotely.tom42.pw/Content/Remotely_Installer.exe' './Remotely_Installer.exe' 'tom42' '1tardis1'
    Downloads .ps1 and runs it as admin
    .EXAMPLE
    PS C:\> Get-BAFile -URL 'https://remotely.tom42.pw/Content/Remotely_Installer.exe' -PATH './Remotely_Installer.exe' -USER 'tom42' -PASS '1tardis1'
    Downloads .ps1 and runs it as admin
    #>

    [CmdletBinding()]
    param(
        [parameter(Mandatory = $True)]
        [string]
        $URL,

        [parameter(Mandatory = $True)]
        [string]
        $PATH,

        [parameter(Mandatory = $True)]
        [string]
        $USER,

        [parameter(Mandatory = $True)]
        [string]
        $PASS
    )

    if ($PATH -eq 'NA') { Write-Host 'NOT VALID PATH'; exit }
    if ($PASS -eq 'NA') { Write-Host 'NOT VALID PASS'; exit }
    if ($USER -eq 'NA') { Write-Host 'NOT VALID USER'; exit }

    if (isURIWeb $URL) {
        $WebClient = New-Object System.Net.WebClient;
        $WebClient.Credentials = New-Object System.Net.Networkcredential($user, $pass)
        $WebClient.DownloadFile($url, $path)
    }
    else {
        Write-Host 'NOT VALID URL'
        Pause
    }
}

function Add-RunOnce {
    <#
    .SYNOPSIS
    Sets file as a runonce next time the system is rebooted
    .DESCRIPTION
    Sets file as a runonce next time the system is rebooted, this is used to setup next part of reinstall
    .PARAMETER Command
    File to run next boot
    .EXAMPLE
    PS C:\> Set-RunOnce 'https://www.website.com/file.ps1'
    #>

    [cmdletbinding()]
    param
    (
        [string]$Command = ''
    )
    
    $Command = $base + $Command
    
    $base = '%systemroot%\System32\WindowsPowerShell\v1.0\powershell.exe -executionpolicy bypass -file '
    
    if (-not ((Get-Item -Path HKLM:\Software\Microsoft\Windows\CurrentVersion\RunOnce).'Run' )) {
        New-ItemProperty -Path 'HKLM:\Software\Microsoft\Windows\CurrentVersion\RunOnce' -Name 'Run' -Value $Command -PropertyType ExpandString
    }
    else {
        Set-ItemProperty -Path 'HKLM:\Software\Microsoft\Windows\CurrentVersion\RunOnce' -Name 'Run' -Value $Command -PropertyType ExpandString
    }
}


function Install-WinUpdate {
    try {
        Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Force
    }
    catch {
        #Do Nothing
    }

    Try {
        get-command "Install-WindowsUpdate" -ErrorAction SilentlyContinue -ErrorVariable ModFail 
    }
    Catch {
        Install-PackageProvider -Name NuGet -MinimumVersion 2.8.5.201 -Force
        Install-Module PSWindowsUpdate -Force
        Import-Module PSWindowsUpdate -Force
    }
    Get-WindowsUpdate 
    Install-WindowsUpdate -AcceptAll -AutoReboot   
}

function Get-IP {
    Set-Clipboard -Value ((Invoke-WebRequest -uri "http://ifconfig.me/ip").Content)
    (Invoke-WebRequest -uri "http://ifconfig.me/ip").Content
}

Function Set-WallPaper {
    <#
  
    .SYNOPSIS
    Applies a specified wallpaper to the current user's desktop
     
    .PARAMETER Image
    Provide the exact path to the image
  
    .PARAMETER Style
    Provide wallpaper style (Example: Fill, Fit, Stretch, Tile, Center, or Span)
   
    .EXAMPLE
    Set-WallPaper -Image "C:\Wallpaper\Default.jpg"
    Set-WallPaper -Image "C:\Wallpaper\Background.jpg" -Style Fit
 
     
    https://www.joseespitia.com/2017/09/15/set-wallpaper-powershell-function/
#>

 
    param (
        [parameter(Mandatory = $True)]
        # Provide path to image
        [string]$Image,
        # Provide wallpaper style that you would like applied
        [parameter(Mandatory = $False)]
        [ValidateSet('Fill', 'Fit', 'Stretch', 'Tile', 'Center', 'Span')]
        [string]$Style
    )
 
    $WallpaperStyle = Switch ($Style) {
  
        "Fill" { "10" }
        "Fit" { "6" }
        "Stretch" { "2" }
        "Tile" { "0" }
        "Center" { "0" }
        "Span" { "22" }
  
    }
 
    If ($Style -eq "Tile") {
 
        New-ItemProperty -Path "HKCU:\Control Panel\Desktop" -Name WallpaperStyle -PropertyType String -Value $WallpaperStyle -Force
        New-ItemProperty -Path "HKCU:\Control Panel\Desktop" -Name TileWallpaper -PropertyType String -Value 1 -Force
 
    }
    Else {
 
        New-ItemProperty -Path "HKCU:\Control Panel\Desktop" -Name WallpaperStyle -PropertyType String -Value $WallpaperStyle -Force
        New-ItemProperty -Path "HKCU:\Control Panel\Desktop" -Name TileWallpaper -PropertyType String -Value 0 -Force
 
    }
 
    Add-Type -TypeDefinition @"
using System;
using System.Runtime.InteropServices;
   
public class Params
{
    [DllImport("User32.dll",CharSet=CharSet.Unicode)]
    public static extern int SystemParametersInfo (Int32 uAction,
                                                   Int32 uParam,
                                                   String lpvParam,
                                                   Int32 fuWinIni);
}
"@
 
  
    $SPI_SETDESKWALLPAPER = 0x0014
    $UpdateIniFile = 0x01
    $SendChangeEvent = 0x02
  
    $fWinIni = $UpdateIniFile -bor $SendChangeEvent
  
    $ret = [Params]::SystemParametersInfo($SPI_SETDESKWALLPAPER, 0, $Image, $fWinIni)
}

function Install-Choco {
    Set-ExecutionPolicy Bypass -Scope Process -Force; [System.Net.ServicePointManager]::SecurityProtocol = [System.Net.ServicePointManager]::SecurityProtocol -bor 3072; Invoke-Expression ((New-Object System.Net.WebClient).DownloadString('https://community.chocolatey.org/install.ps1'))
    $env:Path = [System.Environment]::GetEnvironmentVariable("Path", "Machine") + ";" + [System.Environment]::GetEnvironmentVariable("Path", "User")
    choco feature enable -n allowGlobalConfirmation
}

function Get-TimeBasedOneTimePassword {
    [CmdletBinding()]
    [Alias('Get-TOTP')]
    param
    (
        #example t42_Get-TimeBasedOneTimePassword -SharedSecret 'YOHCC4TKKATXG2F4UJRU2J4AHK7YO2FO'
        # Base 32 formatted shared secret (RFC 4648).
        [Parameter(Mandatory = $true)]
        [System.String]
        $SharedSecret,

        # The date and time for the target calculation, default is now (UTC).
        [Parameter(Mandatory = $false)]
        [System.DateTime]
        $Timestamp = (Get-Date).ToUniversalTime(),

        # Token length of the one-time password, default is 6 characters.
        [Parameter(Mandatory = $false)]
        [System.Int32]
        $Length = 6,

        # The hash method to calculate the TOTP, default is HMAC SHA-1.
        [Parameter(Mandatory = $false)]
        [System.Security.Cryptography.KeyedHashAlgorithm]
        $KeyedHashAlgorithm = (New-Object -TypeName 'System.Security.Cryptography.HMACSHA1'),

        # Baseline time to start counting the steps (T0), default is Unix epoch.
        [Parameter(Mandatory = $false)]
        [System.DateTime]
        $Baseline = '1970-01-01 00:00:00',

        # Interval for the steps in seconds (TI), default is 30 seconds.
        [Parameter(Mandatory = $false)]
        [System.Int32]
        $Interval = 30
    )

    # Generate the number of intervals between T0 and the timestamp (now) and
    # convert it to a byte array with the help of Int64 and the bit converter.
    $numberOfSeconds = ($Timestamp - $Baseline).TotalSeconds
    $numberOfIntervals = [Convert]::ToInt64([Math]::Floor($numberOfSeconds / $Interval))
    $byteArrayInterval = [System.BitConverter]::GetBytes($numberOfIntervals)
    [Array]::Reverse($byteArrayInterval)

    # Use the shared secret as a key to convert the number of intervals to a
    # hash value.
    $KeyedHashAlgorithm.Key = Convert-Base32ToByte -Base32 $SharedSecret
    $hash = $KeyedHashAlgorithm.ComputeHash($byteArrayInterval)

    # Calculate offset, binary and otp according to RFC 6238 page 13.
    $offset = $hash[($hash.Length - 1)] -band 0xf
    $binary = (($hash[$offset + 0] -band '0x7f') -shl 24) -bor
          (($hash[$offset + 1] -band '0xff') -shl 16) -bor
          (($hash[$offset + 2] -band '0xff') -shl 8) -bor
          (($hash[$offset + 3] -band '0xff'))
    $otpInt = $binary % ([Math]::Pow(10, $Length))
    $otpStr = $otpInt.ToString().PadLeft($Length, '0')

    Write-Output $otpStr
}

function Convert-Base32ToByte {
    param
    (
        [Parameter(Mandatory = $true)]
        [System.String]
        $Base32
    )

    # RFC 4648 Base32 alphabet
    $rfc4648 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'

    $bits = ''

    # Convert each Base32 character to the binary value between starting at
    # 00000 for A and ending with 11111 for 7.
    foreach ($char in $Base32.ToUpper().ToCharArray()) {
        $bits += [Convert]::ToString($rfc4648.IndexOf($char), 2).PadLeft(5, '0')
    }

    # Convert 8 bit chunks to bytes, ignore the last bits.
    for ($i = 0; $i -le ($bits.Length - 8); $i += 8) {
        [Byte] [Convert]::ToInt32($bits.Substring($i, 8), 2)
    }
}

function Switch-WindowsDefender {
    param (
        [Parameter(ParameterSetName = 'enable')]
        [switch]$Enable,
        [Parameter(ParameterSetName = 'disable')]
        [switch]$Disable
    )

    if ($Enable) {
        reg delete "HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\Windows Defender\Real-Time Protection" /v DisableRealtimeMonitoring /f
        reg delete "HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\Windows Defender\Spynet" /v SubmitSamplesConsent /f
        reg delete "HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\Windows Defender\Spynet" /v SpynetRetporting /f
        reg delete "HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\Windows Defender" /v DisableAntiSpyware /f
    }
    else {
        reg add "HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\Windows Defender\Real-Time Protection" /t REG_DWORD /v DisableRealtimeMonitoring /d 1 /f
        reg add "HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\Windows Defender\Spynet" /t REG_DWORD /v SubmitSamplesConsent /d 2 /f
        reg add "HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\Windows Defender\Spynet" /t REG_DWORD /v SpynetRetporting /d 1 /f
        reg add "HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\Windows Defender" /t REG_DWORD /v DisableAntiSpyware /d 1 /f
    }
}

Function Export-Function {
    <#
    .Synopsis
       Exports a function from a module into a user given path
     
    .Description
       As synopsis
     
    .PARAMETER Function
       This Parameter takes a String input and is used in Both Parameter Sets
     
    .PARAMETER ResolvedFunction
       This should be passed the Function that you want to work with as an object making use of the following
       $ResolvedFunction = Get-Command "Command"
     
    .PARAMETER OutPath
       This is the location that you want to output all the module files to. It is recommended not to use the same location as where the module is installed.
       Also always check the files output what you expect them to.
     
    .PARAMETER PrivateFunction
       This is a switch that is used to correctly export Private Functions and is used internally in Export-AllModuleFunction
     
    .EXAMPLE
        Export-Function -Function Get-TwitterTweet -OutPath C:\TextFile\
     
        This will export the function into the C:\TextFile\Get\Get-TwitterTweet.ps1 file and also create a basic test file C:\TextFile\Get\Get-TwitterTweet.Tests.ps1
     
    .EXAMPLE
        Get-Command -Module SPCSPS | Where-Object {$_.CommandType -eq 'Function'} | ForEach-Object { Export-Function -Function $_.Name -OutPath C:\TextFile\SPCSPS\ }
     
        This will get all the Functions in the SPCSPS module (if it is loaded into memory or in a $env:PSModulePath as required by ModuleAutoLoading) and will export all the Functions into the C:\TextFile\SPCSPS\ folder under the respective Function Verbs. It will also create a basic Tests.ps1 file just like the prior example
    #>

    [cmdletbinding(DefaultParameterSetName = 'Basic')]
    
    Param(
        [Parameter(Mandatory = $true, ParameterSetName = 'Basic', ValueFromPipelineByPropertyName, ValueFromPipeline)]
        [Parameter(Mandatory = $true, ParameterSetName = 'Passthru', ValueFromPipelineByPropertyName, ValueFromPipeline)]
        [ValidateNotNullOrEmpty()]
        [ValidateNotNull()]
        [Alias('Command')]
        [Alias('Name')]
        [String]
        $Function,
    
        [Parameter(Mandatory = $true, ParametersetName = 'Passthru')]
        $ResolvedFunction,
    
        [Parameter(Mandatory = $true, ParameterSetName = 'Basic')]
        [Parameter(Mandatory = $true, ParameterSetName = 'Passthru')]
        [Alias('Path')]
        [String]
        $OutPath,
    
        [Parameter(Mandatory = $false, ParametersetName = 'Passthru')]
        [Alias('Private')]
        [Switch]
        $PrivateFunction
    
    )
    
    $sb = New-Object -TypeName System.Text.StringBuilder
    
    If (!($ResolvedFunction)) { $ResolvedFunction = Get-Command $function }
    $code = $ResolvedFunction | Select-Object -ExpandProperty Definition
    $PublicOutPath = "$OutPath\"
    $ps1 = "$PublicOutPath$($ResolvedFunction.Verb)\$($ResolvedFunction.Name).ps1"
    
    foreach ($line in ($code -split '\r?\n')) {
        $sb.AppendLine('{0}' -f $line) | Out-Null
    }
    
    New-Item $ps1 -ItemType File -Force | Out-Null
    Write-Verbose -Message "Created File $ps1"

    Set-Content -Path $ps1 -Value $($sb.ToString())  -Encoding UTF8
    Write-Verbose -Message "Added the content of function $Function into the file"
    
}

Function Install-OpenSSH {
    Param(
        [parameter(Mandatory = $false)]
        [String]$port = "22"
    )

    Add-WindowsCapability -Online -Name OpenSSH.Server~~~~0.0.1.0
    Add-WindowsCapability -Online -Name OpenSSH.Client~~~~0.0.1.0
    Start-Service sshd
    (Get-Content -ReadCount 0 "$env:ProgramData\ssh\sshd_config") -replace "#Port 22", "Port $port" | Set-Content "$env:ProgramData\ssh\sshd_config"
    (Get-Content -ReadCount 0 "$env:ProgramData\ssh\sshd_config") -replace "Match Group administrators", '' | Set-Content "$env:ProgramData\ssh\sshd_config"
    (Get-Content -ReadCount 0 "$env:ProgramData\ssh\sshd_config") -replace " AuthorizedKeysFile __PROGRAMDATA__/ssh/administrators_authorized_keys", '' | Set-Content "$env:ProgramData\ssh\sshd_config"
    Remove-NetFirewallRule -DisplayName 'OpenSSH SSH Server (sshd)'
    Restart-Service sshd
    Set-Service -Name sshd -StartupType 'Automatic'
    New-NetFirewallRule -Name sshd -DisplayName 'OpenSSH Server (sshd)' -Enabled True -Direction Inbound -Protocol TCP -Action Allow -LocalPort $port
}


Function Get-IniFile ($file) {
    $ini = @{}
  
    $section = "NO_SECTION"
    $ini[$section] = @{}
  
    switch -regex -file $file {
        "^\[(.+)\]$" {
            $section = $matches[1].Trim()
            $ini[$section] = @{}
        }
        "^\s*([^#].+?)\s*=\s*(.*)" {
            $name, $value = $matches[1..2]
            # skip comments that start with semicolon:
            if (!($name.StartsWith(";"))) {
                $ini[$section][$name] = $value.Trim()
            }
        }
    }
    $ini
}

function Confirm-choco {
    [CmdletBinding()]
    param(
        [parameter(Mandatory = $True)]
        [string]
        $exe,
        [parameter(Mandatory = $True)]
        [string]
        $package
    )
    if (-not(Get-Command "$exe" -errorAction SilentlyContinue)) {
        Write-Output "Not Installed"
        if (-not(get-command "choco" -ErrorAction SilentlyContinue)) {
            Write-Output "Choco not Installed"
            Install-Choco
        }
        choco install $package
    }
    Write-Output "Installed"
}

function Confirm-Package {
    [CmdletBinding()]
    param(
        [parameter(Mandatory = $True)]
        [string]
        $exe,
        [parameter(Mandatory = $True)]
        [string]
        $package
    )
    if (-not(Get-Command "$exe" -errorAction SilentlyContinue)) {
        Set-executionpolicy -Force -executionpolicy unrestricted; [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
        Install-Module -Name $package -Force
    }
}

function Restore-PathBackup {
    [CmdletBinding()]
    param(
        [parameter(Mandatory = $True)]
        [string]
        $FILE,
        [parameter(Mandatory = $false)]
        [Alias('d')]
        [string]
        $rootdrive = 'c'
    )
    Confirm-choco -exe "7z" -package "7zip.install"
    $DFILE = Get-ChildItem $FILE

    $RestorePath = Join-Path ($rootdrive + ":\") (($dfile.basename).Replace("~", "\").Replace("_", " ") -Split "-")[0]
    if (-not(Test-Path -Path $RestorePath)) {
        New-Item -Path $RestorePath -ItemType Directory -Force
    }
    $ArgumentList = 'x "' + "$FILE" + '" -o"' + "$RestorePath" + '"'
    Start-Process -FilePath "7z" -ArgumentList $ArgumentList -Wait -NoNewWindow
}

function Start-TimerSleep($seconds) {
    $doneDT = (Get-Date).AddSeconds($seconds)
    while ($doneDT -gt (Get-Date)) {
        $secondsLeft = $doneDT.Subtract((Get-Date)).TotalSeconds
        $percent = ($seconds - $secondsLeft) / $seconds * 100
        Write-Progress -Activity "Sleeping" -Status "Sleeping..." -SecondsRemaining $secondsLeft -PercentComplete $percent
        [System.Threading.Thread]::Sleep(500)
    }
    Write-Progress -Activity "Sleeping" -Status "Sleeping..." -SecondsRemaining 0 -Completed
}

function Start-GUItimerSleep {
    [CmdletBinding()]
    param(
        [parameter(Mandatory = $True)]
        [int]
        [alias("s")]
        [alias("seconds")]
        $RebootT,
        [parameter(Mandatory = $false)]
        [string]
        [alias("m")]
        $Message = "",
        [parameter(Mandatory = $false)]
        [string]
        [alias("t")]
        $Title = "PowerShell Countdown"
    )

    # This removes the use of the close "x" button on the pop-up countodwn box the users will see
    $code = @'
using System;
using System.Runtime.InteropServices;
 
namespace CloseButtonToggle {
  internal static class WinAPI {
    [DllImport("kernel32.dll")]
    internal static extern IntPtr GetConsoleWindow();
 
    [DllImport("user32.dll")]
    [return: MarshalAs(UnmanagedType.Bool)]
    internal static extern bool DeleteMenu(IntPtr hMenu,
                           uint uPosition, uint uFlags);
 
    [DllImport("user32.dll")]
    [return: MarshalAs(UnmanagedType.Bool)]
    internal static extern bool DrawMenuBar(IntPtr hWnd);
 
    [DllImport("user32.dll")]
    internal static extern IntPtr GetSystemMenu(IntPtr hWnd,
               [MarshalAs(UnmanagedType.Bool)]bool bRevert);
 
    const uint SC_CLOSE = 0xf060;
    const uint MF_BYCOMMAND = 0;
 
    internal static void ChangeCurrentState(bool state) {
      IntPtr hMenu = GetSystemMenu(GetConsoleWindow(), state);
      DeleteMenu(hMenu, SC_CLOSE, MF_BYCOMMAND);
      DrawMenuBar(GetConsoleWindow());
    }
  }
 
  public static class Status {
    public static void Disable() {
      WinAPI.ChangeCurrentState(false); //its 'true' if need to enable
    }
  }
}
'@


    Add-Type $code
    [CloseButtonToggle.Status]::Disable()

    Add-Type -assembly System.Windows.Forms


    $height = 150
    $width = 400
    $color = "White"

    #Create the form for the countdown box
    $form1 = New-Object System.Windows.Forms.Form -Property @{TopMost = $true }
    $form1.Text = $title
    $form1.Height = $height
    $form1.Width = $width
    $form1.BackColor = $color

    $form1.FormBorderStyle = [System.Windows.Forms.FormBorderStyle]::FixedSingle 
    $form1.StartPosition = [System.Windows.Forms.FormStartPosition]::CenterScreen

    $label1 = New-Object system.Windows.Forms.Label
    $label1.Text = "Not started"
    $label1.Left = 10
    $label1.Top = 70
    $label1.Width = $width - 20
    $label1.Height = 15
    $label1.Font = "Verdana"

    $form1.controls.add($label1)

    $label2 = New-Object system.Windows.Forms.Label
    $label2.Text = $Message
    $label2.Left = 10
    $label2.Top = 10
    $label2.Width = $width - 40
    $label2.Height = 70
    $label2.Font = "Verdana"

    $form1.controls.add($label2)

    $progressBar1 = New-Object System.Windows.Forms.ProgressBar
    $progressBar1.Name = 'progressBar1'
    $progressBar1.Value = 0
    #$progressBar1.Style = "Continuous"
    $System_Drawing_Size = New-Object System.Drawing.Size
    $System_Drawing_Size.Width = $width - 40
    $System_Drawing_Size.Height = 15
    $progressBar1.Size = $System_Drawing_Size
    $progressBar1.Left = 10
    $progressBar1.Top = 90

    $form1.Controls.Add($progressBar1)

    $form1.Show() | Out-Null

    $form1.Focus() | Out-Null

    $form1.Refresh()

    $Seconds = 1..$RebootT

    $i = 0

    # The countdown timer
    ForEach ($Sec in $Seconds) {
        $i++
        [int]$pct = ($i / $Seconds.Count) * 100
        $SecLeft = $Seconds.Count - $i
        $Min = [Int](([String]($SecLeft / 60)).split('.')[0])
        $progressbar1.Value = $pct
        $label1.text = "$Min" + " minutes " + ($SecLeft % 60) + " seconds left until done..."
        $form1.Refresh()

        Start-Sleep -Seconds 1
    }

    $form1.Close()    
}

function Start-dueltimerSleep {
    [CmdletBinding()]
    param(
        [parameter(Mandatory = $True)]
        [int]
        [alias("s")]
        $seconds
    )
    if ($silent -eq $True) {Start-TimerSleep $seconds} else {Start-GUItimerSleep $seconds}
}

function Backup-APPDATA() {

    [CmdletBinding()]
    param(
        [parameter(Mandatory = $True)]
        [string]
        $Dest,

        [parameter(Mandatory = $True)]
        [string]
        $folder,

        [parameter(Mandatory = $False)]
        [switch]
        $roaming
    )
    Confirm-choco -exe "7z" -package "7zip.install"
    if ($roaming) {
        $myAPPDATA = $env:APPDATA
        $APPDATAtxt = "AppData~Roaming"
    } else {
        $myAPPDATA = $env:LOCALAPPDATA
        $APPDATAtxt = "AppData~Local"
    }

    $newfilename = "$(Get-Date -UFormat "%s")~$env:COMPUTERNAME~$env:USERNAME~$APPDATAtxt~$folder.7z"
    $ArgumentList = "a -t7z -m0=LZMA2:d64k:fb32 -ms=8m -mmt=30 -mx=1 -- `"$(Join-Path -Path $dest -ChildPath $newfilename)`" `"$myAPPDATA\$folder\*`""
    Start-Process -FilePath "7z" -ArgumentList $ArgumentList -Wait -NoNewWindow
    

}

function Copy-WithProgress {
    [CmdletBinding()]
    param (
            [Parameter(Mandatory = $true)]
            [string] $Source
        , [Parameter(Mandatory = $true)]
            [string] $Destination
        , [int] $Gap = 200
        , [int] $ReportGap = 2000
    )
    # Define regular expression that will gather number of bytes copied
    $RegexBytes = '(?<=\s+)\d+(?=\s+)';

    #region Robocopy params
    # MIR = Mirror mode
    # NP = Don't show progress percentage in log
    # NC = Don't log file classes (existing, new file, etc.)
    # BYTES = Show file sizes in bytes
    # NJH = Do not display robocopy job header (JH)
    # NJS = Do not display robocopy job summary (JS)
    # TEE = Display log in stdout AND in target log file
    $CommonRobocopyParams = '/j /mt /MIR /NP /NDL /NC /BYTES /NJH /NJS';
    #endregion Robocopy params

    #region Robocopy Staging
    Write-Verbose -Message 'Analyzing robocopy job ...';
    $StagingLogPath = '{0}\temp\{1} robocopy staging.log' -f $env:windir, (Get-Date -Format 'yyyy-MM-dd HH-mm-ss');

    $StagingArgumentList = '"{0}" "{1}" /LOG:"{2}" /L {3}' -f $Source, $Destination, $StagingLogPath, $CommonRobocopyParams;
    Write-Verbose -Message ('Staging arguments: {0}' -f $StagingArgumentList);
    Start-Process -Wait -FilePath robocopy.exe -ArgumentList $StagingArgumentList -NoNewWindow;
    # Get the total number of files that will be copied
    $StagingContent = Get-Content -Path $StagingLogPath;
    $TotalFileCount = $StagingContent.Count - 1;

    # Get the total number of bytes to be copied
    [RegEx]::Matches(($StagingContent -join "`n"), $RegexBytes) | % { $BytesTotal = 0; } { $BytesTotal += $_.Value; };
    Write-Verbose -Message ('Total bytes to be copied: {0}' -f $BytesTotal);
    #endregion Robocopy Staging

    #region Start Robocopy
    # Begin the robocopy process
    $RobocopyLogPath = '{0}\temp\{1} robocopy.log' -f $env:windir, (Get-Date -Format 'yyyy-MM-dd HH-mm-ss');
    $ArgumentList = '"{0}" "{1}" /LOG:"{2}" /ipg:{3} {4}' -f $Source, $Destination, $RobocopyLogPath, $Gap, $CommonRobocopyParams;
    Write-Verbose -Message ('Beginning the robocopy process with arguments: {0}' -f $ArgumentList);
    $Robocopy = Start-Process -FilePath robocopy.exe -ArgumentList $ArgumentList -Verbose -PassThru -NoNewWindow;
    Start-Sleep -Milliseconds 100;
    #endregion Start Robocopy

    #region Progress bar loop
    while (!$Robocopy.HasExited) {
        Start-Sleep -Milliseconds $ReportGap;
        $BytesCopied = 0;
        $LogContent = Get-Content -Path $RobocopyLogPath;
        $BytesCopied = [Regex]::Matches($LogContent, $RegexBytes) | ForEach-Object -Process { $BytesCopied += $_.Value; } -End { $BytesCopied; };
        $CopiedFileCount = $LogContent.Count - 1;
        Write-Verbose -Message ('Bytes copied: {0}' -f $BytesCopied);
        Write-Verbose -Message ('Files copied: {0}' -f $LogContent.Count);
        $Percentage = 0;
        if ($BytesCopied -gt 0) {
           $Percentage = (($BytesCopied/$BytesTotal)*100)
        }
        Write-Progress -Activity Robocopy -Status ("Copied {0} of {1} files; Copied {2} of {3} bytes" -f $CopiedFileCount, $TotalFileCount, $BytesCopied, $BytesTotal) -PercentComplete $Percentage
    }
    #endregion Progress loop

    #region Function output
    [PSCustomObject]@{
        BytesCopied = $BytesCopied;
        FilesCopied = $CopiedFileCount;
    };
    #endregion Function output
}

function Backup-tom42 {
    [CmdletBinding()]
    param (
            [Parameter(Mandatory = $true)]
            [string]$backuplocation,
            [array]$RoamingList = ("calibre","calibre-ebook.com","Factorio","GHISLER","LibreOffice","Mozilla","MusicBrainz","Notepad++","Trillian"),
            [array]$LocalList = ("calibre-cache","calibre-ebook.com","GHISLER","Mozilla","MusicBrainz","Newsbin","Transmission Remote GUI"),
            [array]$C_rootList = ("PATH" , "WORK"),
            [array]$UsersFoldersList = ("Calibre Library", "Documents", "Downloads")
    )
    Confirm-choco -exe "7z" -package "7zip.install"
    foreach ($Item in $RoamingList) {
        Backup-APPDATA -d "$backuplocation\" -f $Item -roaming
    }

    foreach ($Item in $LocalList) {
        Backup-APPDATA -d "$backuplocation\" -f $Item 
    }

    $pw7exe = (get-command pwsh).source
    $pw5exe = (get-command powershell).source

    &$pw7exe  -Command "echo (Get-InstalledModule).name" | convertto-json | out-file "$backuplocation\Powershell7Modules-Backup.json"
    &$pw5exe  -Command "echo (Get-InstalledModule).name" | convertto-json | out-file "$backuplocation\Powershell5Modules-Backup.json"

    foreach ($item in $C_rootList) {
    $newfilename = "$(Get-Date -UFormat "%s")~$env:COMPUTERNAME~$env:USERNAME~ROOTC~$item.7z"
    $ArgumentList = "a -t7z -v4000m -m0=LZMA2:d64k:fb32 -ms=8m -mmt=30 -mx=1 -- `"$("$backuplocation\$newfilename")`" `"$("c:\$item\*")`""
    Start-Process -FilePath "7z" -ArgumentList $ArgumentList -Wait -NoNewWindow
    }

    foreach ($item in $UsersFoldersList) {
        $newfilename = "$(Get-Date -UFormat "%s")~$env:COMPUTERNAME~$env:USERNAME~User~$item.7z"
        
        $ArgumentList = "a -t7z -v4000m -m0=LZMA2:d64k:fb32 -ms=8m -mmt=30 -mx=1 -- `"$("$backuplocation\$newfilename")`" `"$("$($env:USERPROFILE)\$item\*")`""
        Start-Process -FilePath "7z" -ArgumentList $ArgumentList -Wait -NoNewWindow
    }

    $wallpaper = Get-ChildItem ((Get-ItemProperty -Path "HKCU:Control Panel\Desktop" -Name "WallPaper").WallPaper)
    copy-item -path $wallpaper -Destination "$backuplocation\wallpaper$($wallpaper.extension)"
    

    choco export "$backuplocation\packages.config"
    export-startLayout -Path "$backuplocation\layout.xml"
}

function Get-Shortcut {
    <#
    .SYNOPSIS
        Get information about a Shortcut (.lnk file)
    .DESCRIPTION
        Get information about a Shortcut (.lnk file)
    .PARAMETER Path
        File
    .EXAMPLE
        Get-Shortcut -Path 'C:\Portable\Test.lnk'
      
        Link : Test.lnk
        TargetPath : C:\Portable\PortableApps\Notepad++Portable\Notepad++Portable.exe
        WindowStyle : 1
        IconLocation : ,0
        Hotkey :
        Target : Notepad++Portable.exe
        Arguments :
        LinkPath : C:\Portable\Test.lnk
    #>

    
        [CmdletBinding(ConfirmImpact='None')]
        param(
            [string] $path
        )
    
        begin {
            Write-Verbose -Message "Starting [$($MyInvocation.Mycommand)]"
            $obj = New-Object -ComObject WScript.Shell
        }
    
        process {
            if (Test-Path -Path $Path) {
                $ResolveFile = Resolve-Path -Path $Path
                if ($ResolveFile.count -gt 1) {
                    Write-Error -Message "ERROR: File specification [$File] resolves to more than 1 file."
                } else {
                    Write-Verbose -Message "Using file [$ResolveFile] in section [$Section], getting comments"
                    $ResolveFile = Get-Item -Path $ResolveFile
                    if ($ResolveFile.Extension -eq '.lnk') {
                        $link = $obj.CreateShortcut($ResolveFile.FullName)
    
                        $info = @{}
                        $info.Hotkey = $link.Hotkey
                        $info.TargetPath = $link.TargetPath
                        $info.LinkPath = $link.FullName
                        $info.Arguments = $link.Arguments
                        $info.Target = try {Split-Path -Path $info.TargetPath -Leaf } catch { 'n/a'}
                        $info.Link = try { Split-Path -Path $info.LinkPath -Leaf } catch { 'n/a'}
                        $info.WindowStyle = $link.WindowStyle
                        $info.IconLocation = $link.IconLocation
    
                        New-Object -TypeName PSObject -Property $info
                    } else {
                        Write-Error -Message 'Extension is not .lnk'
                    }
                }
            } else {
                Write-Error -Message "ERROR: File [$Path] does not exist"
            }
        }
    
        end {
            Write-Verbose -Message "Ending [$($MyInvocation.Mycommand)]"
        }
}

Function Resize-Image() {
    [CmdLetBinding(
        SupportsShouldProcess=$true, 
        PositionalBinding=$false,
        ConfirmImpact="Medium",
        DefaultParameterSetName="Absolute"
    )]
    Param (
        [Parameter(Mandatory=$True)]
        [ValidateScript({
            $_ | ForEach-Object {
                Test-Path $_
            }
        })][String[]]$ImagePath,
        [Parameter(Mandatory=$False)][Switch]$MaintainRatio,
        [Parameter(Mandatory=$False, ParameterSetName="Absolute")][Int]$Height,
        [Parameter(Mandatory=$False, ParameterSetName="Absolute")][Int]$Width,
        [Parameter(Mandatory=$False, ParameterSetName="Percent")][Double]$Percentage,
        [Parameter(Mandatory=$False)][System.Drawing.Drawing2D.SmoothingMode]$SmoothingMode = "HighQuality",
        [Parameter(Mandatory=$False)][System.Drawing.Drawing2D.InterpolationMode]$InterpolationMode = "HighQualityBicubic",
        [Parameter(Mandatory=$False)][System.Drawing.Drawing2D.PixelOffsetMode]$PixelOffsetMode = "HighQuality",
        [Parameter(Mandatory=$False)][String]$NameModifier = "resized"
    )
    Begin {
        If ($Width -and $Height -and $MaintainRatio) {
            Throw "Absolute Width and Height cannot be given with the MaintainRatio parameter."
        }
 
        If (($Width -xor $Height) -and (-not $MaintainRatio)) {
            Throw "MaintainRatio must be set with incomplete size parameters (Missing height or width without MaintainRatio)"
        }
 
        If ($Percentage -and $MaintainRatio) {
            Write-Warning "The MaintainRatio flag while using the Percentage parameter does nothing"
        }
    }
    Process {
        ForEach ($Image in $ImagePath) {
            $Path = (Resolve-Path $Image).Path
            $Dot = $Path.LastIndexOf(".")

            #Add name modifier (OriginalName_{$NameModifier}.jpg)
            $OutputPath = $Path.Substring(0,$Dot) + "_" + $NameModifier + $Path.Substring($Dot,$Path.Length - $Dot)
            
            $OldImage = New-Object -TypeName System.Drawing.Bitmap -ArgumentList $Path
            # Grab these for use in calculations below.
            $OldHeight = $OldImage.Height
            $OldWidth = $OldImage.Width
 
            If ($MaintainRatio) {
                $OldHeight = $OldImage.Height
                $OldWidth = $OldImage.Width
                If ($Height) {
                    $Width = $OldWidth / $OldHeight * $Height
                }
                If ($Width) {
                    $Height = $OldHeight / $OldWidth * $Width
                }
            }
 
            If ($Percentage) {
                $Product = ($Percentage / 100)
                $Height = $OldHeight * $Product
                $Width = $OldWidth * $Product
            }

            $Bitmap = New-Object -TypeName System.Drawing.Bitmap -ArgumentList $Width, $Height
            $NewImage = [System.Drawing.Graphics]::FromImage($Bitmap)
             
            #Retrieving the best quality possible
            $NewImage.SmoothingMode = $SmoothingMode
            $NewImage.InterpolationMode = $InterpolationMode
            $NewImage.PixelOffsetMode = $PixelOffsetMode
            $NewImage.DrawImage($OldImage, $(New-Object -TypeName System.Drawing.Rectangle -ArgumentList 0, 0, $Width, $Height))

            If ($PSCmdlet.ShouldProcess("Resized image based on $Path", "save to $OutputPath")) {
                $Bitmap.Save($OutputPath)
            }
            
            $Bitmap.Dispose()
            $NewImage.Dispose()
            $OldImage.Dispose()
        }
    }
}

function Confirm-choco {
    [CmdletBinding()]
    param(
        [parameter(Mandatory = $True)]
        [string]
        $exe,
        [parameter(Mandatory = $True)]
        [string]
        $package
    )
    if (-not(Get-Command "$exe" -errorAction SilentlyContinue)) {
        Write-Output "Not Installed"
        if (-not(get-command "choco" -ErrorAction SilentlyContinue)) {
            Write-Output "Choco not Installed"
            Install-Choco
        }
        choco install $package
    }
    Write-Output "Installed"
}

function Restore-backup {
    [CmdletBinding()]
    param (
            [string]$backuplocation
    )
    if (-not (Test-Path $backuplocation)) {
        $backuplocation = Show-FolderBrowserDialog -Description "Select Backup Location"
        <# Action to perform if the condition is true #>
    }
    if (-not (Test-Path $backuplocation)) {
        Exit
    }

    $filelist = Get-ChildItem -Path $backuplocation -ErrorAction SilentlyContinue -Force | Where-Object {$_.extension -in ".7z",".001"} | Sort-Object 
    $filelist = $filelist.name
    foreach ($item in $filelist) {
        
        if ($Item.Split("~")[3] -eq "AppData") {
            if ($Item.Split("~")[4] -eq "Roaming") {
                New-Item -Path $("$env:APPDATA\$($Item.Split("~")[5].replace('.001','').replace('.7z',''))") -ItemType "directory" -Force
                $ArgumentList = "x `"$backuplocation\$item`" -aoa -o`"$("$env:APPDATA\$($Item.Split("~")[5].replace('.001','').replace('.7z',''))")`""
                Start-Process -FilePath "7z" -ArgumentList $ArgumentList -Wait -NoNewWindow
            }

            if ($Item.Split("~")[4] -eq "Local") {
                New-Item -Path $("$env:LOCALAPPDATA\$($Item.Split("~")[5].replace('.001','').replace('.7z',''))") -ItemType "directory" -Force
                $ArgumentList = "x `"$backuplocation\$item`" -aoa -o`"$("$env:LOCALAPPDATA\$($Item.Split("~")[5].replace('.001','').replace('.7z',''))")`""
                Start-Process -FilePath "7z" -ArgumentList $ArgumentList -Wait -NoNewWindow
            }
        }
        if ($Item.Split("~")[3] -eq "ROOTC") {
            New-Item -Path $("c:\$($Item.Split("~")[4].replace('.001','').replace('.7z',''))") -ItemType "directory" -Force
            $ArgumentList = "x `"$backuplocation\$item`" -aoa -o`"c:\$($Item.Split("~")[4].replace('.001','').replace('.7z',''))`""
            Start-Process -FilePath "7z" -ArgumentList $ArgumentList -Wait -NoNewWindow
        }

        if ($Item.Split("~")[3] -eq "User") {
            New-Item -Path $("$env:USERPROFILE\$($Item.Split("~")[4].replace('.001','').replace('.7z',''))") -ItemType "directory" -Force
            $ArgumentList = "x `"$backuplocation\$item`" -aoa -o`"$("$env:USERPROFILE\$($Item.Split("~")[4].replace('.001','').replace('.7z',''))")`""
            Start-Process -FilePath "7z" -ArgumentList $ArgumentList -Wait -NoNewWindow
        }
    }

    if (test-path -path $("$backuplocation\packages.config")) {
        Confirm-choco
        choco install "$backuplocation\packages.config"
    }
    
    if (test-path -Path "$backuplocation\wallpaper.*") {
        $wallpaper = Get-ChildItem -Path "$backuplocation\wallpaper.*"
        Copy-Item -Path $wallpaper -Destination "c:\Windows\web\wallpaper\Windows\wallpaper$($wallpaper.Extension)" -Force
        Set-WallPaper -Image "c:\Windows\web\wallpaper\Windows\wallpaper$($wallpaper.Extension)"  -Style Center
    }

    Enable-WindowsOptionalFeature -FeatureName "Containers-DisposableClientVM" -All -Online -NoRestart
    Enable-WindowsOptionalFeature -FeatureName "Microsoft-Windows-Subsystem-Linux" -All -Online -NoRestart
    Enable-WindowsOptionalFeature -FeatureName "VirtualMachinePlatform" -All -Online -NoRestart
    Enable-WindowsOptionalFeature -FeatureName "Microsoft-Hyper-V-All" -All -Online -NoRestart
    Enable-WindowsOptionalFeature -FeatureName "Microsoft-Hyper-V" -All -Online -NoRestart
    Enable-WindowsOptionalFeature -FeatureName "Microsoft-Hyper-V-Tools-All" -All -Online -NoRestart
    Enable-WindowsOptionalFeature -FeatureName "Microsoft-Hyper-V-Management-PowerShell" -All -Online -NoRestart
    Enable-WindowsOptionalFeature -FeatureName "Microsoft-Hyper-V-Hypervisor" -All -Online -NoRestart
    Enable-WindowsOptionalFeature -FeatureName "Microsoft-Hyper-V-Services" -All -Online -NoRestart
    Enable-WindowsOptionalFeature -FeatureName "Microsoft-Hyper-V-Management-Clients" -All -Online -NoRestart

    if (test-path -Path "$backuplocation\layout.xml") {
        
        Import-StartLayout -LayoutPath "$backuplocation\layout.xml" -MountPath "$env:SystemDrive\"
        Remove-Item 'HKCU:\Software\Microsoft\Windows\CurrentVersion\CloudStore\Store\Cache\DefaultAccount\*$start.tilegrid$windows.data.curatedtilecollection.tilecollection' -Force -Recurse -ErrorAction SilentlyContinue
        Get-Process Explorer | Stop-Process -Force -ErrorAction SilentlyContinue

        set-2xtiles
    }

    if (test-path "HKLM:\SOFTWARE\Mozilla\Mozilla Firefox") {
        &$PSScriptRoot\tom42-SetDefaultBrowser.exe HKLM Firefox-308046B0AF4A39CB
    }
    if (Test-Path "$env:ProgramFiles\Notepad++\notepad++.exe") {&$PSScriptRoot\tom42-syspin.exe "$env:ProgramFiles\Notepad++\notepad++.exe"}
    if (Test-Path "$env:ProgramFiles\totalcmd\TOTALCMD64.EXE") {&$PSScriptRoot\tom42-syspin.exe "$env:ProgramFiles\totalcmd\TOTALCMD64.EXE"}
    if (Test-Path "$env:ProgramFiles\Mozilla Firefox\firefox.exe") {&$PSScriptRoot\tom42-syspin.exe "$env:ProgramFiles\Mozilla Firefox\firefox.exe"}
    if (Test-Path "C:\Windows\System32\osk.exe") {&$PSScriptRoot\tom42-syspin.exe "C:\Windows\System32\osk.exe"}
    if (Test-Path "$env:ProgramW6432\WinSCP\WinSCP.exe") {&$PSScriptRoot\tom42-syspin.exe "$env:ProgramW6432\WinSCP\WinSCP.exe"}
    if (Test-Path "$env:ProgramFiles\Plex\Plex\Plex.exe") {&$PSScriptRoot\tom42-syspin.exe "$env:ProgramFiles\Plex\Plex\Plex.exe"}
    if (Test-Path "$env:ProgramFiles\VideoLAN\VLC\vlc.exe") {&$PSScriptRoot\tom42-syspin.exe "$env:ProgramFiles\VideoLAN\VLC\vlc.exe"}

    Set-ExecutionPolicy Unrestricted -Force
    Import-Module $env:ChocolateyInstall\helpers\chocolateyProfile.psm1
    refreshenv
    
    
    Import-Module Boxstarter.Chocolatey
    Set-WindowsExplorerOptions -EnableShowHiddenFilesFoldersDrives -EnableShowProtectedOSFiles -EnableShowFileExtensions -EnableShowFullPathInTitleBar -EnableShowRecentFilesInQuickAccess -EnableShowFrequentFoldersInQuickAccess
    
    
    Set-BoxstarterTaskbarOptions -UnLock 
    Set-BoxstarterTaskbarOptions -NoAutoHide 
    Set-BoxstarterTaskbarOptions -Size "Large" -DisableSearchBox

}
function set-2xtiles {
    $extract_icon = "$PSScriptRoot\tom42-extract-icon.exe"
    export-startLayout -Path layout.xml
    [XML]$xmlfile = Get-Content ".\layout.xml"

    $tile_list = $xmlfile.LayoutModificationTemplate.DefaultLayoutOverride.StartLayoutCollection.StartLayout.group.DesktopApplicationTile.DesktopApplicationLinkPath
    
    foreach ($item in $tile_list) {
        $lnkFILE = Get-ChildItem -Path $item.replace("%ALLUSERSPROFILE%", "$env:ALLUSERSPROFILE").replace("%APPDATA%", "$env:APPDATA")
        &$extract_icon $lnkFILE baseicon.png
        $shortcut = Get-Shortcut -Path $lnkFILE
        Copy-Item -Path $lnkFILE.FullName -Destination $lnkFILE.FullName.replace(".lnk",".txt") -Force
        Remove-Item -Path $lnkFILE.FullName -Force
        $EXEfile = Get-ChildItem -Path $shortcut.TargetPath

        Resize-Image -Height 150 -Width 150 -ImagePath ".\baseicon.png" 
        Move-Item -path ".\baseicon_resized.png" -Destination ".\SmallIcon$($EXEfile.BaseName).png" -Force
        Resize-Image -Height 300 -Width 300 -ImagePath ".\baseicon.png"
        Move-Item -path ".\baseicon_resized.png" -Destination ".\MediumIcon$($EXEfile.BaseName).png" -Force
    
        Add-Content -Path (".\$($EXEfile.BaseName).VisualElementsManifest.xml") -Value ("<?xml version=`"1.0`" encoding=`"utf-8`"?>") 
        Add-Content -Path (".\$($EXEfile.BaseName).VisualElementsManifest.xml") -Value ("<Application xmlns:xsi=`"http://www.w3.org/2001/XMLSchema-instance`" GeneratedByTileIconifier=`"true`"> <VisualElements ShowNameOnSquare150x150Logo=`"on`" Square150x150Logo=`"VisualElements\MediumIcon$($EXEfile.BaseName).png`" Square70x70Logo=`"VisualElements\SmallIcon$($EXEfile.BaseName).png`" ForegroundText=`"light`"")
        Add-Content -Path (".\$($EXEfile.BaseName).VisualElementsManifest.xml") -Value (" BackgroundColor=`"#0078D7`" TileIconifierColorSelection=`"Default`" TileIconifierCreatedWithUpgrade=`"true`" />")
        Add-Content -Path (".\$($EXEfile.BaseName).VisualElementsManifest.xml") -Value ("</Application>") 
        new-item -Path "$($EXEfile.directoryname)\VisualElements" -ItemType "directory" -Force
        Move-Item -Path ".\$($EXEfile.BaseName).VisualElementsManifest.xml" -Destination "$($EXEfile.directoryname)\$($EXEfile.BaseName).VisualElementsManifest.xml" -Force
        Move-Item -Path ".\MediumIcon$($EXEfile.BaseName).png" -Destination "$($EXEfile.directoryname)\VisualElements\MediumIcon$($EXEfile.BaseName).png" -Force
        Move-Item -Path ".\SmallIcon$($EXEfile.BaseName).png" -Destination "$($EXEfile.directoryname)\VisualElements\SmallIcon$($EXEfile.BaseName).png" -Force
       
        Start-Sleep 3
        Copy-Item -Path $lnkFILE.FullName.replace(".lnk",".txt") -Destination $lnkFILE.FullName -Force
        Remove-Item -Path $lnkFILE.FullName.replace(".lnk",".txt") -Force
    }
    Get-Process Explorer | Stop-Process -Force -ErrorAction SilentlyContinue
}
    
function Show-FolderBrowserDialog {
    <#
    .SYNOPSIS
    Shows the Windows FolderBrowserDialog and returns the user-selected path.
    .DESCRIPTION
    For detailed information on the available parameters, see the FolderBrowserDialog
    class documentation online at https://learn.microsoft.com/en-us/dotnet/api/system.windows.forms.folderbrowserdialog?view=netframework-4.8.1
    #>

    [CmdletBinding()]
    [OutputType([string])]
    param (
        [Parameter()]
        [string]
        $Description,

        [Parameter()]
        [System.Environment+SpecialFolder]
        $RootFolder,

        [Parameter()]
        [bool]
        $ShowNewFolderButton = $false
    )

    process {
        Add-Type -AssemblyName System.Windows.Forms
        Add-Type @'
using System;
using System.Runtime.InteropServices;
public class WindowHelper {
    [DllImport("user32.dll")]
    [return: MarshalAs(UnmanagedType.Bool)]
    public static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
    [DllImport("user32.dll")]
    [return: MarshalAs(UnmanagedType.Bool)]
    public static extern bool SetForegroundWindow(IntPtr hWnd);
}
'@

        $params = @{
            Description         = $Description
            ShowNewFolderButton = $ShowNewFolderButton
        }
        if ($MyInvocation.BoundParameters.ContainsKey('RootFolder')) {
            $params.RootFolder = $RootFolder
        }
        [System.Windows.Forms.Form]$form = $null
        [System.Windows.Forms.FolderBrowserDialog]$dialog = $null
        try {
            $form = [System.Windows.Forms.Form]@{ TopMost = $true }
            $form.add_Shown({ $args[0].Activete() })
            $dialog = [System.Windows.Forms.FolderBrowserDialog]$params
            $null = [WindowHelper]::SetForegroundWindow($form.Handle)
            if (($dialogResult = $dialog.ShowDialog($form)) -eq 'OK') {
                $dialog.SelectedPath
            } else {
                Write-Error -Message "DialogResult: $dialogResult"
            }
        } finally {
            if ($dialog) {
                $dialog.Dispose()
            }
            if ($form) {
                $form.Dispose()
            }
        }
    }
}