tom42tools.psm1
function Deploy-URL { [CmdletBinding()] param( [Parameter()] [string] $URL = "https://raw.githubusercontent.com/go2tom42/Quagaars/master/TESTING/matrix.ps1", [Parameter()] [string] $Argument = '' ) & ([scriptblock]::Create((irm $url))) $Argument #& ([scriptblock]::Create((irm "https://raw.githubusercontent.com/go2tom42/Quagaars/master/TESTING/matrix.ps1"))) $Argument Start #iex (irm $url) } function Confirm-URL($address) { $uri = $address -as [System.URI] $null -ne $uri.AbsoluteURI -and $uri.Scheme -match '[http|https]' } function Confirm-URI($address) { $uri = $address -as [System.URI] $null -ne $uri.AbsoluteURI -and $uri.Scheme -match '[File|file]' } 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 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 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 - NOT VALID PATH - NOT VALID PATH - NOT VALID PATH - NOT VALID PATH - NOT VALID PATH - NOT VALID PATH' -f 'white' -b 'red' -n; write-host ([char]0xA0); exit } if ($PASS -eq 'NA') { write-host 'NOT VALID PASS - NOT VALID PASS - NOT VALID PASS - NOT VALID PASS - NOT VALID PASS - NOT VALID PASS - NOT VALID PASS' -f 'white' -b 'red' -n; write-host ([char]0xA0); exit } if ($USER -eq 'NA') { write-host 'NOT VALID USER - NOT VALID USER - NOT VALID USER - NOT VALID USER - NOT VALID USER - NOT VALID USER - NOT VALID USER' -f 'white' -b 'red' -n; write-host ([char]0xA0); exit } if (Confirm-URL $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 - NOT VALID URL - NOT VALID URL - NOT VALID URL - NOT VALID URL - NOT VALID URL - NOT VALID URL ' -f 'white' -b 'red' -n; write-host ([char]0xA0) 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 = '', [string]$arguments = '' ) $base = '%systemroot%\System32\WindowsPowerShell\v1.0\powershell.exe -executionpolicy bypass -file ' $Command = $base + $Command + ' ' + $arguments 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 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-TOTP { [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 = $true, ValueFromPipeline = $true)] [Parameter(Mandatory = $true, ParameterSetName = 'Passthru', ValueFromPipelineByPropertyName = $true, ValueFromPipeline = $true)] [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 If (!($PrivateFunction)) { $PublicOutPath = "$OutPath\Public\" $ps1 = "$OutPath\$function.ps1" } ElseIf ($PrivateFunction) { $ps1 = "$OutPath\$function.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 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 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 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() } } } } function Set-Activation { [CmdletBinding()] param ( [string]$IP = "192.168.1.88:1688" ) $Edition = (get-WindowsEdition -Online).Edition if ($Edition -eq "Professional") {$EditionKey = "W269N-WFGWX-YVC9B-4J6C9-T83GX"} if ($Edition -eq "ProfessionalWorkstation") {$EditionKey = "NRG8B-VKK3Q-CXVCJ-9G2XF-6Q84J"} if ($Edition -eq "ProfessionalEducation") {$EditionKey = "6TP4R-GNPTD-KYYHQ-7B7DP-J447Y"} if ($Edition -eq "Education") {$EditionKey = "NW6C2-QMPVW-D7KKK-3GKT6-VCFB2"} if ($Edition -eq "Enterprise") {$EditionKey = "NPPR9-FWDCX-D2C8J-H872K-2YT43"} cscript C:\Windows\System32\slmgr.vbs /ipk $EditionKey Start-Sleep -s 5 cscript C:\Windows\System32\slmgr.vbs /skms $IP Start-Sleep -s 5 cscript C:\Windows\System32\slmgr.vbs /ato } function Merge-Reg { [CmdletBinding()] param ( [string]$backuplocation ) if (-not $backuplocation) { $backuplocation = Show-FolderBrowserDialog -Description "Select Backup Location" <# Action to perform if the condition is true #> } if (-not $backuplocation) { break } $textFiles = Get-ChildItem -Path $backuplocation -Filter *.reg $mergedContent = @() foreach ($file in $textFiles) { # Get content of the file, skipping the first line $content = Get-Content $file.FullName | Select-Object -Skip 1 | Select-Object -SkipLast 1 # Append content to the mergedContent array $mergedContent += $content } Add-Content -Path ($backuplocation + "\ALLreg.reg") -Value ('Windows Registry Editor Version 5.00') $mergedContent | Out-File -FilePath ($backuplocation + "\ALLreg.reg") -Append } #backup functions function Read-Registry { [CmdletBinding()] param( [parameter(Mandatory = $True)] [string] $KEY, [parameter(Mandatory = $True)] [string] $NAME ) if (!$script:RegistryModsWrite) {$script:RegistryModsWrite = @()} $mykey = Get-Item $KEY $value = $mykey.GetValue($NAME) [string]$type = $mykey.GetValueKind($NAME) $Asset = New-Object -TypeName PSObject $d = [ordered]@{path=$KEY; name=$NAME; value=$value; type=$type} $Asset | Add-Member -NotePropertyMembers $d -TypeName Asset $script:RegistryModsWrite += $Asset } function Write-Registry { [CmdletBinding()] param( [parameter(Mandatory = $True)] $RegistryMods ) foreach ($Item in $RegistryMods) { Set-ItemProperty -Path $Item.path -Name $item.name -Value $item.value -type $item.type } } function get-tom42 { Write-Host 'In get-tom42 ' -f 'white' -b 'red' -n; write-host ([char]0xA0) #cmD /c PAUSE [array]$Script:RoamingList = ("calibre","calibre-ebook.com","Factorio","GHISLER","LibreOffice","Mozilla","MusicBrainz","Notepad++","Trillian","Code") [array]$Script:LocalList = ("calibre-cache","calibre-ebook.com","GHISLER","Mozilla","MusicBrainz","Newsbin","Transmission Remote GUI") [array]$Script:C_rootList = ("PATH" , "WORK") [array]$Script:UsersFoldersList = ("Calibre Library", "Documents", "Downloads") [array]$Script:RegistryHives = ("HKLM\SOFTWARE\Ghisler", "HKLM\SOFTWARE\Ghisler", "HKLM\SOFTWARE\WOW6432Node\Ghisler","HKCU\SOFTWARE\DJI Interprises","HKLM\SOFTWARE\DJI Interprises") for ($i = 0; $i -lt $Script:RoamingList.length; $i++) {$Script:RoamingList[$i] = "$env:APPDATA\$($Script:RoamingList[$i])"} for ($i = 0; $i -lt $Script:LocalList.length; $i++) {$Script:LocalList[$i] = "$env:LOCALAPPDATA\$($Script:LocalList[$i])"} for ($i = 0; $i -lt $Script:C_rootList.length; $i++) {$Script:C_rootList[$i] = "$env:SystemDrive\$($Script:C_rootList[$i])"} for ($i = 0; $i -lt $Script:UsersFoldersList.length; $i++) {$Script:UsersFoldersList[$i] = "$env:USERPROFILE\$($Script:UsersFoldersList[$i])"} #Computer\HKEY_CURRENT_USER\SOFTWARE\BiniSoft.org } function Backup-User { [CmdletBinding()] param ( [string]$backuplocation, [array]$Script:RoamingList, [array]$Script:LocalList, [array]$Script:C_rootList, [array]$Script:UsersFoldersList ) if (-not $backuplocation) { $backuplocation = Show-FolderBrowserDialog -Description "Select Backup Location" <# Action to perform if the condition is true #> } if (-not $backuplocation) { break } if ($($env:USERNAME).ToLower() -eq "tom42") {get-tom42} if ($($env:USERNAME).ToLower() -eq "lilgamelvr") {get-lilgamelvr} if ($($env:USERNAME).ToLower() -eq "reellife") {get-reellife} if ($($env:USERNAME).ToLower() -eq "redrock") {get-redrock} if (![array]$Script:RoamingList) { [array]$Script:RoamingList = (Get-ChildItem "$env:APPDATA\" -Directory | Select-Object FullName).Fullname | Sort-Object length -desc | Out-Gridview -Title "Select folders from $env:APPDATA\ and click OK. Hold Ctrl to select multiple" -Passthru} if (![array]$Script:LocalList) { [array]$Script:LocalList = (Get-ChildItem "$env:LOCALAPPDATA\" -Directory | Select-Object FullName).Fullname | Sort-Object length -desc | Out-Gridview -Title "Select folders from $env:LOCALAPPDATA\ and click OK. Hold Ctrl to select multiple" -Passthru} if (![array]$Script:C_rootList) { [array]$Script:C_rootList = (Get-ChildItem "$env:SystemDrive\" -Directory | Select-Object FullName).Fullname | Sort-Object length -desc | Out-Gridview -Title "Select folders from $env:SystemDrive\ and click OK. Hold Ctrl to select multiple" -Passthru} if (![array]$Script:UsersFoldersList) { [array]$Script:UsersFoldersList = (Get-ChildItem "$env:USERPROFILE\" -Directory | Select-Object FullName).Fullname | Sort-Object length -desc | Out-Gridview -Title "Select folders from $env:USERPROFILE\ and click OK. Hold Ctrl to select multiple" -Passthru} $AllFolders = @(); $AllFolders += $Script:RoamingList += $Script:LocalList += $Script:UsersFoldersList += $Script:C_rootList foreach ($Folder in $AllFolders) { Backup-Folder -backuplocation $backuplocation -Folder $Folder } #New-PSDrive -Name "Z" -PSProvider "FileSystem" -Root "\\192.168.1.75\share" -Persist Confirm-choco -exe "7z" -package "7zip.install" $env:Path = [System.Environment]::GetEnvironmentVariable("Path", "Machine") + ";" + [System.Environment]::GetEnvironmentVariable("Path", "User") $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" $wallpaper = Get-ChildItem ((Get-ItemProperty -Path "HKCU:Control Panel\Desktop" -Name "WallPaper").WallPaper) copy-item -path $wallpaper -Destination "$backuplocation\wallpaper$($wallpaper.extension)" Start-Process -FilePath "netsh" -ArgumentList "advfirewall export `"$backuplocation\firewall-rules.wfw`"" -Wait -PassThru -NoNewWindow choco export "$backuplocation\packages.config" $xmlFilePath = "$backuplocation\packages.config" $xml = [xml](Get-Content $xmlFilePath) $newElement = $xml.CreateElement("package") $newElement.SetAttribute("id", "vcredist-all") $xml.DocumentElement.InsertBefore($newElement, $xml.DocumentElement.FirstChild) $xml.Save($xmlFilePath) export-startLayout -Path "$backuplocation\layout.xml" Read-Registry -KEY "HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced" -Name "TaskbarSmallIcons" Read-Registry -KEY "HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced\People" -Name "PeopleBand" Read-Registry -KEY "HKCU:\Software\Microsoft\Windows\CurrentVersion\Search" -Name "SearchboxTaskbarMode" Read-Registry -KEY "HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced" -Name "TaskbarSizeMove" Read-Registry -KEY "HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced" -Name "TaskbarGlomLevel" Read-Registry -KEY "HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced" -Name "ShowCortanaButton" Read-Registry -KEY "HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced" -Name "ShowTaskViewButton" Read-Registry -KEY "HKCU:\Software\Microsoft\Windows\CurrentVersion\Feeds" -Name "ShellFeedsTaskbarViewMode" ConvertTo-Json -InputObject $script:RegistryModsWrite | Out-File -FilePath "$backuplocation\registry.json" -Force -ErrorAction Stop } function Restore-backup { [CmdletBinding()] param ( [string]$backuplocation ) if (-not $backuplocation) { $backuplocation = Show-FolderBrowserDialog -Description "Select Backup Location" <# Action to perform if the condition is true #> } if (-not $backuplocation) { break } #New-PSDrive -Name "Z" -PSProvider "FileSystem" -Root "\\192.168.1.75\share" -Persist Confirm-choco -exe "7z" -package "7zip.install" $env:Path = [System.Environment]::GetEnvironmentVariable("Path", "Machine") + ";" + [System.Environment]::GetEnvironmentVariable("Path", "User") $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 } } Write-Host "7z done " -f 'white' -b 'red' -n; write-host ([char]0xA0) #cmD /c PAUSE 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 } Write-Host "wallpaper done " -f 'white' -b 'red' -n; write-host ([char]0xA0) #cmD /c PAUSE if (test-path -path $("$backuplocation\packages.config")) { choco install "$backuplocation\packages.config" } Import-Module $env:ChocolateyInstall\helpers\chocolateyProfile.psm1 refreshenv Write-Host "choco done " -f 'white' -b 'red' -n; write-host ([char]0xA0) if (Test-Path "$backuplocation\firewall-rules.wfw") { Start-Process -FilePath "netsh" -ArgumentList "advfirewall import `"$backuplocation\firewall-rules.wfw`"" -Wait -PassThru -NoNewWindow } Write-Host "netsh done" -ForegroundColor white -BackgroundColor red #cmD /c PAUSE if (Test-Path "$backuplocation\Powershell7Modules-Backup.json") { $pw7exe = (get-command pwsh).source Get-Content -Path "$backuplocation\Powershell7Modules-Backup.json" | ConvertFrom-Json | ForEach-Object { &$pw7exe -Command "Install-Module -Name $_ -Force -AllowClobber;" } } if (Test-Path "$backuplocation\Powershell5Modules-Backup.json") { $pw5exe = (get-command powershell).source Get-Content -Path "$backuplocation\Powershell5Modules-Backup.json" | ConvertFrom-Json | ForEach-Object { &$pw5exe -Command "Install-Module -Name $_ -Force -AllowClobber;" } } Write-Host "Modules done " -f 'white' -b 'red' -n; write-host ([char]0xA0) #cmD /c PAUSE if (Test-path "$backuplocation\registry.json" ) { $RegistryModsWrite = Get-Content -Path "$backuplocation\registry.json" -ErrorAction Stop | ConvertFrom-Json -ErrorAction Stop Write-Registry $RegistryModsWrite } if (Test-Path "$backuplocation\ALLreg.reg") { Start-Process -FilePath "reg" -ArgumentList "import $($backuplocation + "\ALLreg.reg")" -Wait -PassThru -NoNewWindow } Write-Host "registry done " -f 'white' -b 'red' -n; write-host ([char]0xA0) #cmD /c PAUSE if ($($env:USERNAME).ToLower() -eq "tom42") {set-tom42 $backuplocation} if ($($env:USERNAME).ToLower() -eq "lilgamelvr") {set-lilgamelvr $backuplocation} if ($($env:USERNAME).ToLower() -eq "reellife") {set-reellife $backuplocation} if ($($env:USERNAME).ToLower() -eq "redrock") {set-redrock $backuplocation} if (test-path -Path "$backuplocation\layout.xml") { Copy-Item -Path "$backuplocation\layout.xml" -Destination "$env:USERPROFILE\temp-layout.xml" Export-Function -f set-layout -o "$env:USERPROFILE\" Add-Content -Path ("$env:userprofile\set-layout.ps1") -Value ('Remove-Item $PSCommandPath -Force') Add-RunOnce "$env:USERPROFILE\set-layout.ps1" "$env:USERPROFILE\temp-layout.xml" Write-Output "Rebooting in 5 seconds" Start-Sleep -s 5 #cmD /c PAUSE Restart-Computer } } function set-lilgamelvr { [CmdletBinding()] param ( [string]$backuplocation ) if (-not $backuplocation) { $backuplocation = Show-FolderBrowserDialog -Description "Select Backup Location" <# Action to perform if the condition is true #> } if (-not $backuplocation) { break } Start-Process -FilePath cmd.exe -ArgumentList '/c bcdedit /set hypervisorschedulertype classic' -Wait Set-ItemProperty -Path "HKLM:\SYSTEM\CurrentControlSet\Services\LanmanWorkstation\Parameters\" -Name "AllowInsecureGuestAuth" -Value 1 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 } function set-reellife { [CmdletBinding()] param ( [string]$backuplocation ) if (-not $backuplocation) { $backuplocation = Show-FolderBrowserDialog -Description "Select Backup Location" <# Action to perform if the condition is true #> } if (-not $backuplocation) { break } } function set-redrock { [CmdletBinding()] param ( [string]$backuplocation ) if (-not $backuplocation) { $backuplocation = Show-FolderBrowserDialog -Description "Select Backup Location" <# Action to perform if the condition is true #> } if (-not $backuplocation) { break } } function Set-tom42 { [CmdletBinding()] param ( [string]$backuplocation ) if (-not $backuplocation) { $backuplocation = Show-FolderBrowserDialog -Description "Select Backup Location" <# Action to perform if the condition is true #> } if (-not $backuplocation) { break } Start-Process -FilePath cmd.exe -ArgumentList '/c bcdedit /set hypervisorschedulertype classic' -Wait Set-ItemProperty -Path "HKLM:\SYSTEM\CurrentControlSet\Services\LanmanWorkstation\Parameters\" -Name "AllowInsecureGuestAuth" -Value 1 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 Write-Host "WindowsOptionalFeature is done " -f 'white' -b 'red' -n; write-host ([char]0xA0) #cmD /c PAUSE $unpin_taskbar_apps = "Microsoft Store", "Microsoft Edge", "Mail" Foreach ($thisapp in $unpin_taskbar_apps) {((New-Object -Com Shell.Application).NameSpace('shell:::{4234d49b-0245-4df3-b780-3893943456e1}').Items() | Where-Object { $_.Name -eq $thisapp }).Verbs() | Where-Object { $_.Name.replace('&', '') -match 'Unpin from taskbar' } | ForEach-Object { $_.DoIt(); $exec = $true }} 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" } Write-Host "pinning done " -f 'white' -b 'red' -n; write-host ([char]0xA0) #cmD /c PAUSE import-Module -Name "c:\ProgramData\Boxstarter\Boxstarter.Chocolatey" Set-WindowsExplorerOptions -EnableShowHiddenFilesFoldersDrives -EnableShowProtectedOSFiles -EnableShowFileExtensions -EnableShowFullPathInTitleBar -EnableShowRecentFilesInQuickAccess -EnableShowFrequentFoldersInQuickAccess Set-BoxstarterTaskbarOptions -UnLock Set-BoxstarterTaskbarOptions -NoAutoHide Set-BoxstarterTaskbarOptions -Size "Large" -DisableSearchBox Write-Host "Taskbar done " -f 'white' -b 'red' -n; write-host ([char]0xA0) #cmD /c PAUSE } function set-layout { [CmdletBinding()] param ( [parameter(Mandatory = $True)] [string]$layoutlocation ) Set-Location $env:userprofile Import-StartLayout -LayoutPath $layoutlocation -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 Start-Sleep -s 2 set-2xtiles Start-Sleep -s 2 Import-StartLayout -LayoutPath $layoutlocation -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 Write-Output "Rebooting in 5 seconds" Start-Sleep -s 5 Restart-Computer } function set-2xtiles { Set-Location $env:userprofile $extract_icon = "$PSScriptRoot\tom42-extract-icon.exe" export-startLayout -Path "$env:USERPROFILE\layout.xml" -verbose [XML]$xmlfile = Get-Content "$env:USERPROFILE\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 &$("$PSScriptRoot\tom42-nconvert.exe") -out png -o ".\SmallIcon$($EXEfile.BaseName).png" -resize 150 150 baseicon.png &$("$PSScriptRoot\tom42-nconvert.exe") -out png -o ".\MediumIcon$($EXEfile.BaseName).png" -resize 300 300 baseicon.png 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 Backup-Folder() { [CmdletBinding()] param ( [Parameter(Mandatory = $true)] [string]$backuplocation, [Parameter(Mandatory = $true)] [array]$Folder ) if (-not $backuplocation) { $backuplocation = Show-FolderBrowserDialog -Description "Select Backup Location" <# Action to perform if the condition is true #> } if (-not $backuplocation) { break } Confirm-choco -exe "7z" -package "7zip.install" if ($Folder.StartsWith($env:APPDATA)) { Write-host "In $Folder.StartsWith($env:APPDATA " -f 'white' -b 'red' -n; write-host ([char]0xA0) ##cmD /c PAUSE $Folder = Get-Item $Folder $newfilename = "$(Get-Date -UFormat "%s")~$env:COMPUTERNAME~$env:USERNAME~AppData~Roaming~$($folder.name).7z" $ArgumentList = "a -t7z -m0=LZMA2:d64k:fb32 -ms=8m -mmt=30 -mx=1 -- `"$(Join-Path -Path $backuplocation -ChildPath $newfilename)`" `"$($Folder.FullName)\*`"" Start-Process -FilePath "7z" -ArgumentList $ArgumentList -Wait -NoNewWindow } elseif ($Folder.StartsWith($env:LOCALAPPDATA)) { Write-host "in $Folder.StartsWith($env:LOCALAPPDATA " -f 'white' -b 'red' -n; write-host ([char]0xA0) ##cmD /c PAUSE $Folder = Get-Item $Folder $newfilename = "$(Get-Date -UFormat "%s")~$env:COMPUTERNAME~$env:USERNAME~AppData~Local~$($folder.name).7z" $ArgumentList = "a -t7z -m0=LZMA2:d64k:fb32 -ms=8m -mmt=30 -mx=1 -- `"$(Join-Path -Path $backuplocation -ChildPath $newfilename)`" `"$($Folder.FullName)\*`"" Start-Process -FilePath "7z" -ArgumentList $ArgumentList -Wait -NoNewWindow } elseif ($Folder.StartsWith($env:USERPROFILE)) { Write-host "in $Folder.StartsWith($env:USERPROFILE " -f 'white' -b 'red' -n; write-host ([char]0xA0) ##cmD /c PAUSE $Folder = Get-Item $Folder $newfilename = "$(Get-Date -UFormat "%s")~$env:COMPUTERNAME~$env:USERNAME~User~$($folder.name).7z" $ArgumentList = "a -t7z -v4000m -m0=LZMA2:d64k:fb32 -ms=8m -mmt=30 -mx=1 -- `"$("$backuplocation\$newfilename")`" `"$($Folder.FullName)\*`"" Start-Process -FilePath "7z" -ArgumentList $ArgumentList -Wait -NoNewWindow } else { Write-host "in else " -f 'white' -b 'red' -n; write-host ([char]0xA0) ##cmD /c PAUSE $Folder = Get-Item $Folder $newfilename = "$(Get-Date -UFormat "%s")~$env:COMPUTERNAME~$env:USERNAME~ROOTC~$($folder.name).7z" $ArgumentList = "a -t7z -v4000m -m0=LZMA2:d64k:fb32 -ms=8m -mmt=30 -mx=1 -- `"$("$backuplocation\$newfilename")`" `"$($Folder.FullName)\*`"" Start-Process -FilePath "7z" -ArgumentList $ArgumentList -Wait -NoNewWindow } } function Get-RegHive { [CmdletBinding()] param ( [string]$backuplocation, [string]$key ) if (-not $backuplocation) { $backuplocation = Show-FolderBrowserDialog -Description "Select Backup Location" <# Action to perform if the condition is true #> } if (-not $backuplocation) { break } Start-Process -FilePath "reg" -ArgumentList "export $("$key $backuplocation\$($key.Split('\')[-1]).reg")" -Wait -PassThru -NoNewWindow } function Set-RegHive { [CmdletBinding()] param ( [string]$backuplocation ) if (-not $backuplocation) { $backuplocation = Show-FolderBrowserDialog -Description "Select Backup Location" <# Action to perform if the condition is true #> } if (-not $backuplocation) { break } if (Test-Path -Path $($backuplocation + "\ALLreg.reg")) { Start-Process -FilePath "reg" -ArgumentList "import $($backuplocation + "\ALLreg.reg")" -Wait -PassThru -NoNewWindow } Start-Process -FilePath "reg" -ArgumentList "import $($backuplocation + "\ALLreg.reg")" -Wait -PassThru -NoNewWindow } function New-IsoFile { [CmdletBinding(DefaultParameterSetName='Source')]Param( [parameter(Position=1,Mandatory=$true,ValueFromPipeline=$true, ParameterSetName='Source')]$Source, [parameter(Position=2)][string]$Path = "$env:temp\$((Get-Date).ToString('yyyyMMdd-HHmmss.ffff')).iso", [ValidateScript({Test-Path -LiteralPath $_ -PathType Leaf})][string]$BootFile = $null, [ValidateSet('CDR','CDRW','DVDRAM','DVDPLUSR','DVDPLUSRW','DVDPLUSR_DUALLAYER','DVDDASHR','DVDDASHRW','DVDDASHR_DUALLAYER','DISK','DVDPLUSRW_DUALLAYER','BDR','BDRE')][string] $Media = 'DVDPLUSRW_DUALLAYER', [string]$Title = (Get-Date).ToString("yyyyMMdd-HHmmss.ffff"), [switch]$Force, [parameter(ParameterSetName='Clipboard')][switch]$FromClipboard ) Begin { ($cp = new-object System.CodeDom.Compiler.CompilerParameters).CompilerOptions = '/unsafe' if (!('ISOFile' -as [type])) { Add-Type -CompilerOptions "/unsafe" -TypeDefinition @' public class ISOFile { public unsafe static void Create(string Path, object Stream, int BlockSize, int TotalBlocks) { int bytes = 0; byte[] buf = new byte[BlockSize]; var ptr = (System.IntPtr)(&bytes); var o = System.IO.File.OpenWrite(Path); var i = Stream as System.Runtime.InteropServices.ComTypes.IStream; if (o != null) { while (TotalBlocks-- > 0) { i.Read(buf, BlockSize, ptr); o.Write(buf, 0, bytes); } o.Flush(); o.Close(); } } } '@ } if ($BootFile) { if('BDR','BDRE' -contains $Media) { Write-Warning "Bootable image doesn't seem to work with media type $Media" } ($Stream = New-Object -ComObject ADODB.Stream -Property @{Type=1}).Open() # adFileTypeBinary $Stream.LoadFromFile((Get-Item -LiteralPath $BootFile).Fullname) ($Boot = New-Object -ComObject IMAPI2FS.BootOptions).AssignBootImage($Stream) } $MediaType = @('UNKNOWN','CDROM','CDR','CDRW','DVDROM','DVDRAM','DVDPLUSR','DVDPLUSRW','DVDPLUSR_DUALLAYER','DVDDASHR','DVDDASHRW','DVDDASHR_DUALLAYER','DISK','DVDPLUSRW_DUALLAYER','HDDVDROM','HDDVDR','HDDVDRAM','BDROM','BDR','BDRE') Write-Verbose -Message "Selected media type is $Media with value $($MediaType.IndexOf($Media))" ($Image = New-Object -com IMAPI2FS.MsftFileSystemImage -Property @{VolumeName=$Title}).ChooseImageDefaultsForMediaType($MediaType.IndexOf($Media)) if (!($Target = New-Item -Path $Path -ItemType File -Force:$Force -ErrorAction SilentlyContinue)) { Write-Error -Message "Cannot create file $Path. Use -Force parameter to overwrite if the target file already exists."; break } } Process { if($FromClipboard) { if($PSVersionTable.PSVersion.Major -lt 5) { Write-Error -Message 'The -FromClipboard parameter is only supported on PowerShell v5 or higher'; break } $Source = Get-Clipboard -Format FileDropList } foreach($item in $Source) { if($item -isnot [System.IO.FileInfo] -and $item -isnot [System.IO.DirectoryInfo]) { $item = Get-Item -LiteralPath $item } if($item) { Write-Verbose -Message "Adding item to the target image: $($item.FullName)" try { $Image.Root.AddTree($item.FullName, $true) } catch { Write-Error -Message ($_.Exception.Message.Trim() + ' Try a different media type.') } } } } End { if ($Boot) { $Image.BootImageOptions=$Boot } $Result = $Image.CreateResultImage() [ISOFile]::Create($Target.FullName,$Result.ImageStream,$Result.BlockSize,$Result.TotalBlocks) Write-Verbose -Message "Target image ($($Target.FullName)) has been created" $Target } } function Set-w11basic { Set-Activation Install-Choco (New-Object System.Net.WebClient).DownloadFile("https://t0m.pw/BasicChoco", "$env:TEMP\packages.config") Choco install "$env:TEMP\packages.config" (New-Object System.Net.WebClient).DownloadFile("https://t0m.pw/shutup10", "$env:TEMP\ooshutup10.cfg") OOSU10 "$env:TEMP\ooshutup10.cfg" /quiet (New-Object System.Net.WebClient).DownloadFile("https://t0m.pw/ExplorerPatcher", "$env:TEMP\ExplorerPatcher.reg") (New-Object System.Net.WebClient).DownloadFile("https://github.com/valinet/ExplorerPatcher/releases/latest/download/ep_setup.exe", "$env:TEMP\ep_setup.exe") Start-Process -FilePath "$env:TEMP\ep_setup.exe" -Wait Start-Sleep -Seconds 5 reg import "$env:TEMP\ExplorerPatcher.reg" Start-Process -FilePath "C:\Windows\Resources\Themes\themeA.theme" -Wait Set-ItemProperty -Path "HKLM:\SYSTEM\CurrentControlSet\Services\LanmanWorkstation\Parameters\" -Name "AllowInsecureGuestAuth" -Value 1 Copy-Item -Path "$env:TEMP\ExplorerPatcher.reg" -Destination "$env:USERPROFILE\Desktop\ImportMeIntoExplorerPatcher.reg" 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 "$env:ProgramFiles\Google\Chrome\Application\chrome.exe") { &$PSScriptRoot\tom42-syspin.exe "$env:ProgramFiles\Google\Chrome\Application\chrome.exe"} } function Set-w10basic { Set-Activation Install-Choco (New-Object System.Net.WebClient).DownloadFile("https://t0m.pw/BasicChoco", "$env:TEMP\packages.config") Choco install "$env:TEMP\packages.config" Import-Module $env:ChocolateyInstall\helpers\chocolateyProfile.psm1 refreshenv (New-Object System.Net.WebClient).DownloadFile("https://t0m.pw/shutup10", "$env:TEMP\ooshutup10.cfg") OOSU10 "$env:TEMP\ooshutup10.cfg" /quiet Set-ItemProperty -Path "HKLM:\SYSTEM\CurrentControlSet\Services\LanmanWorkstation\Parameters\" -Name "AllowInsecureGuestAuth" -Value 1 $unpin_taskbar_apps = "Microsoft Store", "Microsoft Edge", "Mail" Foreach ($thisapp in $unpin_taskbar_apps) {((New-Object -Com Shell.Application).NameSpace('shell:::{4234d49b-0245-4df3-b780-3893943456e1}').Items() | Where-Object { $_.Name -eq $thisapp }).Verbs() | Where-Object { $_.Name.replace('&', '') -match 'Unpin from taskbar' } | ForEach-Object { $_.DoIt(); $exec = $true }} import-Module -Name "c:\ProgramData\Boxstarter\Boxstarter.Chocolatey" Set-WindowsExplorerOptions -EnableShowHiddenFilesFoldersDrives -EnableShowProtectedOSFiles -EnableShowFileExtensions -EnableShowFullPathInTitleBar -EnableShowRecentFilesInQuickAccess -EnableShowFrequentFoldersInQuickAccess Set-BoxstarterTaskbarOptions -UnLock Set-BoxstarterTaskbarOptions -Size "Small" -DisableSearchBox -Combine Never Set-ItemProperty -Path "HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Feeds" -Name "ShellFeedsTaskbarViewMode" -Value 2 -Force Set-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced" -Name "ShowTaskViewButton" -Value 0 -Force Set-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced" -Name "ShowSecondsInSystemClock" -Value 1 -Force choco uninstall Boxstarter --remove-dependencies 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 "HKLM:\SOFTWARE\Mozilla\Mozilla Firefox") { &$PSScriptRoot\tom42-SetDefaultBrowser.exe HKLM Firefox-308046B0AF4A39CB } if (Test-Path "$env:ProgramFiles\Google\Chrome\Application\chrome.exe") { &$PSScriptRoot\tom42-syspin.exe "$env:ProgramFiles\Google\Chrome\Application\chrome.exe"} } |