## ToDo: ## Download function | to install function ## Office begone may need passthru wait ## mikedirstat #Vars #$ipregex = "^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$" $DellID = "l763eea921e5b44e4da96d4ab1e9225082" #old l7cf3c7bac338148f5a9bf149275ea3aee $DellSecret = "b81b5b095e0546b6a6db5594c4fc4a7d" #old 7b9743c25402415f91b36a388c6d9ec9 Add-Type -Assembly 'System.Drawing' Add-Type -A 'System.IO.Compression.FileSystem' Function clx($SaveRows) { If ($SaveRows) { [System.Console]::SetWindowPosition(0,[System.Console]::CursorTop-($SaveRows+1)) } Else { [System.Console]::SetWindowPosition(0,[System.Console]::CursorTop) } } function DrawMenu { param ($menuItems, $menuPosition, $Multiselect, $selection) $l = $menuItems.length for ($i = 0; $i -le $l;$i++) { if ($menuItems[$i] -ne $null){ $item = $menuItems[$i] #if ($item[0] -eq "@"){ $item = $item.trim("@") if ($Multiselect) { if ($selection -contains $i){ $item = '[x] ' + $item } else { $item = '[ ] ' + $item } } if ($i -eq $menuPosition) { Write-Host "> $($item)" -ForegroundColor Green } else { Write-Host " $($item)" } } } } function Toggle-Selection { param ($pos, [array]$selection) if ($selection -contains $pos){ $result = $selection | where {$_ -ne $pos} } else { $selection += $pos $result = $selection } $result } function Menu { param ([array]$menuItems, [switch]$ReturnIndex=$false, [switch]$Multiselect) $vkeycode = 0 $pos = 0 $selection = @() ################# $headers = @() $l = $menuItems.length for ($i = 0; $i -le $l;$i++) { if ($menuItems[$i] -ne $null){ $item = $menuItems[$i] if ($item[0] -eq "@"){$headers += 1} else {$headers += 0} } } #write-host $headers ################# $cur_pos = [System.Console]::CursorTop [console]::CursorVisible=$false #prevents cursor flickering if ($menuItems.Length -gt 0) { DrawMenu $menuItems $pos $Multiselect $selection While ($vkeycode -ne 13 -and $vkeycode -ne 27) { $press = $host.ui.rawui.readkey("NoEcho,IncludeKeyDown") $vkeycode = $press.virtualkeycode If ($vkeycode -eq 38 -or $press.Character -eq 'k') {$pos--} If ($vkeycode -eq 40 -or $press.Character -eq 'j') {$pos++} If ($press.Character -eq ' ') { $selection = Toggle-Selection $pos $selection } if ($pos -lt 0) {$pos = 0} If ($vkeycode -eq 27) {$pos = $null } if ($pos -ge $menuItems.length) {$pos = $menuItems.length -1} if ($vkeycode -ne 27) { [System.Console]::SetCursorPosition(0,$cur_pos) DrawMenu $menuItems $pos $Multiselect $selection } if ($headers[$pos] -eq 1) {$vkeycode = $null} } } else { $pos = $null } [console]::CursorVisible=$true if ($ReturnIndex -eq $false -and $pos -ne $null) { if ($Multiselect){ return $menuItems[$selection] } else { return $menuItems[$pos] } } else { if ($Multiselect){ return $selection } else { return $pos } } } function Write-Color { <# .SYNOPSIS Write-Color is a wrapper around Write-Host. It provides: - Easy manipulation of colors, - Logging output to file (log) - Nice formatting options out of the box. .DESCRIPTION Author: przemyslaw.klys at evotec.pl Project website: https://evotec.xyz/hub/scripts/write-color-ps1/ Project support: https://github.com/EvotecIT/PSWriteColor Original idea: Josh (https://stackoverflow.com/users/81769/josh) .EXAMPLE Write-Color -Text "Red ", "Green ", "Yellow " -Color Red,Green,Yellow .EXAMPLE Write-Color -Text "This is text in Green ", "followed by red ", "and then we have Magenta... ", "isn't it fun? ", "Here goes DarkCyan" -Color Green,Red,Magenta,White,DarkCyan .EXAMPLE Write-Color -Text "This is text in Green ", "followed by red ", "and then we have Magenta... ", "isn't it fun? ", "Here goes DarkCyan" -Color Green,Red,Magenta,White,DarkCyan -StartTab 3 -LinesBefore 1 -LinesAfter 1 .EXAMPLE Write-Color "1. ", "Option 1" -Color Yellow, Green Write-Color "2. ", "Option 2" -Color Yellow, Green Write-Color "3. ", "Option 3" -Color Yellow, Green Write-Color "4. ", "Option 4" -Color Yellow, Green Write-Color "9. ", "Press 9 to exit" -Color Yellow, Gray -LinesBefore 1 .EXAMPLE Write-Color -LinesBefore 2 -Text "This little ","message is ", "written to log ", "file as well." ` -Color Yellow, White, Green, Red, Red -LogFile "C:\testing.txt" -TimeFormat "yyyy-MM-dd HH:mm:ss" Write-Color -Text "This can get ","handy if ", "want to display things, and log actions to file ", "at the same time." ` -Color Yellow, White, Green, Red, Red -LogFile "C:\testing.txt" .EXAMPLE # Added in 0.5 Write-Color -T "My text", " is ", "all colorful" -C Yellow, Red, Green -B Green, Green, Yellow wc -t "my text" -c yellow -b green wc -text "my text" -c red .NOTES Additional Notes: - TimeFormat https://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx #> [alias('Write-Colour')] [CmdletBinding()] param ( [alias ('T')] [String[]]$Text, [alias ('C', 'ForegroundColor', 'FGC')] [ConsoleColor[]]$Color = [ConsoleColor]::White, [alias ('B', 'BGC')] [ConsoleColor[]]$BackGroundColor = $null, [alias ('Indent')][int] $StartTab = 0, [int] $LinesBefore = 0, [int] $LinesAfter = 0, [int] $StartSpaces = 0, [alias ('L')] [string] $LogFile = '', [Alias('DateFormat', 'TimeFormat')][string] $DateTimeFormat = 'yyyy-MM-dd HH:mm:ss', [alias ('LogTimeStamp')][bool] $LogTime = $true, [ValidateSet('unknown', 'string', 'unicode', 'bigendianunicode', 'utf8', 'utf7', 'utf32', 'ascii', 'default', 'oem')][string]$Encoding = 'Unicode', [switch] $ShowTime, [switch] $NoNewLine ) $DefaultColor = $Color[0] if ($null -ne $BackGroundColor -and $BackGroundColor.Count -ne $Color.Count) { Write-Error "Colors, BackGroundColors parameters count doesn't match. Terminated." return } #if ($Text.Count -eq 0) { return } if ($LinesBefore -ne 0) { for ($i = 0; $i -lt $LinesBefore; $i++) { Write-Host -Object "`n" -NoNewline } } # Add empty line before if ($StartTab -ne 0) { for ($i = 0; $i -lt $StartTab; $i++) { Write-Host -Object "`t" -NoNewLine } } # Add TABS before text if ($StartSpaces -ne 0) { for ($i = 0; $i -lt $StartSpaces; $i++) { Write-Host -Object ' ' -NoNewLine } } # Add SPACES before text if ($ShowTime) { Write-Host -Object "[$([datetime]::Now.ToString($DateTimeFormat))]" -NoNewline } # Add Time before output if ($Text.Count -ne 0) { if ($Color.Count -ge $Text.Count) { # the real deal coloring if ($null -eq $BackGroundColor) { for ($i = 0; $i -lt $Text.Length; $i++) { Write-Host -Object $Text[$i] -ForegroundColor $Color[$i] -NoNewLine } } else { for ($i = 0; $i -lt $Text.Length; $i++) { Write-Host -Object $Text[$i] -ForegroundColor $Color[$i] -BackgroundColor $BackGroundColor[$i] -NoNewLine } } } else { if ($null -eq $BackGroundColor) { for ($i = 0; $i -lt $Color.Length ; $i++) { Write-Host -Object $Text[$i] -ForegroundColor $Color[$i] -NoNewLine } for ($i = $Color.Length; $i -lt $Text.Length; $i++) { Write-Host -Object $Text[$i] -ForegroundColor $DefaultColor -NoNewLine } } else { for ($i = 0; $i -lt $Color.Length ; $i++) { Write-Host -Object $Text[$i] -ForegroundColor $Color[$i] -BackgroundColor $BackGroundColor[$i] -NoNewLine } for ($i = $Color.Length; $i -lt $Text.Length; $i++) { Write-Host -Object $Text[$i] -ForegroundColor $DefaultColor -BackgroundColor $BackGroundColor[0] -NoNewLine } } } } if ($NoNewLine -eq $true) { Write-Host -NoNewline } else { Write-Host } # Support for no new line if ($LinesAfter -ne 0) { for ($i = 0; $i -lt $LinesAfter; $i++) { Write-Host -Object "`n" -NoNewline } } # Add empty line after if ($Text.Count -and $LogFile) { # Save to file $TextToFile = "" for ($i = 0; $i -lt $Text.Length; $i++) { $TextToFile += $Text[$i] } try { if ($LogTime) { "[$([datetime]::Now.ToString($DateTimeFormat))]$TextToFile" | Out-File -FilePath $LogFile -Encoding $Encoding -Append -ErrorAction Stop } else { "$TextToFile" | Out-File -FilePath $LogFile -Encoding $Encoding -Append -ErrorAction Stop } } catch { $PSCmdlet.WriteError($_) } } } function ConvertTo-Icon { <# .Synopsis Converts image to icons .Description Converts an image to an icon .Example ConvertTo-Icon -File .\Logo.png -OutputFile .\Favicon.ico #> [CmdletBinding()] param( [Parameter(Mandatory=$true, Position=0,ValueFromPipelineByPropertyName=$true)] [Alias('Fullname')] [string]$File, [Parameter(Position=1, ValueFromPipelineByPropertyName=$true)] [string]$OutputFile ) begin { Add-Type -AssemblyName System.Windows.Forms, System.Drawing } process { #region Load Icon $resolvedFile = $ExecutionContext.SessionState.Path.GetResolvedPSPathFromPSPath($file) if (-not $resolvedFile) { return } $inputBitmap = [Drawing.Image]::FromFile($resolvedFile) $width = $inputBitmap.Width $height = $inputBitmap.Height $size = New-Object Drawing.Size $width, $height $newBitmap = New-Object Drawing.Bitmap $inputBitmap, $size #endregion Load Icon #region Save Icon $memoryStream = New-Object System.IO.MemoryStream $newBitmap.Save($memoryStream, [System.Drawing.Imaging.ImageFormat]::Png) $resolvedOutputFile = $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($outputFile) $output = [IO.File]::Create("$resolvedOutputFile") $iconWriter = New-Object System.IO.BinaryWriter($output) # 0-1 reserved, 0 $iconWriter.Write([byte]0) $iconWriter.Write([byte]0) # 2-3 image type, 1 = icon, 2 = cursor $iconWriter.Write([int16]1); # 4-5 number of images $iconWriter.Write([int16]1); # image entry 1 # 0 image width $iconWriter.Write([byte]$width); # 1 image height $iconWriter.Write([byte]$height); # 2 number of colors $iconWriter.Write([byte]0); # 3 reserved $iconWriter.Write([byte]0); # 4-5 color planes $iconWriter.Write([int16]0); # 6-7 bits per pixel $iconWriter.Write([int16]32); # 8-11 size of image data $iconWriter.Write([int]$memoryStream.Length); # 12-15 offset of image data $iconWriter.Write([int](6 + 16)); # write image data # png data must contain the whole png data file $iconWriter.Write($memoryStream.ToArray()); $iconWriter.Flush(); $output.Close() #endregion Save Icon #region Cleanup $memoryStream.Dispose() $newBitmap.Dispose() $inputBitmap.Dispose() #endregion Cleanup } } function Create-Shortcut { [CmdletBinding()] [Alias()] Param ( [Parameter( Mandatory=$true, ValueFromPipelineByPropertyName=$true, Position=0)] $ShortcutFile, [Parameter( Mandatory=$true, ValueFromPipelineByPropertyName=$true, Position=1)] $TargetPath, [Parameter( Mandatory=$false, ValueFromPipelineByPropertyName=$true, ParameterSetName="URL")] [ValidateNotNull()] [ValidateNotNullOrEmpty()] [ValidatePattern("^((?:ht|f)tp(?:s?)\:\/\/)?([0-9a-zA-Z][-.\w]*\.)([\w\-]*)(\.[0-9a-zA-Z]*)(:(?:6553[0-5]|655[0-2]\d|65[0-4]\d\d|6[0-4]\d{3}|[1-5]\d{4}|[1-9]\d{0,3}))?([\w\-\.\?\,\'\/\\\+&%\$#]*\/)?([\w\-. ]*\.ico)$")] [Alias("iurl")] $IconURL, [Parameter( Mandatory=$false, ValueFromPipelineByPropertyName=$true, ParameterSetName="Path")] [ValidateNotNull()] [ValidateNotNullOrEmpty()] [ValidatePattern('^([a-zA-Z]\:|\\\\[^\/\\:*?"<>|]+\\[^\/\\:*?"<>|]+)(\\[^\/\\:*?"<>|]+)+(\.ico)$')] [Alias("ico")] $IconPath ) Begin { if($IconURL){ $Path = "C:\ProgramData\BLTS" $IcoName = (Split-Path $ShortcutFile -Leaf).Split(".")[0] New-Item -ItemType Directory -Force -Path "$Path\icons" Invoke-WebRequest "$IconURL" -OutFile "$($env:TEMP)\$IcoName.ico" ConvertTo-Icon "$($env:TEMP)\$IcoName.ico" "$Path\icons\$IcoName.ico" #Start-Sleep 2 if(!(Test-Path "$Path\icons\$IcoName.ico")){return "Couldn't get Favicon"} $IconLocation = "$Path\icons\$IcoName.ico" } if($IconPath){ $IconLocation = $IconPath } $WScriptShell = New-Object -ComObject WScript.Shell } Process { $Shortcut = $WScriptShell.CreateShortcut($ShortcutFile) $Shortcut.TargetPath = $Targetpath if($IconLocation){ $Shortcut.IconLocation = $IconLocation} $Shortcut.Save() } End { } } function New-SWRandomPassword { <# .Synopsis Generates one or more complex passwords designed to fulfill the requirements for Active Directory .DESCRIPTION Generates one or more complex passwords designed to fulfill the requirements for Active Directory .EXAMPLE New-SWRandomPassword C&3SX6Kn Will generate one password with a length between 8 and 12 chars. .EXAMPLE New-SWRandomPassword -MinPasswordLength 8 -MaxPasswordLength 12 -Count 4 7d&5cnaB !Bh776T"Fw 9"C"RxKcY %mtM7#9LQ9h Will generate four passwords, each with a length of between 8 and 12 chars. .EXAMPLE New-SWRandomPassword -InputStrings abc, ABC, 123 -PasswordLength 4 3ABa Generates a password with a length of 4 containing atleast one char from each InputString .EXAMPLE New-SWRandomPassword -InputStrings abc, ABC, 123 -PasswordLength 4 -FirstChar abcdefghijkmnpqrstuvwxyzABCEFGHJKLMNPQRSTUVWXYZ 3ABa Generates a password with a length of 4 containing atleast one char from each InputString that will start with a letter from the string specified with the parameter FirstChar .OUTPUTS [String] .NOTES Written by Simon Wåhlin, blog.simonw.se I take no responsibility for any issues caused by this script. .FUNCTIONALITY Generates random passwords .LINK http://blog.simonw.se/powershell-generating-random-password-for-active-directory/ #> [CmdletBinding(DefaultParameterSetName='FixedLength',ConfirmImpact='None')] [OutputType([String])] Param ( # Specifies minimum password length [Parameter(Mandatory=$false, ParameterSetName='RandomLength')] [ValidateScript({$_ -gt 0})] [Alias('Min')] [int]$MinPasswordLength = 8, # Specifies maximum password length [Parameter(Mandatory=$false, ParameterSetName='RandomLength')] [ValidateScript({ if($_ -ge $MinPasswordLength){$true} else{Throw 'Max value cannot be lesser than min value.'}})] [Alias('Max')] [int]$MaxPasswordLength = 12, # Specifies a fixed password length [Parameter(Mandatory=$false, ParameterSetName='FixedLength')] [ValidateRange(1,2147483647)] [int]$PasswordLength = 8, # Specifies an array of strings containing charactergroups from which the password will be generated. # At least one char from each group (string) will be used. [String[]]$InputStrings = @('abcdefghijkmnpqrstuvwxyz', 'ABCEFGHJKLMNPQRSTUVWXYZ', '23456789'), # Specifies a string containing a character group from which the first character in the password will be generated. # Useful for systems which requires first char in password to be alphabetic. [String] $FirstChar, # Specifies number of passwords to generate. [ValidateRange(1,2147483647)] [int]$Count = 1 ) Begin { Function Get-Seed{ # Generate a seed for randomization $RandomBytes = New-Object -TypeName 'System.Byte[]' 4 $Random = New-Object -TypeName 'System.Security.Cryptography.RNGCryptoServiceProvider' $Random.GetBytes($RandomBytes) [BitConverter]::ToUInt32($RandomBytes, 0) } } Process { For($iteration = 1;$iteration -le $Count; $iteration++){ $Password = @{} # Create char arrays containing groups of possible chars [char[][]]$CharGroups = $InputStrings # Create char array containing all chars $AllChars = $CharGroups | ForEach-Object {[Char[]]$_} # Set password length if($PSCmdlet.ParameterSetName -eq 'RandomLength') { if($MinPasswordLength -eq $MaxPasswordLength) { # If password length is set, use set length $PasswordLength = $MinPasswordLength } else { # Otherwise randomize password length $PasswordLength = ((Get-Seed) % ($MaxPasswordLength + 1 - $MinPasswordLength)) + $MinPasswordLength } } # If FirstChar is defined, randomize first char in password from that string. if($PSBoundParameters.ContainsKey('FirstChar')){ $Password.Add(0,$FirstChar[((Get-Seed) % $FirstChar.Length)]) } # Randomize one char from each group Foreach($Group in $CharGroups) { if($Password.Count -lt $PasswordLength) { $Index = Get-Seed While ($Password.ContainsKey($Index)){ $Index = Get-Seed } $Password.Add($Index,$Group[((Get-Seed) % $Group.Count)]) } } # Fill out with chars from $AllChars for($i=$Password.Count;$i -lt $PasswordLength;$i++) { $Index = Get-Seed While ($Password.ContainsKey($Index)){ $Index = Get-Seed } $Password.Add($Index,$AllChars[((Get-Seed) % $AllChars.Count)]) } Write-Output -InputObject $(-join ($Password.GetEnumerator() | Sort-Object -Property Name | Select-Object -ExpandProperty Value)) } } #CITATION Above function came from: https://gallery.technet.microsoft.com/scriptcenter/Generate-a-random-and-5c879ed5 }# function Get-Systeminfo{ $date = Get-Date -Format "MM-dd HH:mm" $cpuTime = ((Get-Counter '\Processor(_Total)\% Processor Time').CounterSamples.CookedValue).ToString("#,0.00") $totalRam = ((Get-CimInstance Win32_PhysicalMemory | Measure-Object -Property capacity -Sum).Sum) $availMem = ((Get-Counter '\Memory\Available MBytes').CounterSamples.CookedValue) $availMemNeat = $availMem.ToString("N0") $totalRamNeat = ($totalRam/1048576).ToString("N0") $RamPercent = (104857600 * $availMem / $totalRam).ToString("#,0.0") $serial= (Get-Ciminstance Win32_BIOS).serialnumber Write-host "Computer Name: $env:COMPUTERNAME Username: $env:username Profile: $env:userprofile Serial: $serial CPU Usage: $cpuTime% Memory: $($availMemNeat)MB free of $($totalRamNeat)MB ($RamPercent% free)" }# function Connect-O365($credparam) { if (!$credparam) {$UserCredential = Get-Credential -ErrorAction SilentlyContinue} Else {$UserCredential = $credparam} if (!$UserCredential) {write-host No Credential Given; break} Import-PSSession (New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://outlook.office365.com/powershell-liveid/ -Credential $UserCredential -Authentication Basic -AllowRedirection) } function Create-RDP { param( [string]$Path, [string]$Server, [string]$Gateway ) if (!$server) {write-host "Server is required, duh." -ForegroundColor Yellow; break} if (!$Path) {$Path = "temp.rdp"} $content = "screen mode id:i:1 desktopwidth:i:1024 desktopheight:i:768 session bpp:i:16 compression:i:1 keyboardhook:i:2 displayconnectionbar:i:1 disable wallpaper:i:1 disable full window drag:i:1 allow desktop composition:i:0 allow font smoothing:i:0 disable menu anims:i:1 disable themes:i:0 disable cursor setting:i:0 bitmapcachepersistenable:i:1 full address:s:$server audiomode:i:0 redirectprinters:i:1 redirectcomports:i:0 redirectsmartcards:i:1 redirectclipboard:i:1 redirectposdevices:i:0 autoreconnection enabled:i:1 authentication level:i:2 prompt for credentials:i:0 negotiate security layer:i:1 remoteapplicationmode:i:0 alternate shell:s: shell working directory:s: gatewayusagemethod:i:1 gatewaycredentialssource:i:4 gatewayprofileusagemethod:i:1 promptcredentialonce:i:1 drivestoredirect:s: use multimon:i:0 audiocapturemode:i:0 videoplaybackmode:i:1 connection type:i:7 networkautodetect:i:1 bandwidthautodetect:i:1 enableworkspacereconnect:i:0 gatewayhostname:s:$gateway gatewaybrokeringtype:i:0 use redirection server name:i:0 rdgiskdcproxy:i:0 kdcproxyname:s:" Set-Content -Path $Path -Value $content -Force } function Connect-RDP { param( [string]$Server, [string]$Gateway, [string]$Password ) Create-RDP -Path "$env:temp\temp.rdp" -Server $server -Gateway $Gateway -Password $Password mstsc.exe "$env:temp\temp.rdp" } function Edit-Hosts{ start-process notepad.exe -verb runas -argumentlist "C:\Windows\System32\drivers\etc\hosts" }# function Add-NetworkPrinter{ [CmdletBinding(DefaultParameterSetName='Parameter Set 1', SupportsShouldProcess=$true, PositionalBinding=$false, <#HelpUri = 'http://www.microsoft.com/',#> ConfirmImpact='Medium')] [Alias()] [OutputType([String])] Param ( # Param1 help description [Parameter(Mandatory=$False, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true, ValueFromRemainingArguments=$false, Position=0, ParameterSetName='Parameter Set 1')] [ValidateNotNull()] [ValidateNotNullOrEmpty()] [Alias("inf")] [string] $INFFile, # Param2 help description [Parameter(Mandatory=$false, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true, ValueFromRemainingArguments=$false, Position=1, ParameterSetName='Parameter Set 1')] [ValidateNotNull()] [ValidateNotNullOrEmpty()] [Alias("Zip")] [string] $DriverPackage, # Param3 help description [Parameter(Mandatory=$true, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true, ValueFromRemainingArguments=$false, Position=2, ParameterSetName='Parameter Set 1')] [ValidateNotNull()] [ValidateNotNullOrEmpty()] [Alias("driver")] [string] $DriverName, # Param4 help description [Parameter(Mandatory=$true, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true, ValueFromRemainingArguments=$false, Position=3, ParameterSetName='Parameter Set 1')] [ValidateNotNull()] [ValidateNotNullOrEmpty()] [ValidatePattern("^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$")] [Alias("ip")] [String] $PrinterHostAddress, # Param5 help description [Parameter(Mandatory=$False, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true, ValueFromRemainingArguments=$false, Position=4, ParameterSetName='Parameter Set 1')] [ValidateNotNull()] [ValidateNotNullOrEmpty()] [Alias("Name")] [string] $PrinterName ) Begin { $Path = "C:\AEMDeploy" if (!$DriverPackage) {$DriverPackage = $($DriverName -replace(" ","_")) + ".zip"} if (!$PrinterName) {$PrinterName = $Drivername} Write-Verbose "Path: $Path" } Process { if ($pscmdlet.ShouldProcess("$DriverPackage", "Copy and extract to temp location")) { #Copy-Item "$DriverPackage" -Destination (new-item -type directory -force ($Path)) -force Add-Type -A 'System.IO.Compression.FileSystem' if(Test-Path ("$path\$Drivername")){Remove-Item "$path\$Drivername" -Recurse} [IO.Compression.ZipFile]::ExtractToDirectory("$(Get-Location)\$DriverPackage", "$path\$DriverName") if (!$INFFile){ Write-Verbose "INF not defined" if ($(Get-ChildItem "$Path\$DriverName\*.inf").count -ne 1){ Write-Verbose "Error: None or more than one INF file. INF to use can't be determined and must be specified." Exit } else{ $INFFile = $(Get-ChildItem "$Path\$DriverName\*.inf").name Write-Verbose "Only one INF. `$INFFile set to $INFFile" } } } if ($pscmdlet.ShouldProcess("$INFFile", "Installing INF")) {& {pnputil.exe -i -a "$Path\$DriverName\$INFFile"}} if ($pscmdlet.ShouldProcess("$DriverName", "Installing driver")) {& {add-printerdriver -name "$DriverName"}} if ($pscmdlet.ShouldProcess("$PrinterHostAddress", "Creating printer port")) {& {Add-PrinterPort -Name "BLTS_$PrinterHostAddress" -PrinterHostAddress "$PrinterHostAddress"}} if ($pscmdlet.ShouldProcess("$PrinterName", "Creating printer")) {& {Add-Printer -Name "$PrinterName" -DriverName "$DriverName" -PortName "BLTS_$PrinterHostAddress"}} } End { Write-Verbose "Ending variables: $INFFile | $DriverPackage | $DriverName | $PrinterHostAddress | $PrinterName" } } <# function Get-DiskNumber{ param( [parameter(Position=0, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)] [ValidateNotNullOrEmpty()] [string]$DriveLetter ) return ((gwmi win32_logicaldisk | ?{$_.DeviceID -eq "$DriveLetter"}).getrelated("win32_diskpartition")).diskindex } function Get-DiskType{ param( [parameter(Position=0, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)] [ValidateNotNullOrEmpty()] [int]$DiskNumber ) # Param($DiskNumber) return (gwmi -Class MSFT_PhysicalDisk -Namespace root\Microsoft\Windows\Storage | ?{$_.DeviceID -eq "$DiskNumber"} | Select @{ name="MediaType"; expression={ switch ($_.MediaType) { 3 {"HDD"} 4 {"SSD"} } } }).mediatype } $type = Get-DiskNumber C: | Get-DiskType #> <#function Get-FileInstallEXE{ [CmdletBinding( SupportsShouldProcess=$true, ConfirmImpact='Medium')] [Alias()] [OutputType([String])] Param ( # Param1 help description [Parameter(Mandatory=$True, ValueFromPipeline=$true, Position=0)] [string] $FileURL ) if(!$Path){$Path = $env:TEMP} $Installer = [System.IO.Path]::GetFileName("$FileURL") Invoke-WebRequest "$FileURL" -OutFile $Path\$Installer (Start-Process -FilePath $Path\$Installer -Args "/silent /install" -Verb RunAs -Wait).ExitCode Remove-Item $Path\$Installer } #> function Install-OfficeCTR{ Invoke-WebRequest "files.hink.link/OfficeSetupComponent.exe" -OutFile "$Env:Temp\setup.exe" Set-Location $env:Temp $ProductID = "O365BusinessRetail" if ($ProductID -eq "Other") {$ProductID = $env:CustomProductID} if (!$ProductID) {Write-Host "ProductID Required" ; exit 1} $configfile = "configuration.xml" if (!(Test-Path $configfile)) {New-Item $configfile} Clear-Content $configfile ##Begin Config file Base ($ConfigFileContents = ' ') ##End config file base $ConfigFileContents = $ConfigFileContents.Replace('InsertProdIDHere',$ProductID) Add-Content -Path $configfile -Value $ConfigFileContents .\setup.exe /configure $configfile } #untested function Install-Chrome{ $Installer = "chrome_installer.exe"; Invoke-WebRequest "http://dl.google.com/chrome/install/375.126/chrome_installer.exe" -OutFile $Path\$Installer $LastExit = (Start-Process -FilePath $Path\$Installer -Wait -Args "/silent /install" -PassThru).ExitCode Remove-Item $Path\$Installer Return $LastExit }# function Install-8x8{ $Installer = "VOD_6_0.msi"; Invoke-WebRequest "https://support.8x8.com/@api/deki/files/1947/VOD_6_0.msi" -OutFile "$Path\$Installer"; $LastExit = (Start-Process msiexec.exe -Wait -ArgumentList "/quiet /norestart /i `"$Path\$Installer`"" -PassThru).ExitCode Remove-Item $Path\$Installer Return $LastExit }# function Install-Foxit{ $Installer = "FoxitPhantomPDF90_enu_Setup.msi"; Invoke-WebRequest "http://cdn09.foxitsoftware.com/product/phantomPDF/desktop/win/9.0/FoxitPhantomPDF90_enu_Setup.msi" -OutFile "$Path\$Installer"; $LastExit = (Start-Process msiexec.exe -Wait -ArgumentList "/quiet /norestart /i `"$Path\$Installer`" keycode=`"97000-010S0-20G20-CSAKG-CC002-Q7P0P`"" -PassThru).ExitCode Remove-Item $Path\$Installer Return $LastExit }# function Install-FireFox{ $Installer = "firefox.exe"; Invoke-WebRequest "https://download.mozilla.org/?product=firefox-latest&os=win64&lang=en-US" -OutFile "$Path\$Installer"; $LastExit = (Start-Process $Path\$Installer -Wait -ArgumentList "/S" -PassThru).ExitCode Remove-Item $Path\$Installer Return $LastExit }# function Office-BeGone{ Get-AppxPackage -Name "*office*" -AllUsers | Remove-AppxPackage Get-AppXProvisionedPackage -Online | where DisplayName -like "*office*" | Remove-AppxProvisionedPackage -Online Get-AppxPackage -Name "*office*" -AllUsers | Remove-AppxPackage Get-AppXProvisionedPackage -Online | where DisplayName -like "*office*" | Remove-AppxProvisionedPackage -Online ### Maybe needs wait? #"C:\Program Files\Common Files\Microsoft Shared\ClickToRun\OfficeClickToRun.exe" scenario=install scenariosubtype=ARP sourcetype=None productstoremove=O365HomePremRetail.16_en-us_x-none culture=en-us version.16=16.0 DisplayLevel=False #timeout 180 #"C:\Program Files\Common Files\Microsoft Shared\ClickToRun\OfficeClickToRun.exe" scenario=install scenariosubtype=ARP sourcetype=None productstoremove=O365HomePremRetail.16_es-es_x-none culture=es-es version.16=16.0 DisplayLevel=False #timeout 180 #"C:\Program Files\Common Files\Microsoft Shared\ClickToRun\OfficeClickToRun.exe" scenario=install scenariosubtype=ARP sourcetype=None productstoremove=O365HomePremRetail.16_fr-fr_x-none culture=fr-fr version.16=16.0 DisplayLevel=False #timeout 180 }# function Set-PublicDesktopFullControl{ Write-Host "Setting permissions on public desktop to everyone" $Sharepath = "C:\users\public\desktop" $Acl = Get-ACL $SharePath $AccessRule= New-Object System.Security.AccessControl.FileSystemAccessRule("everyone","FullControl","ContainerInherit,Objectinherit","none","Allow") $Acl.AddAccessRule($AccessRule) Set-Acl $SharePath $Acl }# function Install-AdobeCC(){ Write-Host "Downloading and extracting Adobe CC" $aInstaller = "ACCCx4_7_0_400"; Invoke-WebRequest "http://ccmdl.adobe.com/AdobeProducts/KCCC/1/win32/ACCCx4_7_0_400.zip" -OutFile "$Path\$aInstaller.zip"; [IO.Compression.ZipFile]::ExtractToDirectory("$Path\$aInstaller.zip", "$Path\$aInstaller"); Write-Host "Installing Adobe CC - Please sign in when it opens. End all Adobe tasks in task manager once installed to continue." Start-Process -FilePath "$Path\$aInstaller\Set-up.exe" -Wait Write-Host "Done installing Adobe CC" }# Function EnableFileDeleteConfirm { Write-Output "Enabling file delete confirmation dialog..." If (!(Test-Path "HKCU:\Software\Microsoft\Windows\CurrentVersion\Policies\Explorer")) { New-Item -Path "HKCU:\Software\Microsoft\Windows\CurrentVersion\Policies\Explorer" | Out-Null } Set-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\CurrentVersion\Policies\Explorer" -Name "ConfirmFileDelete" -Type DWord -Value 1 }# Function HideTaskbarPeopleIcon { Write-Output "Hiding People icon..." If (!(Test-Path "HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced\People")) { New-Item -Path "HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced\People" | Out-Null } Set-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced\People" -Name "PeopleBand" -Type DWord -Value 0 }# Function Disable-LocalAdmins{ $localadmins = Get-LocalGroupMember -name administrators | ?{(Get-LocalUser -sid $_.sid).enabled -eq $true} $todisable = New-Object System.Collections.Generic.List[System.Object] foreach ($admin in $localadmins){ if ([System.Security.Principal.WindowsIdentity]::GetCurrent().Name -ne $admin.name) {$todisable.Add($admin)} } Write-Host "Current user is: $([System.Security.Principal.WindowsIdentity]::GetCurrent().Name)" Write-host "To disable: $todisable" Read-Host -Prompt "Press any key to continue or CTRL+C to quit" foreach($user in $todisable){ Disable-LocalUser -sid $user.sid } }# Function Detect-Laptop{ Param( [string]$computer = "localhost" ) $isLaptop = $false #The chassis is the physical container that houses the components of a computer. Check if the machine’s chasis type is 9.Laptop 10.Notebook 14.Sub-Notebook if(Get-WmiObject -Class win32_systemenclosure -ComputerName $computer | Where-Object { $_.chassistypes -eq 9 -or $_.chassistypes -eq 10 -or $_.chassistypes -eq 14}) { $isLaptop = $true } #Shows battery status , if true then the machine is a laptop. if(Get-WmiObject -Class win32_battery -ComputerName $computer) { $isLaptop = $true } $isLaptop } <# Rename-Computer -NewName "$((gwmi win32_bios).serialnumber)-$(@('DT','LT')[[bool]$(Detect-laptop)])" -Restart -Force#> function Get-DellComputerInfo{ [CmdletBinding()] [Alias()] [OutputType([string])] Param ( # Param1 help description [Parameter(Mandatory=$true, ValueFromPipelineByPropertyName=$true, Position=0)] $ServiceTag, [Switch] $Debugme ) <#Normal use: $Tags = @("hyg3t33") $tags | foreach{Get-DellComputerInfo $_ <#-Debugme #`>} #> $DellID = "l763eea921e5b44e4da96d4ab1e9225082" #old l7cf3c7bac338148f5a9bf149275ea3aee $DellSecret = "b81b5b095e0546b6a6db5594c4fc4a7d" #old 7b9743c25402415f91b36a388c6d9ec9 $TokenRequest = Invoke-WebRequest -Uri "https://apigtwb2c.us.dell.com/auth/oauth/v2/token" -method 'POST' -Body @{"grant_type"="client_credentials"; "client_id"="$DellID"; "client_secret"="$DellSecret"; "Content-Type"="application/x-www-form-urlencoded"} $token = (ConvertFrom-Json($TokenRequest.Content)).access_token $x = Invoke-WebRequest -Uri "https://apigtwb2c.us.dell.com/PROD/sbil/eapi/v5/asset-entitlement-components" -method 'GET' -Headers @{"Authorization"="Bearer $token"} -Body @{"servicetag"="$ServiceTag"} $x = ConvertFrom-Json($x.Content) if($Debugme){return $x.components | ?{$_.partQuantity -ge 1}} $mem = $x.components | ?{(($_.partDescription).split(","))[0] -eq "DIMM" } try{$mem = $mem.partDescription.Split(",")}catch{$mem = @('Unknown','Unknown')} $proc = $x.components | ?{(($_.partDescription).split(","))[0] -match "(PRC|Processor)" } if (!$proc){ $proc = $x.components | ?{(($_.partDescription).split(","))[0] -match "(ASSY)" } | ?{(($_.partDescription).split(","))[1] -match "(BASE)" } [System.Collections.ArrayList]$proc = $proc.partDescription.Split(",") $proc.RemoveAt(0) } else{ $proc = $($proc.partDescription.Split(",")) } $drive = $x.components | ?{(($_.partDescription).split(","))[0] -match "(SSDR|HD)" } try{$driveitempart = " $($drive.itemnumber)|$($drive.partnumber)" $drive = $drive.partDescription.Split(",")}catch{$drive=@('Unknown','Unknown')} #[string]$proc #[string]$mem #[string]$drive write-color -text $x.systemDescription -color White,Yellow write-color -text "Service Tag: ","$($x.serviceTag)"," | Ship Date: ","$($x.shipdate.Split("T")[0])" -color White,Yellow,White,Yellow write-color -text "Warranty: ","$($x.entitlements.startdate.Split("T")[0]) - $($x.entitlements.enddate.Split("T")[0])"," Type: ","$($x.entitlements.serviceleveldescription.Split(",")[1])" -color White,Yellow,white,Yellow write-color -text "Proc: ","$($proc[1]) $($proc[2]) $($proc[3])Ghz"," > $([string]$proc)" -color white,yellow,red write-color -text "MemorySize: ","$($mem[1]) | MemorySpeed=$($mem[2])"," > $([string]$mem)" -color white,yellow,red write-color -text "Storage: ","$($drive[1]) $($drive[0])"," > $([string]$drive)", "Item|Part - $driveitempart" -color white,yellow,red,yellow }# function List-Functions{ cls Write-Color 'Create-Shortcut',' -ShortcutFile ','"$($env:USERPROFILE)\Desktop\testlink.lnk"',' -TargetPath',' "C:\Windows\system32\notepad.exe" ','(Optional: ','-IconURL ','|',' -IconPath',') (','"https://www.reddit.com/favicon.ico" ','|',' "C:\temp\icon.ico"',')' -C Yellow, red, Green, red, green, gray, magenta, gray, magenta, gray, white, gray, white, gray Write-Color "Install-AdobeCC" -Color Yellow Write-Color "Install-FireFox" -Color Yellow Write-Color "Install-Foxit" -Color Yellow Write-Color "Install-8x8" -Color Yellow Write-Color "Install-Chrome" -Color Yellow Write-Color "Install-OfficeCTR" -Color Yellow Write-Color "Office-BeGone" -Color Yellow Write-Color "Set-PublicDesktopFullControl" -Color Yellow Write-Color "EnableFileDeleteConfirm" -Color Yellow Write-Color "HideTaskbarPeopleIcon" -Color Yellow Write-Color "Disable-LocalAdmins" -Color Yellow Write-Color "Detect-Laptop" -Color Yellow Write-Color "Get-DellComputerInfo" -Color Yellow Write-Color "Add-NetworkPrinter" -Color Yellow Write-Color "Edit-Hosts" -Color Yellow Write-Color "Connect-RDP" -Color Yellow Write-Color "Connect-O365" -Color Yellow Write-Color "Get-Systeminfo" -Color Yellow Write-Color "New-SWRandomPassword" -Color Yellow } switch(menu @("@Installs",#0 " Chrome",#1 " Firefox", " OfficeCTR",#2 " Foxit",#3 " 8x8",#4 " AdobeCC", "@Tools",#6 " Random Pass",#7 " System Info",#8 ADD " Dell Lookup", " Edit Hosts", " Public Desktop - Full Control", " Office removal", " Disable all other local admins", "@Tweaks",#9 " Hide 'People' Icon",#10 " Enable delete confirmation",#11 " List added functions"#12 ) -returnindex true) { ##0 1{Write-Host "Installing Chrome";Install-Chrome} 2{Write-Host "Installing Firefox";Install-FireFox} 3{Install-OfficeCTR} 4{Install-Foxit} 5{Install-8x8} 6{Install-AdobeCC} #6 8{New-SWRandomPassword} 9{Get-Systeminfo} 10{$x = Read-Host -Prompt "Service Tags, comma separated"; Get-DellComputerInfo $x} 11{Edit-Hosts} 12{Set-PublicDesktopFullControl} 13{Office-BeGone} 14{Disable-LocalAdmins} #15 16{HideTaskbarPeopleIcon} 17{EnableFileDeleteConfirm} 18{List-Functions} }