Pages

Tuesday, 28 December 2021

Replace file extension

ls C:\Temp\Tesingname\*.* | ? { !$_.PSIsContainer   -and   $_.extension -eq '.txt' } |   ren -NewName { "$($_.BaseName)_$(get-date -format "yyyyMMdd_HHmmss")$($_.extension) "  }  
ls C:\Temp\Tesingname\*.* | ? { !$_.PSIsContainer   -and   $_.extension -eq '.log' } |   ren -NewName { "$($_.BaseName)_$(get-date -format "HHmmss")$($_.extension) "  }  


Thursday, 7 October 2021

Remove only path variable through powershell

 $path = [System.Environment]::GetEnvironmentVariable(

    'PATH',
    'User' # For user variable
    #'Machine' for system variable
)
 
$path = ($path.Split(';') | Where-Object { $_ -ne 'var1' }) -join ';'
 
$path = ($path.Split(';') | Where-Object { $_ -ne 'var2' }) -join ';'
# Set it
[System.Environment]::SetEnvironmentVariable(
    'PATH',
    $path,
    'User' # For user variable
    #'Machine' for system variable
)

Tuesday, 21 September 2021

Keepass

 Set objShell = CreateObject( "WScript.Shell" )
Set objFSO = CreateObject("Scripting.FileSystemObject")
GetCurrentFolder = ObjFso.GetParentFolderName (Wscript.ScriptFullName)
strAppDATA = objShell.ExpandEnvironmentstrings ("%appdata%")
If NOT objFSO.FolderExists(strAppData & "\KeePass") Then
objFSO.CreateFolder(strAppData & "\KeePass")
End If
ObjFSo.CopyFile (GetCurrentFolder & "\KeePass.config.xml") , (strAppData & "\KeePass\KeePass.config.xml")


#Set Active setup

Copy-Item -Path "$dirsupportfiles\*.*" -Destination "$envProgramFilesX86\KeePass Password Safe 2\"        
Set-ActiveSetup -StubExePath "$envProgramFilesX86\KeePass Password Safe 2\copyfile.vbs" -Arguments '/Silent' -Description 'Userdata' -Key 'KeePass' -Locale 'en'

Friday, 27 August 2021

Batch script to set a registry key in HKCU registry

 @ECHO OFF

SETLOCAL enabledelayedexpansion


FOR /f "tokens=7 delims=\" %%a in ('REG QUERY "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList" /f "S-1-5-21"') do (

    REG QUERY "HKU\%%a\Software" >nul 2^>^&1

    IF !ERRORLEVEL! EQU 0 (

        ECHO Adding Reg Key to Pre-Enable Open Text 1 for %%a

        REG ADD "HKU\%%a\Software\Microsoft\Internet Explorer\Approved Extensions" /v "{67FFC103-051E-48ED-8F5A-76C9C82A36F2}" /t REG_BINARY /d "51667a6c4c1d3b1b13deea7e2e568b069b503589ca6c75ed" /f

REG DEL "HKU\%%a\Software\Microsoft\Windows\CurrentVersion\Ext\Settings\{67FFC103-051E-48ED-8F5A-76C9C82A36F2}" /f 

    )

)


Thursday, 26 August 2021

Add content to azure table PowerShell

# Step 1, use Start-Transcript to capture the execution to a text file and set variables for connecting to Azure Table
#Start-Transcript -Path "C:\TempLogs\NvidiaAdapter-$(((get-date).ToUniversalTime()).ToString("yyyyMMddThhmmssZ")).log"

Start-Transcript -Path "C:\TempLogs\NvidiaAdapter.log"

#storage account details
$storageAccountName = 'laps1'
$tableName = 'PowershellReports'
$sasToken = '?sv=2020-08-04&ss=bfqt&srt=sco&sp=rwdlacuptfx&se=2022-10-19T15:25:02Z&st=2021-08-24T07:25:02Z&spr=https&sig=jqaTwTTsVOZu08Xu93GVAOtf4mmpKN5IiuMYgOcq%2F78%3D'
$dateTime = get-date
$partitionKey = 'displaydrivers'

# Step 2, Connect to Azure Table Storage
Install-Module -Name Az -Repository PSGallery -Force
Import-Module -Name Az
$storageCtx = New-AzStorageContext -StorageAccountName $storageAccountName -SasToken $sasToken
$table = (Get-AzStorageTable -Name $tableName -Context $storageCtx).CloudTable

# Step 3, Check for presence of hotfix
$graphics = gwmi Win32_VideoController | Where-Object {$_.Name.contains("NVIDIA") } |Select-Object Name
$nvidiadriver = $graphics.Name
$PatchCheck = "$nvidiadriver"
$model = (gwmi Win32_computersystem -computername $env:COMPUTERNAME).model
# Step 4, Write data to Table Storage and end transcript.
Write-Host "Writing to Azure Table $table"
Install-Module AzTable -Force
Add-AzTableRow -table $table -partitionKey $partitionKey -rowKey ([guid]::NewGuid().tostring()) -property @{

'LocalHostname' = $env:computername
'NvidiaAdaptername' = $PatchCheck
'Model' = $model

} | Out-Null
Stop-Transcript

Sunday, 1 August 2021

PowerShell App Deployment Toolkit useful Commands

 ## Commonly used PSADT env variables
 $envCommonDesktop           # C:\Users\Public\Desktop
 $envCommonPrograms          # C:\ProgramData\Microsoft\Windows\Start Menu\Programs
 $envProgramFiles            # C:\Program Files
 $envProgramFilesX86         # C:\Program Files (x86)
 $envProgramData             # c:\ProgramData
 $envUserDesktop             # c:\Users\{user currently logged in}\Desktop
 $envUserStartMenuPrograms   # c:\Users\{user currently logged in}\AppData\Roaming\Microsoft\Windows\Start Menu\Programs
 $envSystemDrive             # c:
 $envWinDir                  # c:\windows
 
 ## How to load ("dotsource") PSADT functions/variables for manual testing (your powershell window must be run as administrator first)
 
 cd "$path_to_PSADT_folder_youre_working_from"
 
 . .\AppDeployToolkit\AppDeployToolkitMain.ps1
 
 ## *** Examples of exe install***
 
 Execute-Process -Path '<application>.exe' -Parameters '/quiet' -WaitForMsiExec:$true
 
 Execute-Process -Path "$dirFiles\DirectX\DXSetup.exe" -Parameters '/silent' -WindowStyle 'Hidden'
 
 #open notepad, don't wait for it to close before proceeding (i.e. continue with script)
 
 Execute-Process -Path "$envSystemRoot\notepad.exe" -NoWait
 
 #Execute an .exe, and hide confidential parameters from log file
 
 $serialisation_params = '-batchmode -quit -serial <aa-bb-cc-dd-ee-ffff11111> -username "<serialisation username>" -password "SuperSecret123"'
 
 Execute-Process -Path "$envProgramFiles\Application\Serialise.exe" -Parameters "$serialisation_params" -SecureParameters:$True
 
 ##***Example to install an msi***
 
 Execute-MSI -Action 'Install' -Path "$dirFiles\<application>.msi" -Parameters 'REBOOT=ReallySuppress /QN'
 
 Execute-MSI -Action 'Install' -Path 'Discovery 2015.1.msi'
 
 #MSI install + transform file
 
 Execute-MSI -Action 'Install' -Path 'Adobe_Reader_11.0.0_EN.msi' -Transform 'Adobe_Reader_11.0.0_EN_01.mst'
 
 ## Install a patch
 
 Execute-MSI -Action 'Patch' -Path 'Adobe_Reader_11.0.3_EN.msp'
 
 ## To uninstall an MSI
 
 Execute-MSI -Action Uninstall -Path '{5708517C-59A3-45C6-9727-6C06C8595AFD}'
 
 ## Uninstall a number of msi codes
 
 "{2E873893-A883-4C06-8308-7B491D58F3D6}", <# Example #>`
  "{2E873893-A883-4C06-8308-7B491D58F3D6}", <# Example #>`
  "{2E873893-A883-4C06-8308-7B491D58F3D6}", <# Example #>`
  "{2E873893-A883-4C06-8308-7B491D58F3D6}", <# Example #>`
  "{2E873893-A883-4C06-8308-7B491D58F3D6}", <# Example #>`
  "{B234DC00-1003-47E7-8111-230AA9E6BF10}" <# Last example cannot have a comma after the double quotes #>`
  | % { Execute-MSI -Action 'Uninstall' -Path "$_" } <# foreach item, uninstall #>
 
 ## ***Run a vbscript***
 
 Execute-Process -Path "cscript.exe" -Parameters "$dirFiles\whatever.vbs"

 ## Copy a file to the correct relative location for all user accounts
 
 #grabbed from here: http://psappdeploytoolkit.com/forums/topic/copy-file-to-all-users-currently-logged-in-and-for-all-future-users/
 
 $ProfilePaths = Get-UserProfiles | Select-Object -ExpandProperty 'ProfilePath'
 
 ForEach ($Profile in $ProfilePaths) {
 
     Copy-File -Path "$dirFiles\Example\example.ini" -Destination "$Profile\Example\To\Path\"
 
 }
 
 ##***Remove registry key***
 
 #I dont know the right term, but these are to delete the whole 'folder' reg key
 
 Remove-RegistryKey -Key 'HKEY_LOCAL_MACHINE\SOFTWARE\Macromedia\FlashPlayer\SafeVersions' -Recurse
  Remove-RegistryKey -Key 'HKLM:SOFTWARE\Macromedia\FlashPlayer\SafeVersions' -Recurse
 
 #This is to remove a specific reg key item from within a 'folder'
 
 Remove-RegistryKey -Key 'HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Run' -Name 'RunAppInstall'
 
 Remove-RegistryKey -Key 'HKLM:SOFTWARE\Microsoft\Windows\CurrentVersion\Run' -Name 'RunAppInstall'
 
 ## ***Create a reg key***
 
 Set-RegistryKey -Key 'HKEY_LOCAL_MACHINE\SOFTWARE\LMKR\Licensing' -Name 'LMKR_LICENSE_FILE' -Value '@license'-Type String -ContinueOnError:$True
 
 ## ***To set an HKCU key for all users including default profile***
  [scriptblock]$HKCURegistrySettings = {
      # I included both to illustrate that HKCU\ is an acceptable abbreviation
      Set-RegistryKey -Key 'HKEY_CURRENT_USER\SOFTWARE\Classes\AppX4hxtad77fbk3jkkeerkrm0ze94wjf3s9' -Name 'NoOpenWith' -Value '""'-Type String -ContinueOnError:$True -SID $UserProfile.SID
      Set-RegistryKey -Key 'HKCU\Software\Microsoft\Office\14.0\Common' -Name 'qmenable' -Value 0 -Type DWord -SID $UserProfile.SID
  }Invoke-HKCURegistrySettingsForAllUsers -RegistrySettings $HKCURegistrySettings
 
  #import a .reg key, useful if there's a butt-tonne of nested keys/etc
 
 Execute-Process -FilePath "reg.exe" -Parameters "IMPORT `"$dirFiles\name-of-reg-export.reg`"" -PassThru
 
 ## To pause script for <x> time
 
 Start-Sleep -Seconds 120
  ## ***To copy and overwrite a file***
 
 Copy-File -Path "$dirSupportFiles\mms.cfg" -Destination "C:\Windows\SysWOW64\Macromed\Flash\mms.cfg"
 
 ## ***To copy a file***
 Copy-File -Path "$dirSupportFiles\mms.cfg" -Destination "C:\Windows\SysWOW64\Macromed\Flash\"
 
 ## ***To copy a folder***
 
 # pls note the destination should be the PARENT folder, not the folder name you want it to be.
 
 # for example, you'd copy "mozilla firefox" to "c:\program files", if you were wanting to copy the application files.
 
 # if copying to root of c:, include trailing slash - i.e. "$envSystemDrive\" not "$envSystemDrive" or "c:"
 
 Copy-File -Path "$dirFiles\client_1" -Destination "C:\oracle\product\11.2.0\" -Recurse
 
 ## ***To delete a file or shortcut***
 
 Remove-File -Path "$envCommonDesktop\GeoGraphix Seismic Modeling.lnk"

 ## Remove a bunch of specific files
 "$envCommonDesktop\Example 1.lnk", <# Example #>`
 "$envCommonDesktop\Example 2.lnk", <# Example #>`
  "$envCommonDesktop\Example 3.lnk" <# Careful with the last item to not include a comma after the double quote #>`
  | % { Remove-File -Path "$_" }
 
 ## Remove a bunch of specific folders and their contents
 
 "$envSystemDrive\Example Dir1",  <# Example #>`
 "$envProgramFiles\Example Dir2",  <# Example #>`
 "$envProgramFiles\Example Dir3",  <# Example #>`
 "$envProgramFilesX86\Example Dir4",  <# Example #>`
 "$envSystemRoot\Example4" <# Careful with the last item to not include a comma after the double quote #>``
 | % { Remove-Folder -Path "$_" }
 
 ## Remove a bunch of specific folders, only if they're empty
 <# Use this by specifying folders from "deepest folder level" to "most shallow folder level" order e.g.
  c:\program files\vendor\app\v12\junk - then  
 c:\program files\vendor\app\v12 - then
 c:\program files\vendor\app - then
 c:\program files\vendor
 using the above example, it will only remove c:\program files\vendor if every other folder above is completely empty.
 
 if for example v11 was also installed, it would stop prior #>
 
 (
 
     "$envProgramFiles\vendor\app\v12\junk",
     "$envProgramFiles\vendor\app\v12",
     "$envProgramFiles\vendor\app",
     "$envProgramFiles\vendor",
     "$envProgramFilesX86\vendor\app\v12\junk",
     "$envProgramFilesX86\vendor\app\v12",
     "$envProgramFilesX86\vendor\app",
     "$envProgramFilesX86\vendor" <# careful not to include the comma after the double quotes in this one #>
      ) | % { if (!(Test-Path -Path "$_\*")) { Remove-Folder -Path "$_" } }
 
# for each piped item, if the folder specified DOES NOT have contents ($folder\*), remove the folder
  ## Import a certificate to system 'Trusted Publishers' store.. helpful for clickOnce installers & importing drivers
  # (for references sake, I saved as base64, unsure if DER encoded certs work)
 
 Execute-Process -Path "certutil.exe" -Parameters "-f -addstore -enterprise TrustedPublisher `"$dirFiles\certname.cer`""
  Write-Log -Message "Imported Cert" -Source $deployAppScriptFriendlyName
 
 ## Import a driver (note, >= win7 must be signed, and cert must be in trusted publishers store)
 
 Execute-Process -Path 'PnPutil.exe' -Parameters "/a `"$dirFiles\USB Drivers\driver.inf`""
 
 ## Register a DLL module
 
 Execute-Process -FilePath "regsvr32.exe" -Parameters "/s `"$dirFiles\example\codec.dll`""
 
 ## Make an install marker reg key for custom detections
  #for e.g. below would create something like:
  #HKLM:\SOFTWARE\PSAppDeployToolkit\InstallMarkers\Microsoft_KB2921916_1.0_x64_EN_01
 
 Set-RegistryKey -Key "$configToolkitRegPath\$appDeployToolkitName\InstallMarkers\$installName"
 
 ## While loop pause (incase app installer exits immediately)
 
 #pause until example reg key
 
 While(!(test-path -path "HKLM:\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\{product-code-hereD}")) {
 
                 sleep 5;
 
                 Write-Log -Message "$appVendor - $appName - $appVersion is still not finished installing, sleeping another 5" -Source $deployAppScriptFriendlyName;
 
 }
 
 #pause until example file
 
 While(!(test-path -path "$envCommonDesktop\Example Shortcut.lnk")) {
 
                 sleep 5;
 
                 Write-Log -Message "$appVendor - $appName - $appVersion is still not finished installing, sleeping another 5" -Source $deployAppScriptFriendlyName;
 
 }
 
 ##***To Create a shortcut***
 
 New-Shortcut -Path "$envCommonPrograms\My Shortcut.lnk" `
 
     -TargetPath "$envWinDir\system32\notepad.exe" `
 
     -Arguments "--example-argument --example-argument-two" `
 
     -Description 'Notepad' `
 
     -WorkingDirectory "$envHomeDrive\$envHomePath"
 
 ## Modify ACL on a file
 
 #first load the ACL
 
 $acl_to_modify = "$envProgramData\Example\File.txt"
 $acl = Get-Acl "$acl_to_modify"
 #add another entry to the ACL list (in this case, add all users to have full control)
 $ar = New-Object System.Security.AccessControl.FileSystemAccessRule("BUILTIN\Users", "FullControl", "None", "None", "Allow")
 $acl.SetAccessRule($ar)
 #re-write the acl on the target file
 Set-Acl "$acl_to_modify" $acl
 
 ## Modify ACL on a folder
 
 $folder_to_change = "$envSystemDrive\Example_Folder"
 $acl = Get-Acl "$folder_to_change"
 $ar = New-Object System.Security.AccessControl.FileSystemAccessRule("BUILTIN\Users", "FullControl", "ContainerInherit,ObjectInherit", "None", "Allow")
 $acl.SetAccessRule($ar)
 Set-Acl "$folder_to_change" $acl  
 

##Modify ACL to registry

$acl = Get-Acl "HKLM:\SOFTWARE\Microsoft\Active Setup"
$person = [System.Security.Principal.NTAccount]"Users"          
$access = [System.Security.AccessControl.RegistryRights]"FullControl"
$inheritance = [System.Security.AccessControl.InheritanceFlags]"ContainerInherit,ObjectInherit"
$propagation = [System.Security.AccessControl.PropagationFlags]"None"
$type = [System.Security.AccessControl.AccessControlType]"Allow"
$rule = New-Object System.Security.AccessControl.RegistryAccessRule($person,$access,$inheritance,$propagation,$type)
$acl.AddAccessRule($rule)
$acl |Set-Acl

 ## Add to environment variables (specifically PATH in this case)
 
 # The first input in the .NET code can have Path subtituted for any other environemnt variable name (gci env: to see what is presently set)
 
 $path_addition = "C:\bin"
 #add $path_addition to permanent system wide path
 [Environment]::SetEnvironmentVariable("Path", $env:Path + ";" + $path_addition, "Machine")
 #add $path_addition to permanent user specific path
 [Environment]::SetEnvironmentVariable("Path", $env:Path + ";" + $path_addition, "User")
 #add $path_addition to the process level path only (i.e. when you quit script, it will no longer be applied)
  [Environment]::SetEnvironmentVariable("Path", $env:Path + ";" + $path_addition, "Process")
 
 
 
 
 
 #.NET 4.x comparison/install
 $version_we_require = [version]"4.5.2"
 $version_we_want_path = "$dirFiles\NDP452-KB2901907-x86-x64-AllOS-ENU.exe"
 $install_params = "/q /norestart"
 if((Get-RegistryKey "HKLM:\SOFTWARE\Microsoft\NET Framework Setup\NDP\v4\Full" -Value Version) -lt $version_we_require) {
 
     Write-Log -Source $deployAppScriptFriendlyName -Message ".NET version is < [string]$version_we_require, installing"
 
     Execute-Process -Path "$version_we_want_path" -Parameters "$install_params" -WaitForMSIExec:$true
  }
 
 
 
 #exit codes for reboot required
  #soft reboot <- will not 'force' restart, and sccm will progress past, but will nag to restart afterward
  Exit-Script -ExitCode 3010
  #hard reboot <- does not 'force' restart, but sccm won't proceed past any pre-reqs without reboot
  Exit-Script -ExitCode 1641
 
 ##Create Active Setup to run once per user, and run an arbitrary executable as the user
  # *WARNING* this really isn't a recommended method for a number of reasons.
  # 1. You must logoff a logged in user for them to run this
  # 2. Activesetup is not syncronous and will hold up the user login process until the command completes
  # If the executable requests user input you can prevent logins
  # 3. It's slow
  # You're better off using a scheduled task, or capturing what the executable does and doing it another way
 
 Copy-File -Path "$dirFiles\Example.exe" -Destination "$envProgramData\Example"
  Set-ActiveSetup -StubExePath "$envProgramData\Example\Example.exe" `
  -Description 'AutoDesk BIM Glue install' `
      -Key 'Autodesk_BIM_Glue_Install' `
      -ContinueOnError:$true
 
 ## Create an activesetup to run once per user, to import a .reg file
  # *WARNING* this really isn't a recommended method for a number of reasons.
  # 1. You must logoff a logged in user for them to run this
  # 2. Activesetup is not syncronous and will hold up the user login process until the command completes
  # If the executable requests user input you can prevent logins
  # 3. It's slow
  # You're better off using a scheduled task, or capturing what the executable does and doing it another way
 Copy-File -Path "$dirFiles\many_registry_keys_for_app_x.reg" -Destination "$envProgramData\Hidden\Path"

  Set-ActiveSetup -StubExePath "reg.exe IMPORT `"$envProgramData\Hidden\Path\many_registry_keys_for_app_x.reg`"" `
      -Description 'My undesirable way of applying registry keys' `
      -Key 'Undesirable_Reg_keys' `
      -ContinueOnError:$true
 
 ## function to assist finding uninstall strings, msi codes, display names of installed applications
 # paste into powershell window (or save in (powershell profile)[http://www.howtogeek.com/50236/customizing-your-powershell-profile/]
  # usage once loaded: 'Get-Uninstaller chrome'

 function Get-Uninstaller {
    [CmdletBinding()]
   param(
     [Parameter(Mandatory = $true)]
     [ValidateNotNullOrEmpty()]
     [string] $Name
    )
 
   $local_key     = 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Uninstall\*'
   $machine_key32 = 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\*'
   $machine_key64 = 'HKLM:\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\*'
   $keys = @($local_key, $machine_key32, $machine_key64)
   Get-ItemProperty -Path $keys -ErrorAction 'SilentlyContinue' | ?{ ($_.DisplayName -like "*$Name*") -or ($_.PsChildName -like "*$Name*") } | Select-Object PsPath,DisplayVersion,DisplayName,UninstallString,InstallSource,InstallLocation,QuietUninstallString,InstallDate
 
 }
 
 ## end of function
 
 [scriptblock]$HKCURegistrySettings = {
  Remove-RegistryKey -Key "HKCU\Software\Microsoft\Active Setup\Installed Components\HelperObject" -SID $UserProfile.SID
} Invoke-HKCURegistrySettingsForAllUsers -RegistrySettings $HKCURegistrySettings
 
#Get pending rebppt

 $reboot = Get-PendingReboot
 if($reboot.IsSystemRebootPending -eq $true -or $reboot.IsCBServicingRebootPending -eq $true -or $reboot.IsWindowsUpdateRebootPending -eq $true -or $reboot.IsSCCMClientRebootPending -eq $true -or $reboot.IsFileRenameRebootPending -eq $true)
 
 { #reboot pending, cannot proceed.
     Show-InstallationPrompt -Message "A reboot is pending on this machine. Please reboot this machine first before installing $installTitle" -ButtonRightText 'OK'
      Exit-Script -ExitCode 69004 #this code to indicate a reboot is pending on this machine, and installation cannot proceed.
  }
 
 #End
  # Powershell deployment tool kit extra script
  # https://www.etdwh.com/2016/07/powershell-app-deployment-toolkit-deep-dive/

##Get Any file exists in the folder
 $UninstPath32 = Get-ChildItem -Path "C:\ProgramData\Package Cache\*" -Include windowsdesktop-runtime-3.0.*win-x86.exe -Recurse -ErrorAction SilentlyContinue
 If($UninstPath32.Exists)
 {
 Write-Log -Message "Found $($UninstPath32.FullName), now attempting to uninstall $installTitle (x86)."
 Execute-Process -Path "$UninstPath32" -Parameters "/uninstall /quiet /norestart /log C:\Windows\Logs\Software\NETDesktopRuntime30x86-Uninstall.log" -WindowStyle Hidden
 }
  ##Get the processor Architechture  
 ##AMD64
 
  If ($ENV:PROCESSOR_ARCHITECTURE -eq 'x86'){
  Write-Log -Message "Detected 32-bit OS Architecture" -Severity 1 -Source $deployAppScriptFriendlyName
 
## Microsoft Windows .NET Desktop Runtime 3.0 (x86)
$ExePath32 = Get-ChildItem -Path "$dirFiles" -Include windowsdesktop-runtime-3.0.*win-x86.exe -File -Recurse -ErrorAction SilentlyContinue
 
If($ExePath32.Exists)
{
Write-Log -Message "Found $($ExePath32.FullName), now attempting to install Microsoft Windows .NET Desktop Runtime 3.0 (x86)."
Show-InstallationProgress "Installing Microsoft Windows .NET Desktop Runtime 3.0 (x86). This may take some time. Please wait..."
Execute-Process -Path "$ExePath32" -Parameters "/install /quiet /norestart /log C:\Windows\Logs\Software\NETDesktopRuntime30x86-Install.log" -WindowStyle Hidden
}
}
 
## Get The uninstallation string for exe and uninstall silently
 $AppList = Get-InstalledApplication -Name '7-Zip'
 ForEach ($App in $AppList)
{
If($App.UninstallString)
{
$UninstPath = $App.UninstallString -replace '"', ''
If(Test-Path -Path $UninstPath)
{
Write-log -Message "Found $($App.DisplayName) ($($App.DisplayVersion)) and a valid uninstall string, now attempting to uninstall."
Execute-Process -Path $UninstPath -Parameters '/S'
Sleep -Seconds 5
}
 
}
 
}
##Run the Registries through CMD
cmd /c regedit.exe /s $dirSupportFiles\7zipFileAssoc.reg
## Install Adobe Patch only
$MspPath = Get-ChildItem -Path "$dirFiles" -Include AcroRdr*.msp -File -Recurse -ErrorAction SilentlyContinue
 
If($MspPath.Exists)
{ Write-Log -Message "Found $($MspPath.FullName), now attempting to install $installTitle."
# Install Adobe Reader DC Patch
Show-InstallationProgress "Installing Adobe Reader DC Patch. This may take some time. Please wait..."
Execute-MSI -Action Patch -Path "$MspPath"
}
### Remove the userdata through system contest
$Users = Get-ChildItem C:\Users
 
foreach ($user in $Users){
 
$StartMenuSC = "$($user.fullname)\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Amazon"
 
If (Test-Path $StartMenuSC) {
 
Remove-Item $StartMenuSC -Recurse -Force -ErrorAction SilentlyContinue
 
}
 
## Remove Kindle Desktop Shortcuts From All Profiles
 
$DesktopSC = "$($user.fullname)\Desktop\Kindle.lnk"
 
If (Test-Path $DesktopSC) {
 
Remove-Item $DesktopSC -Recurse -Force -ErrorAction SilentlyContinue
 
}
 
}
 
### Get user profile and uninstall the application if installed in user profile
$Users = Get-ChildItem C:\Users
foreach ($user in $Users){
$Anaconda = "$($user.fullname)\Anaconda"
If (Test-Path $Anaconda) {
$UninstPath = Get-ChildItem -Path "$Anaconda\*" -Include Uninstall-Anaconda.exe -Recurse -ErrorAction SilentlyContinue
If($UninstPath.Exists)
{
Write-Log -Message "Found $($UninstPath.FullName), now attempting to uninstall $installTitle."
 
Execute-ProcessAsUser -Path "$UninstPath" -Parameters "/S"
 
Get-Process -Name "Un_A" -ErrorAction SilentlyContinue | Wait-Process
 
## Cleanup Anaconda (User Profile) Directory
 
If (Test-Path $Anaconda) {
 
Write-Log -Message "Cleanup ($Anaconda) Directory."
 
Remove-Item -Path "$Anaconda" -Force -Recurse -ErrorAction SilentlyContinue
 
}
 
}
 
}
 
}

#Profiles in the machine

$UserProfiles = Get-WmiObject Win32_UserProfile | Select-Object -ExpandProperty LocalPath
 
ForEach ($Profile in $UserProfiles) {
 
if (Test-Path -Path "$envProgramFiles\NetBeans-12.9\") {
 
New-Item "$Profile\AppData\Roaming\NetBeans\12.9\config\Preferences\org\netbeans\" -ItemType Directory -Force
 
Copy-Item $Config -Destination "$Profile\AppData\Roaming\NetBeans\12.9\config\Preferences\org\netbeans\" -ErrorAction SilentlyContinue
 
}
 
}
 
##  https://silentinstallhq.com/atom-install-and-uninstall-powershell/
 
## Stop Process
 
Get-Process -Name "unins000" -ErrorAction SilentlyContinue | Wait-Process
Stop-Process -Name 'Integrator','DiskDefrag' -Force -ErrorAction SilentlyContinue
 
#Service disabled
 
Set-Service -Name 'AdskLicensingService' -StartupType 'Disabled' -ErrorAction SilentlyContinue
 
#Get the file and Uninstall the application
 
$XML = Get-ChildItem -Path "C:\ProgramData\Autodesk\ODIS\metadata\{82C320DD-8EC4-3382-A19F-1AB2019EEFCE}\" -Include bundleManifest.xml -File -Recurse -ErrorAction SilentlyContinue
 
If($XML.Exists)
{

Write-Log -Message "Found $($XML.FullName), now attempting to uninstall Autodesk AutoCAD 2022."
 
Show-InstallationProgress "Uninstalling Autodesk AutoCAD Mechanical 2022. This may take some time. Please wait..."
 
if (Test-Path -Path "$envProgramFiles\Autodesk\AdODIS\V1\Installer.exe") {
 
Execute-Process -Path "$envProgramFiles\Autodesk\AdODIS\V1\Installer.exe" -Parameters "-i uninstall -q -m C:\ProgramData\Autodesk\ODIS\metadata\{82C320DD-8EC4-3382-A19F-1AB2019EEFCE}\bundleManifest.xml" -WindowStyle Hidden -IgnoreExitCodes "1603"
 
Sleep -Seconds 5
 
}
 
}
## DIffirent uninstall older application
 
https://silentinstallhq.com/azure-batch-explorer-install-and-uninstall-powershell/

#Brave application Uninstallation
$Brave = ((Get-InstalledApplication -Name 'Brave').UninstallString -split '" ').Trim('"')
 
If ($Brave) {
 
$BraveUninst = $Brave[0]
 
$BraveParams = $Brave[1]
 
Execute-Process -Path $BraveUninst -Parameters "$BraveParams --force-uninstall" -WindowStyle Hidden -IgnoreExitCodes '20'
 
Sleep -Seconds 5
 
}
$ExePath = Get-ChildItem -Path "$dirFiles" -Include DiscordSetup.exe -File -Recurse -ErrorAction SilentlyContinue
 
If($ExePath.Exists)
 
{
 
Write-Log -Message "Found $($ExePath.FullName), now attempting to install $installTitle."
 
Show-InstallationProgress "Installing the Discord Application. This may take some time. Please wait..."
 
Execute-ProcessAsUser -Path "$ExePath" -Parameters "-s" -Wait

Get-Process -Name "DiscordSetup" -ErrorAction SilentlyContinue | Wait-Process
 
}
 
###ISS File handling  
https://silentinstallhq.com/dell-storage-manager-client-install-and-uninstall-powershell/
 
 
$Users = Get-ChildItem C:\Users
 
foreach ($user in $Users){
$DeepLLocal = "$($user.fullname)\AppData\Local\DeepL"
 
If (Test-Path $DeepLLocal) {
$UninstPath = Get-ChildItem -Path "$DeepLLocal\*" -Include Update.exe -Recurse -ErrorAction SilentlyContinue
If($UninstPath.Exists)
{}}
 
##Create a startmenu shortcut
$TargetFile = "$envProgramFiles\Eclipse\cpp-2021\eclipse\eclipse.exe"
 
$ShortcutFile = "$envAllUsersProfile\Microsoft\Windows\Start Menu\Programs\Eclipse IDE for CPP Developers.lnk"
 
$WScriptShell = New-Object -ComObject WScript.Shell
 
$Shortcut = $WScriptShell.CreateShortcut($ShortcutFile)
 
$Shortcut.TargetPath = $TargetFile
 
$Shortcut.Save()
 
#Stop more than one servuce
Stop-Process -Name 'ExpressVPN','ExpressVPNNotificationService' -Force -ErrorAction SilentlyContinue
 
$Reboot = Get-PendingReboot
 
if($Reboot.IsSystemRebootPending -eq $True -or $Reboot.IsCBServicingRebootPending -eq $True -or $Reboot.IsWindowsUpdateRebootPending -eq $True -or $Reboot.IsSCCMClientRebootPending -eq $True -or $Reboot.IsFileRenameRebootPending -eq $True)
 
{
 
## A Reboot Is Pending, Cannot Proceed Without a Restart
 
Write-Log -Message "A system restart is required before the installation of $installTitle can proceed."
 
Show-InstallationPrompt -Message "A system restart is required before the installation of $installTitle can proceed, please reboot at your earliest convenience." -ButtonRightText 'OK'
 
Exit-Script -ExitCode 69004 #This code is to indicate a reboot is pending on this machine, and the installation cannot proceed.
 
}
$GraphiQL = ((Get-InstalledApplication -Name 'GraphiQL').UninstallString -split '" ').Trim('"')

If ($GraphiQL) {
 
$GraphiQLUninst = $GraphiQL[0]
$GraphiQLParams = $GraphiQL[1]
Execute-Process -Path $GraphiQLUninst -Parameters "$GraphiQLParams /S" -WindowStyle Hidden
 
Sleep -Seconds 5
 
}
 
 
 
 ## Set-ExecutionPolicy -Scope Process -ExecutionPolicy Bypass
 
 ## cmd /c setx /M PATH "%PATH%;C:\Program Files (x86)\Common Files\Lenel;C:\Program Files (x86)\Acuant\SDK" | Out-Null
 
 #### Set registry to all hives in the registry
 
 Get-ChildItem -Path "HKLM:\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\Interfaces" | ForEach-Object { Set-ItemProperty -Path $_.PSPath -Name "RegisterAdapterName" -Value "1" }
 
 ## Lap manufacturar
 
 $model = (gwmi Win32_computersystem -computername $env:COMPUTERNAME).Manufacturer
 
 $model
 

User based detection

function getloggedindetails () {     ##Find logged in username     $user = Get-WmiObject Win32_Process - Filter "Name='explorer...

Search This Blog