Skip to content

Instantly share code, notes, and snippets.

@mezcel
Last active December 8, 2024 23:36
Show Gist options
  • Select an option

  • Save mezcel/34895a5ae768873a26e762e068394a84 to your computer and use it in GitHub Desktop.

Select an option

Save mezcel/34895a5ae768873a26e762e068394a84 to your computer and use it in GitHub Desktop.
Powershell notes
## ignore vs settings
.vscode
.vs
## win10 line endins
*.bat eol=crlf
*.ps1 eol=crlf
## Linux/Posix line endins
*.sh eol=lf
Makefile eol=lf
################################################################################
# This .gitignore file was automatically created by Microsoft(R) Visual Studio.
################################################################################
.vs
## debug refferences
Win32Product.csv
Uninstall_HKLM.csv
Exec_FileVersionInfo.csv

powershell-notes

About

Reminders and script snippets for Powershell

Contents

Menu:

1. Online Resources

2. Markdown Notes

3. PS1 Scripts

4. Misc. Notes ( Uncategorized )

  • Powershell scripts in git repo
    ## Consistent win10 line endings in git repo
    ## Add ps1 to .gitattributes
    
    Add-Content "*.ps1 eol=crlf" .gitattributes

Bash to Powershell

The default is is v5.1 but v7.1 (March 2020) has more builtin tools, like Markdown viewing.

## outdated install
msiexec.exe /package PowerShell-7.1.2-win-x64.msi /quiet ADD_EXPLORER_CONTEXT_MENU_OPENPOWERSHELL=1 ENABLE_PSREMOTING=1 REGISTER_MANIFEST=1
  • github dl
  • View this markdown in Powershell 7.1

    Show-Markdown .\bash2powershell.md

edit text in powershell

  • Micro text editor
  • If WSL bash is installed with vim you can edit a text file in PS
     bash -c "vim myFile.txt"

Common cmdlet's

## Update local help documentation
Update-Help

Note: A lot of bashism equivalents are built into PS

about BASH Powershell
Display the pathname for the current directory pwd Get-Location
Change to directory cd Set-Location
List directory contents ls Get-ChildItem
Copy files and directories cp Copy-Item
Remove (delete) file(s) and/or directories rm Remove-Item
Create a new directory mkdir New-Item -ItemType Directory
Create an empty file with the specified name touch New-Item -ItemType File
Display file�s contents to the standard output device cat Get-Content
ping ping Test-Connection
manpage man Get-Help
ps ps Get-Process
kill Kill Stop-Process -Name
echo echo Write-Host
print lines matching a pattern grep Select-String -Path "file-path" -Pattern "string-pattern"
does path exist? [ -f "filePath" ] Test-Path "filePath"
If - else if - else statement if [ condition ]; then ## stuff; elif [ condition ]; then ## stuff; else ## stuff; fi if ( condition ) { ## stuff; } elseif ( condition ) { ## stuff; } else { ## stuff; }
The name directory file is in. In PowerShell, remember to first get the file object. basename fileName fileName.name
The number of bytes in file. In PowerShell, remember to first get the file object. dirname fileName fileName.directoryname
unzip Expand-Archive -LiteralPath ".\file.zip" -DestinationPath ".\FileDir"
zip Compress-Archive -Path ".\FileDir\*.*" -DestinationPath "file.zip"
download files wget (New-Object Net.WebClient).DownloadString( 'https://url-string/file' )
shutdown shutdown now Stop-Now

common commands and aliases

bash equivalents

bash Powershell About
touch New-Item -Path "< path to file >" -ItemType File new file
mkdir New-Item -Path "< path to dir >" -ItemType Directory new dir
rm Remove-Item -Path "< path to file/dir >" remove file/dir
mv Move-Item -Path "< source path > " -Destination "< destination path >" move
mv Rename-Item -Path "< original file path >" -NewName "< new file name >" rename
rm Remove-Item -Path "< path >" del file/dir
rm -rf Remove-Item -Path "< path >" -Recurse del file/dir recursively
cp Copy-Item -Path "< source path >" -Destination "< destination path >" copy
ls -al Get-ChildItem -Force "< dir >" -Force shows hidden files too
ls Get-ChildItem -Force "< dir >" -Recurse all subfolders and their content
echo "text to add" >> < your file > Add-Content "text to add" < your file > append text to file
echo " " Write-Host " " echo
less Get-Content -Path < file path > view text file contents
\n `n new line
\t `t tab
&& -and and
|| -or or
bash Powershell About
command -v < prgm name > Get-Command "< prgm name >" is the command recognized by the terminal
killall < proc name > Stop-Process -Name "< process name >" kill process
shutdown now shutdown /s /f /t 0 shutdown
shutdown now Stop-Computer shutdown
bash Powershell About
ifconfig ipconfig
systemctl con up Enable-NetAdapter -Name "< my adapter >" -Confirm:$false
systemctl con down Disable-NetAdapter -Name "< my adapter >" -Confirm:$false
<#
clone-my-gist-notes.ps1
Clone my gist notes
https://gist.github.com/mezcel
#>
function greetings {
Write-Host "`nAbout:" -ForegroundColor Cyan
Write-Host "`tUpdate local gist repos from https://gist.github.com/mezcel" -ForegroundColor Cyan
Write-Host "`tand clone repos that are not on local machine" -ForegroundColor Cyan
Write-Host "`tsource:`n`thttps://gist.github.com/mezcel/34895a5ae768873a26e762e068394a84#file-clone-my-gist-notes-ps1" -ForegroundColor Cyan
Start-Sleep 2
}
function dependencyCheck {
## Check if git is installed
if ( Get-Command git -ErrorAction 'SilentlyContinue' ) {
Write-Host "`nGit is installed`n`tGood." -ForegroundColor Green
} else {
Write-Host "`nGit is NOT installed`n`tInstall Git and try again." -ForegroundColor Red
Write-Host "Done." -ForegroundColor Green
Exit
}
## Check internet connectivity
$pingPass = Test-Connection -ComputerName "google.com" -Count 3 -Quiet
if ( $pingPass ) {
Write-Host "`nInternet Works.`n`tGood." -ForegroundColor Green
} else {
Write-Host "`nPing failed.`n`tGet online and try again." -ForegroundColor Red
Write-Host "Done." -ForegroundColor Green
Exit
}
}
function cloneGists {
## Make gist dir if needed
$myGistDir = "C:$env:HOMEPATH\gist.github\mezcel"
#$myGistDir = "~\gist.github\mezcel"
New-Item -ItemType Directory -Force -Path $myGistDir
Start-Sleep 1
Write-Host "`nCloneing gists.`n" -ForegroundColor Cyan
## Clone gists if they do not exist
git clone https://gist.github.com/eab7764d1f9e67d051fd59ec7ce3e066.git "$myGistDir\git-notes.gist"
git clone https://gist.github.com/c90ce696785821d1921f8c2104fb60d3.git "$myGistDir\stations.gist"
git clone https://gist.github.com/72730d0c2f8cd8b7e0491188df6fa0f0.git "$myGistDir\tmux-notes.gist"
git clone https://gist.github.com/7293290230cda8dc69d1ad0a67ad4250.git "$myGistDir\vim-notes.gist"
git clone https://gist.github.com/7bf48505cc0440f7a5ff08340ecb24bd.git "$myGistDir\atomio-notes.gist"
git clone https://gist.github.com/62f85669d9d901d364f3779198e1f5b6.git "$myGistDir\c-snipits.gist"
git clone https://gist.github.com/f374a42c197ba9d2d41cd1d6b95f9496.git "$myGistDir\tmp-gist.gist"
git clone https://gist.github.com/2cc404f78d2488f02394c81d30047b2d.git "$myGistDir\nodejs-notes.gist"
git clone https://gist.github.com/fa9f298a0e02ff8f7afa02b05f2804f8.git "$myGistDir\python-notes.gist"
git clone https://gist.github.com/34895a5ae768873a26e762e068394a84.git "$myGistDir\powershell-notes.gist"
git clone https://gist.github.com/4be2de2cb400dd7f781c721c19e3b99b.git "$myGistDir\vscode-notes.gist"
git clone https://gist.github.com/247eda1319b9e1815cad7b955fdcc379.git "$myGistDir\notepadpp-notes.gist"
Write-Host "`nDone cloneing gists." -ForegroundColor Cyan
}
function cloneGithub {
## Make gist dir if needed
$myGistDir = "C:$env:HOMEPATH\github\mezcel"
#$myGistDir = "~\github\mezcel"
New-Item -ItemType Directory -Force -Path $myGistDir
Start-Sleep 1
Write-Host "`nCloneing github.`n" -ForegroundColor Cyan
## Clone gists if they do not exist
git clone https://github.com/mezcel/electron-container.git "$myGistDir\electron-container.git"
git clone https://github.com/mezcel/printf-time.git "$myGistDir\printf-time.git"
git clone https://github.com/mezcel/jq-tput-terminal.git "$myGistDir\jq-tput-terminal.git"
#git clone https://github.com/mezcel/carousel-score.git "$myGistDir\carousel-score.git"
git clone https://github.com/mezcel/python-curses.git "$myGistDir\python-curses.git"
#git clone https://github.com/mezcel/catechism-scrape.git "$myGistDir\catechism-scrape.git"
git clone https://github.com/mezcel/wicked-curse.git "$myGistDir\wicked-curse.git"
git clone https://github.com/mezcel/simple-respin.git "$myGistDir\simple-respin.git"
git clone https://github.com/mezcel/terminal-profile.git "$myGistDir\terminal-profile.git"
git clone https://github.com/mezcel/keyboard-layout.git "$myGistDir\keyboard-layout.git"
git clone https://github.com/mezcel/bookmark-renderer.git "$myGistDir\bookmark-renderer.git"
Write-Host "`nDone cloneing github." -ForegroundColor Cyan
}
function pullRepos ( [string] $myGistDir ) {
Write-Host "`nPulling $myGistDir repos.`n" -ForegroundColor Cyan
## Array of Dirs present in repo dir
$repoArr = Get-ChildItem -Path $myGistDir | Where-Object { $_.PSIsContainer } | Foreach-Object { $_.Name }
## Perform a pull on every repo
for ( $i = 0; $i -lt $repoArr.length; $i++ ) {
$repo = $repoArr[$i].ToString()
$repoPath = "$myGistDir\$repo"
## repo to update
Write-Host $repo -ForegroundColor Magenta
## cd into repo
Set-Location -Path $repoPath
git pull
}
Write-Host "`nDone pulling $myGistDir repos.`n" -ForegroundColor Cyan
}
function pullGists {
## Make gist dir if needed
$myGistDir = "C:$env:HOMEPATH\gist.github\mezcel"
New-Item -ItemType Directory -Force -Path $myGistDir
Start-Sleep 1
$currentDir = (Get-Item -Path ".\").FullName
pullRepos $myGistDir
## cd back to working dir
Set-Location -Path $currentDir
}
function pullGithub {
## Make gist dir if needed
$myGithubDir = "C:$env:HOMEPATH\github\mezcel"
New-Item -ItemType Directory -Force -Path $myGithubDir
Start-Sleep 1
$currentDir = (Get-Item -Path ".\").FullName
pullRepos $myGithubDir
## cd back to working dir
Set-Location -Path $currentDir
}
function main {
greetings
dependencyCheck
pullGists
cloneGists
pullGithub
cloneGithub
}
##############
## Run
##############
main
## Check radio status
#powershell Get-NetAdapterAdvancedProperty -Name "Wi-Fi" -AllProperties -RegistryKeyword "radioEnable"
## To turn radio on (run as administrator)
#powershell Set-NetAdapterAdvancedProperty -Name "Wi-Fi" -AllProperties -RegistryKeyword "radioEnable" -RegistryValue "1"
## To turn radio off (run as administrator)
#powershell Set-NetAdapterAdvancedProperty -Name "Wi-Fi" -AllProperties -RegistryKeyword "radioEnable" -RegistryValue "0"
## Get adapter property
Get-NetAdapter
If ( (Get-NetAdapter -Name 'Ethernet').Status -ne 'Connected' ) {
Get-NetAdapter | Disable-NetAdapter -Confirm:$false -AsJob | Wait-Job
Enable-NetAdapter -Name 'Wi-Fi'-Confirm:$false
Enable-NetAdapter -Name 'Ethernet 3' -Confirm:$false
}
<#
Test script used to convert a csv file to an html table
#>
function MultipleFiles {
param ( [string] $sourceDir, [string] $outFile )
$Files = Get-ChildItem -Path $sourceDir -Include *.csv
$HTML = foreach( $File in $Files ){
Import-Csv -Path $File.FullName | ConvertTo-Html -Fragment
}
$HTML |
Out-File -FilePath $outFile
}
function SingleFile {
param ( [string] $sourceFile, [string] $outFile )
$File = Get-ChildItem -Path $sourceFile
[string]$cssFile = "styles.css"
[string]$myStyles = "<link rel=`"stylesheet`" href=`"$cssFile`">"
Write-Host $myStyles
#Import-Csv -Path $File.FullName | ConvertTo-Html -Fragment | Out-File -FilePath $outFile
Import-Csv -Path $File.FullName | ConvertTo-Html -head $myStyles | Out-File -FilePath $outFile
}
## [string]$csvFile = Read-Host -Prompt "directory path"
$sourceFile="filePaths.csv"
$outFile="~/Downloads/index.html"
SingleFile $sourceFile $outFile
firefox-esr $outFile
:: Sell Service Tag Number
@ECHO off
ECHO Dell Service Tag Number: bios
ECHO ==============================
wmic bios get BIOSVersion,Manufacturer,TargetOperatingSystem,Name,SerialNumber
ECHO Architecture: computersystem
ECHO ==============================
wmic computersystem get Model,Name,Manufacturer,SystemType,CurrentTimeZone,Description,SystemFamily,SystemType,SystemSKUNumber
ECHO Monitors: desktopmonitor
ECHO ==============================
wmic desktopmonitor get DeviceID,ScreenWidth,ScreenHeight,MonitorType,DisplayType,Status,SystemName,MonitorManufacturer

extras

Curl Weather

## Region
(curl http://wttr.in/NewYork -UserAgent "curl" ).Content

## city
(curl http://wttr.in/"my_city,my_state" -UserAgent "curl" ).Content

## Moon
(curl wttr.in/Moon -UserAgent "curl" ).Content

Security Settings

PowerShell script to batch-change privacy settings in Windows 10

ID Name Path
1 Libre Office LibreOffice
2 Powershell PowerShell
3 GitBash Git-
4 Notepad++ npp
5 7zip 7z
6 VSCode VSCodeUserSetup
7 VLC vlc
8 Gimp gimp
[
{
Name: "7-zip",
InstallerPath: "7z",
InstalledPath: "C:\Program Files\7-Zip\7zFM.exe",
Command: ""
},
{
Name: "GIMP",
InstallerPath: "gimp"
InstalledPath: "C:\Program Files\GIMP 2\bin\gimp-2.10.exe",
Command: ""
},
{
Name: "Git",
InstallerPath: "Git",
InstalledPath: "C:\Program Files\Git\git-bash.exe",
Command: ""
},
{
Name: "LibreOffice",
InstallerPath: "LibreOffice",
InstalledPath: "C:\Program Files\LibreOffice\program\soffice.exe",
Command: ""
},
{
Name: "Notepad",
InstallerPath: "npp",
InstalledPath: "C:\Program Files\Notepad++\notepad++.exe",
Command: ""
},
{
Name: "PowerShell 7",
InstallerPath: "PowerShell",
InstalledPath: "C:\Program Files\PowerShell\7",
Command: ""
},
{
Name: "VLC media player",
InstallerPath: "vlc",
InstalledPath: "C:\Program Files\VideoLAN\VLC\vlc.exe",
Command: ""
},
{
Name: "VSCode",
InstallerPath: "VSCodeUserSetup",
InstalledPath: "C:\Users\mezcel\AppData\Local\Programs\Microsoft VS Code\Code.exe",
Command: "code"
}
]
Function Get-LoggedOnUser {
<#
.SYNOPSIS
Find out the current logged on user on a local or remote machine
.PARAMETER ComputerName
Provide remote computer name
.EXAMPLE
Get-LoggedOnUser
.EXAMPLE
Get-LoggedOnUser -ComputerName COMPUTERNAME-D
SOURCE:
https://www.joseespitia.com/category/scripting/powershell/
#>
param (
[parameter(Mandatory=$False)]
[ValidateNotNullOrEmpty()]$ComputerName
)
If($ComputerName -eq $Null) {
$Username = (Get-Process Explorer -IncludeUsername | Where-Object { $_.Username -notlike "*SYSTEM" }).Username
}
Else {
$Username = (Invoke-Command {Get-Process Explorer -IncludeUsername | Where-Object { $_.Username -notlike "*SYSTEM" }} -ComputerName $ComputerName).Username
}
Return $Username
}
*.ps1 eol=crlf
#!/bin/bash
## Installation via Direct Download - Debian 10
## Download the tar.gz package powershell-7.1.3-linux-x64.tar.gz from the releases page onto the Debian machine.
## https://docs.microsoft.com/en-us/powershell/scripting/install/installing-powershell-core-on-linux?view=powershell-7.1#debian-10
function direct_dl {
## https://github.com/PowerShell/PowerShell/releases/tag/v7.1.3
## https://github.com/PowerShell/PowerShell/releases/download/v7.1.3/powershell_7.1.3-1.debian.10_amd64.deb
sudo apt-get update
# install the requirements
sudo apt-get install -y \
less \
locales \
ca-certificates \
libicu63 \
libssl1.1 \
libc6 \
libgcc1 \
libgssapi-krb5-2 \
liblttng-ust0 \
libstdc++6 \
zlib1g \
curl
# Download the powershell '.tar.gz' archive
curl -L https://github.com/PowerShell/PowerShell/releases/download/v7.1.3/powershell-7.1.3-linux-x64.tar.gz -o /tmp/powershell.tar.gz
# Create the target folder where powershell will be placed
sudo mkdir -p /opt/microsoft/powershell/7
# Expand powershell to the target folder
sudo tar zxf /tmp/powershell.tar.gz -C /opt/microsoft/powershell/7
# Set execute permissions
sudo chmod +x /opt/microsoft/powershell/7/pwsh
# Create the symbolic link that points to pwsh
sudo ln -s /opt/microsoft/powershell/7/pwsh /usr/bin/pwsh
# Start PowerShell
pwsh
}
function aptPackage {
cd ~/Downloads/
## Download the Microsoft repository GPG keys
wget https://packages.microsoft.com/config/debian/10/packages-microsoft-prod.deb &&
## Register the Microsoft repository GPG keys
sudo dpkg -i packages-microsoft-prod.deb
## Update the list of products
sudo apt-get update
## Install PowerShell
sudo apt-get install -y powershell
## Start PowerShell
#pwsh
}
thisDir=$(pwd)
mkdir -p ~/Downloads/
cd ~/Downloads/
aptPackage
cd $thisDir
#!/bin/bash
# Download the Microsoft repository GPG keys
if [ ! -f packages-microsoft-prod.deb ]; then
wget https://packages.microsoft.com/config/debian/10/packages-microsoft-prod.deb
fi
# Register the Microsoft repository GPG keyssudo
if [ -f packages-microsoft-prod.deb ]; then
sudo dpkg -i packages-microsoft-prod.deb
# Update the list of products
sudo apt-get update
# Install PowerShell
sudo apt-get install -y powershell
fi
# Start PowerShell
#pwsh
<#
C:\ProgramData\Dell\UpdatePackage\Log
#>
function DisplayAvailableDrives {
## list drives
Write-Host "Available Drives:" -ForegroundColor Cyan
Get-PSDrive -PSProvider FileSystem
Write-Host ""
}
function ChangeTerminalPrompt {
## Custom prompt
function prompt { "PS $pwd> " }
}
function IsPath ( [string] $dirPath ) {
#[string]$dirPath = Read-Host -Prompt 'Input directory path'
#$dirPath = "~\Downloads"
[bool]$isDir = $false
if ( $dirPath ) {
$isDir = Test-Path "$dirPath"
} else {
Write-Host "Path does not exist." -ForegroundColor Red
}
Write-Output $isDir
}
function CsvToArray( [string] $filePath ) {
[bool]$isDir = IsPath( $filePath )
[string]$MyArr = @()
if ( $isDir -eq $true ) {
Get-ChildItem $filePath -Recurse -Include ("*.msi", "*.exe")
$MyArr = Get-ChildItem $filePath -Recurse -Include ("*.msi", "*.exe")
Write-Host $MyArr -ForegroundColor Yellow
Write-Host "`tMyArr[0]:" $MyArr[0] -ForegroundColor Yellow
Write-Host "`tMyArr[1]:" $MyArr[1] -ForegroundColor Yellow
Write-Host "`tMyArr[2]:" $MyArr[2] -ForegroundColor Yellow
}
}
function ReturnNewestExecutable ( [string] $softwareDir ) {
## Sort for the newest executable version
[string] $largestVersion = Get-ChildItem $softwareDir -Include ("*.exe", "*.msi") | Sort-Object $softwareDir -Descending | Select-Object -First 1
Write-Output $largestVersion
}
function ParseCsvFile( [string] $filePath ) {
[bool]$isFile = IsPath( $filePath )
if ( $isFile ) {
## Parse a csv file
#Get-Content -Path ""
$Newlist = Import-Csv $filePath | Add-Member -MemberType noteproperty -Name Results -Value "success" -PassThru | Select-Object ID, Name, Path
$verynew = $Newlist | Select-Object -Property ID, Name, Path | Select-Object -Property ID, Name, Path
Write-Host "Parse CSV" -ForegroundColor Blue
foreach($item in $verynew)
{
Write-Host D:\FreshStart\$($item.Name) D:\FreshStart\$($item.Path)
}
}
}
function RunExecutable ( [string] $ExePath ) {
[bool]$isFile = IsPath( $ExePath )
if ( $isFile -eq $true ) {
Write-Host "Launch $ExePath" -ForegroundColor Cyan
#Invoke-Expression $ExePath
Start-Process -wait $ExePath
} else {
Write-Host "Can't launch $ExePath" -ForegroundColor Red
}
}
function ReturnExeVersion( [string] $exePath ) {
[string] $versionNo = (Get-Item $exePath ).VersionInfo.FileVersion
#Write-Output $versionNo
return $versionNo
}
function ReturnMsiVersion( [string] $msiPath ) {
try {
$FullPath = (Resolve-Path $msiPath).Path
$windowsInstaller = New-Object -com WindowsInstaller.Installer
$database = $windowsInstaller.GetType().InvokeMember(
"OpenDatabase", "InvokeMethod", $Null,
$windowsInstaller, @($FullPath, 0)
)
$q = "SELECT Value FROM Property WHERE Property = 'ProductVersion'"
$View = $database.GetType().InvokeMember(
"OpenView", "InvokeMethod", $Null, $database, ($q)
)
$View.GetType().InvokeMember("Execute", "InvokeMethod", $Null, $View, $Null)
$record = $View.GetType().InvokeMember(
"Fetch", "InvokeMethod", $Null, $View, $Null
)
$productVersion = $record.GetType().InvokeMember(
"StringData", "GetProperty", $Null, $record, 1
)
$View.GetType().InvokeMember("Close", "InvokeMethod", $Null, $View, $Null)
return $productVersion
} catch {
throw "Failed to get MSI file version the error was: {0}." -f $_
}
}
function ParseJsonFile ( [string] $jsonFilePath, [string] $softwareDir ) {
[bool]$isJsonFile = IsPath( $jsonFilePath )
[bool]$isExecFile = IsPath( $softwareDir )
if ( $isJsonFile -and $isExecFile ) {
## Import a json file
$JSONContent = Get-Content -Raw -Path $jsonFilePath | ConvertFrom-JSON
#Write-Host "Json to Table"
$JSONContent | Format-Table | Out-Null
#$JSONContent = $JSONContent | Format-Table -Property Path
foreach( $item in $JSONContent ) {
#Write-Host $softwareDir\$($item.Name) $softwareDir\$($item.Path)
[string] $ExePath = "$softwareDir\$($item.Path)*"
$ExePath = ReturnNewestExecutable($ExePath)
if ( $ExePath -like "*.exe" ) {
[string] $versionNo = ReturnExeVersion($ExePath)
# extract file version from file name string
if ( -not $versionNo ) {
$versionNo = $ExePath -replace '\D+([0-9]*).*', '$1'
}
} elseif ($ExePath -like "*.msi" ) {
[string] $versionNo = ReturnMsiVersion($ExePath)
}
$isInstalled = IsInstalled "~\Downloads\InstalledApps.txt" "$($item.Name)"
if ( -not $isInstalled) {
if ( Get-Command code -ErrorAction 'SilentlyContinue' ) {
Write-Host " $($item.Path) is installed. `tv $versionNo" -ForegroundColor Yellow
$isInstalled = $true
} else {
Write-Host " $($item.Name) is Not installed: $isInstalled" -ForegroundColor Green
#$isInstalled = Check_Program_Installed( $($item.Name) )
#Write-Host "`tIs Not installed: $isInstalled" -ForegroundColor Green
RunExecutable( $ExePath )
}
} else {
Write-Host " $($item.Path) is installed. `tv $versionNo" -ForegroundColor Yellow
}
}
}
}
function WriteFile_Applications( [string] $filePath ) {
Write-Host "`nGenerating file listing installed applications (please wait) ..." -ForegroundColor Cyan
# paths: x86 and x64 registry keys are different
if ( [IntPtr]::Size -eq 4 ) {
$path = 'HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall\*'
} else {
$path = @(
'HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall\*'
'HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\*'
)
}
#Get-ItemProperty $path
# get all data
Get-ItemProperty $path |
# use only with name and unistall information
.{ process { if ( $_.DisplayName -and $_.UninstallString ) { $_ } } } |
#select more or less common subset of properties
#Select-Object DisplayName, Publisher, InstallDate, DisplayVersion, HelpLink, UninstallString | Sort-Object DisplayName | Out-File $filePath
Select-Object DisplayName, DisplayVersion, InstallSource, Publisher | Sort-Object DisplayName | Out-File $filePath
Write-Host "`nScanning complete. Check $filePath" -ForegroundColor Cyan
}
function Check_Program_Installed( [string] $programName ) {
$x86_check = ((Get-ChildItem "HKLM:SoftwareMicrosoftWindowsCurrentVersionUninstall") |
Where-Object { $_."Name" -like "*$programName*" } ).Length -gt 0;
if(Test-Path 'HKLM:SoftwareWow6432NodeMicrosoftWindowsCurrentVersionUninstall') {
$x64_check = ((Get-ChildItem "HKLM:SoftwareWow6432NodeMicrosoftWindowsCurrentVersionUninstall") |
Where-Object { $_."Name" -like "*$programName*" } ).Length -gt 0;
}
return $x86_check -or $x64_check;
}
function DetectCorruption() {
[bool] $isAdmin = IsAdmin
if ( $isAdmin ) {
Write-Host "`nScanning for corrupted installations (please wait) ..." -ForegroundColor Cyan
sfc /SCANNOW
} else {
Write-Host "Powershell needs to be in Administrator mode to scan for corrupted installations." -ForegroundColor Red
}
}
function WriteFile_Drivers( [string] $filePath ) {
Write-Host "`nGenerating file listing driver information (please wait) ..." -ForegroundColor Cyan
#Get-WindowsDriver -Online -All | Out-File $filePath
Get-WindowsDriver -Online -All |
.{process{ if ($_.Driver -and $_.Version) { $_ } }} |
Select-Object Driver, Version | Sort-Object Driver | Out-File $filePath
Write-Host "`nScanning complete. Check $filePath" -ForegroundColor Cyan
}
function IsVersionMatch( [string] $filePath, [string] $execString, [string] $versionString ) {
# grep version from list file
Select-String -Path $filePath -Pattern $versionString
}
function IsInstalled( [string] $filePath , [string] $stringMatch ) {
[string] $matchString = Select-String -Path "$filePath" -Pattern "$($stringMatch)"
[bool] $isInstalled = $false
If ( $matchString ) { $isInstalled = $true }
Write-Output $isInstalled
}
function InstallExternalApps() {
[string] $demoJson = ".\filePaths.json"
[string] $demoDir = "D:\FreshStart"
[string] $jsonFilePath = Read-Host -Prompt "Input JSON file path [ $demoJson ]"
If ( -not $jsonFilePath ) { $jsonFilePath = "$demoJson" }
[bool]$isPath = IsPath( $jsonFilePath )
if ( -not $isPath ) { Write-Host "Json path not found $($jsonFilePath)" -ForegroundColor Red }
Write-Host $jsonFilePath
Write-Host ""
[string] $softwareDir = Read-Host -Prompt "Input software directory [ $demoDir ]"
If ( -not $softwareDir ) { $softwareDir = "$demoDir" }
[bool]$isPath = IsPath( $softwareDir )
if ( -not $isPath ) { Write-Host "Software directory path not found $softwareDir" -ForegroundColor Red }
Write-Host $softwareDir
Write-Host ""
ParseJsonFile $jsonFilePath $softwareDir
}
function IsAdmin() {
## Detect if PowerShell is running as administrator
[bool] $isAdmin = [bool](([System.Security.Principal.WindowsIdentity]::GetCurrent()).groups -match "S-1-5-32-544")
Write-Output $isAdmin
}
function Main {
DisplayAvailableDrives
InstallExternalApps
WriteFile_Applications( "~\Downloads\InstalledApps.txt" )
#WriteFile_Drivers( "~\Downloads\HardwareDrivers.txt" )
}
Main
<#
interface_con.ps1
About:
Turn on wifi and connect to an SSID for internet.
Or Turn off wifi
Git:
https://gist.github.com/mezcel/34895a5ae768873a26e762e068394a84#file-interface_con-ps1
#>
## External argument inputs
param( $flagArg, $ssidArg )
function testPing {
Start-Sleep 2
$pingAddr = "google.com"
Write-Host "`nPinging $pingAddr ...`n" -ForegroundColor Cyan
$pingPass = Test-Connection -ComputerName $pingAddr -Count 3 -Quiet
if ( $pingPass ) {
Write-Host " Ping Pass`n" -ForegroundColor Green
} else {
Write-Host " Ping Fail`n" -ForegroundColor Red
}
return $pingPass
}
function ssidPicker {
## grep and select a deteted ssid
Write-Host "Available SSID's:" -ForegroundColor DarkYellow
$ssidList = netsh wlan show network | Select-String "SSID"
$listLength = $ssidList.length
if ( $listLength -gt 0 ) {
for ($i=1; $i -le $listLength; $i++) {
$ssidString = $ssidList[$i-1]
Write-Host "`t$ssidString" -ForegroundColor Yellow
}
$idx = Read-Host "`nSelect an SSID No [ 1 - $listLength ] "
$idx=$idx-1
$selectedSsid = $ssidList[$idx]
$selectedSsid = ($selectedSsid -split ": ")[1]
Write-Host "`nYou selected: $selectedSsid" -ForegroundColor Green
Write-Host " Connecting ...`n" -ForegroundColor Cyan
netsh wlan connect name=$selectedSsid
testPing
}
}
function wifiStatus {
## View list of avilable wifi net adapters (Typically most Win10 computers have 1 Wi-Fi)
Get-NetAdapter | SELECT Name, InterfaceDescription, Status | WHERE Name -eq Wi-Fi
## check if Status is up
$statusQuery = Get-NetAdapter | SELECT Name, Status | WHERE Name -eq Wi-Fi
$statusString = $statusQuery.Status
if ( $statusString -ne "Up" ) {
## Redundant double check
## Enable Wifi adapter if NIC is manually turned on allready
Enable-NetAdapter -Name "Wi-Fi" -Confirm:$false
Start-Sleep 3
$statusQuery = Get-NetAdapter | SELECT Name, Status | WHERE Name -eq Wi-Fi
$statusString = $statusQuery.Status
if ( $statusString -ne "Up" ) {
Write-Host "NetAdapter status is $statusString" -ForegroundColor Red
Write-Host "`tManually turn on the Wireles NIC and try this script again." -ForegroundColor Red
Write-Host "Tip:`n`tNavigate to Settings --> Wi-Fi settings`n" -ForegroundColor Red
$yn = Read-Host "Do you want to automatically navigate to and open the Wi-Fi Setting now? [ y/N ]"
if ( $yn -eq "y" ) {
## guidance: https://ss64.com/nt/syntax-settings.html
Start-Process "ms-settings:network-wifi"
}
Write-Host "Exiting script now.`n" -ForegroundColor Green
Exit
}
} else {
Write-Host "NetAdapter status is $statusString `n" -ForegroundColor DarkYellow
}
}
function connman () {
ssidPicker
wifiStatus
}
function greeting ( [string] $scriptName ) {
Write-Host "About:`n`tConnect or disconnect to/from Wifi internet." -ForegroundColor Magenta
Write-Host "Flags:`n`tIf you know the SSID you want to connect to." -ForegroundColor Magenta
Write-Host "`tNext time use the --ssid flag to skip prompts" -ForegroundColor Magenta
Write-Host "`tExample:" -ForegroundColor Magenta
Write-Host "`t`t.\$scriptName --ssid KnownSSIDName" -ForegroundColor Magenta
Write-Host "Source code:`n`thttps://gist.github.com/mezcel/34895a5ae768873a26e762e068394a84#file-interface_con-ps1" -ForegroundColor Magenta
}
function main ([string] $flagArg, [string] $ssidArg, [string] $scriptName) {
greeting $scriptName
$testNet = testPing
if ( $testNet -ne "True" ) {
## connect
if ( $flagArg -eq "--ssid" ) {
## connect to a known ssid
Write-Host "Attempt to connect to $ssidArg ..." -ForegroundColor Cyan
Enable-NetAdapter -Name "Wi-Fi" -Confirm:$false
netsh wlan connect name=$ssidArg
testPing
} else {
## find an ssid to connect to
connman
}
} else {
Write-Host "You should already be connected to wifi internet." -ForegroundColor DarkYellow
$yn = Read-Host "Disconnect from wifi? [ y/N ]"
if ( $yn -eq "y" ) {
## disconnect
netsh wlan disconnect interface="Wi-Fi"
#Disable-NetAdapter -Name "Wi-Fi" -Confirm:$false
Write-Host "`nWi-fi should be off now.`n" -ForegroundColor Green
} else {
Write-Host "You entered $yn, nothing will be done.`n" -ForegroundColor Red
}
}
}
##############
## Run
##############
$scriptName = $MyInvocation.MyCommand.Name
main $flagArg $ssidArg $scriptName
::
:: Kill known background process and turn off computer
::
:: Kill steam
cmd /k taskkill /f /im "C:\Program Files (x86)\Steam\Steam.exe"
:: Kill gamebar
cmd /k taskkill /f /im GameBar.exe
cmd /k taskkill /f /im RuntimeBarker.exe
:: Kill ms-edge
cmd /k taskkill /f /im MicrosoftEdge.exe /t
:: Kill Cortana
cmd /k taskkill /f /im SearchUI.exe /t
:::: Shutdown
@echo OFF
ECHO "Choose an option .."
ECHO "1 = Logoff"
ECHO "2 = Reboot"
ECHO "3 = Hibernate"
ECHO "4 = Shutdown"
ECHO "5 = Do Nothing"
SET /p option=Choose one option-
IF %option%==1 SHUTDOWN /l
IF %option%==2 SHUTDOWN -r -t 10
IF %option%==3 SHUTDOWN /h
IF %option%==4 SHUTDOWN /s /f /t 0
IF %option%==5 Exit
PAUSE
<#
# This is a super **SIMPLE** example of how to create a very basic powershell webserver
Code derived from:
https://gist.githubusercontent.com/19WAS85/5424431/raw/3a827c9f4e4065fd4550421fbbc4ad68ddf2adab/powershell-web-server.ps1
#>
# Http Server
$http = [System.Net.HttpListener]::new()
# Hostname and port to listen on
$http.Prefixes.Add("http://localhost:8080/")
# Start the Http Server
$http.Start()
# Log ready message to terminal
if ($http.IsListening) {
write-host " HTTP Server Ready! " -f 'black' -b 'gre'
write-host "now try going to $($http.Prefixes)" -f 'y'
write-host "then try going to $($http.Prefixes)other/path" -f 'y'
}
# INFINTE LOOP
# Used to listen for requests
while ($http.IsListening) {
# Get Request Url
# When a request is made in a web browser the GetContext() method will return a request object
# Our route examples below will use the request object properties to decide how to respond
$context = $http.GetContext()
# ROUTE EXAMPLE 1
# http://127.0.0.1/
if ($context.Request.HttpMethod -eq 'GET' -and $context.Request.RawUrl -eq '/') {
# We can log the request to the terminal
write-host "$($context.Request.UserHostAddress) => $($context.Request.Url)" -f 'mag'
# the html/data you want to send to the browser
# you could replace this with: [string]$html = Get-Content "C:\some\path\index.html" -Raw
[string]$html = "
<h1>A Powershell Webserver</h1>
<p>home page</p>
<a href='./some/form'>Form Link</a> <code>./some/form</code>
"
#resposed to the request
$buffer = [System.Text.Encoding]::UTF8.GetBytes($html) # convert htmtl to bytes
$context.Response.ContentLength64 = $buffer.Length
$context.Response.OutputStream.Write($buffer, 0, $buffer.Length) #stream to broswer
$context.Response.OutputStream.Close() # close the response
}
# ROUTE EXAMPLE 2
# http://127.0.0.1/some/form'
if ($context.Request.HttpMethod -eq 'GET' -and $context.Request.RawUrl -eq '/some/form') {
# We can log the request to the terminal
write-host "$($context.Request.UserHostAddress) => $($context.Request.Url)" -f 'mag'
[string]$html = "
<h1>A Powershell Webserver</h1>
<form action='/some/post' method='post'>
<p>A Basic Form</p>
<p>fullname</p>
<input type='text' name='fullname'>
<p>message</p>
<textarea rows='4' cols='50' name='message'></textarea>
<br>
<input type='submit' value='Submit'>
</form>
"
#resposed to the request
$buffer = [System.Text.Encoding]::UTF8.GetBytes($html)
$context.Response.ContentLength64 = $buffer.Length
$context.Response.OutputStream.Write($buffer, 0, $buffer.Length)
$context.Response.OutputStream.Close()
}
# ROUTE EXAMPLE 3
# http://127.0.0.1/some/post'
if ($context.Request.HttpMethod -eq 'POST' -and $context.Request.RawUrl -eq '/some/post') {
# decode the form post
# html form members need 'name' attributes as in the example!
$FormContent = [System.IO.StreamReader]::new($context.Request.InputStream).ReadToEnd()
# We can log the request to the terminal
write-host "$($context.Request.UserHostAddress) => $($context.Request.Url)" -f 'mag'
Write-Host $FormContent -f 'Green'
# the html/data
[string]$html = "<h1>A Powershell Webserver</h1><p>Post Successful!</p>"
#resposed to the request
$buffer = [System.Text.Encoding]::UTF8.GetBytes($html)
$context.Response.ContentLength64 = $buffer.Length
$context.Response.OutputStream.Write($buffer, 0, $buffer.Length)
$context.Response.OutputStream.Close()
}
# powershell will continue looping and listen for new requests...
}
# Note:
# To end the loop you have to kill the powershell terminal. ctrl-c wont work :/
<#
Check for installed drivers
Get *.msi information
HID Event Filter Chipset_Driver_5TWCG_WN32_1.1.0.317_A01_01
Serial IO Driver Chipset_Driver_FC98F_WN32_30.100.1633.3_A02
I2C
Dynamic Platform and Thermal Framework Chipset_Driver_JTXD1_WN32_8.2.11000.2996_A04
Management Engine Components Chipset_Driver_P90F1_WN32_11.6.0.1035_A00
Realtek USB Memory Card Reader Driver Chipset_Driver_T6F1W_WN32_10.0.14393.31228_A05
Find SystemBIOS
#>
function ReturnObjectArr_MsiDesc {
param ( [string] $dirPath )
$fullPath = (Resolve-Path $dirPath).Path
Write-Host "# Make an array of objects containing file description name and file version." -ForegroundColor Green
## Array which will contain objects
$ObjArr = @()
#Get-ChildItem $fullPath -Include ("*.exe", "*.msi")
Get-ChildItem $fullPath | ForEach-Object {
# Declare a new object for the array
$AttrObject = [PSCustomObject] @{
Desc = ""
Version = ""
}
## get exe attribute meta from child item
[string] $attrString = [System.Diagnostics.FileVersionInfo]::GetVersionInfo($_).FileDescription
[string] $exeDesc = $attrString.Split(",")[0]
[string] $exeVeresion = $attrString.Split(",")[1]; ## Parse out the version number
$exeVeresion = $exeVeresion.Split(" ")[1]; ## Parse out the 1st white space from string
# Populate object variable
$AttrObject.Desc = $exeDesc
$AttrObject.Version = $exeVeresion
#Append Array
$ObjArr+=$AttrObject
}
Write-Host "# Returned the following array of objects:`n`t"-ForegroundColor Magenta
Write-Host "# "$ObjArr -ForegroundColor Magenta
$ObjArr | export-csv "ReturnObjectArr_MsiDesc.csv"
return $ObjArr
}
function GetInstalledWmi {
param( [string] $matchString )
# Display list of installed applications
Write-Host "`n# Get list of installed wmi drivers with matching name properties." -ForegroundColor Green
Write-Host "`# String Match: `"$matchString`"" -ForegroundColor Green
# Get list of installed wmi drivers with matching name properties
$WmiInfo = Get-WmiObject Win32_Product | Where { $_.Name -match $matchString }
[string] $installedName = $WmiInfo.Name
[string] $installedVersion = $WmiInfo.Version
Write-Host "`n# Match return or installed driver:" -ForegroundColor Yellow
Write-Host "# Name:`t`t"$installedName"" -ForegroundColor Yellow
Write-Host "# Version:`t"$installedVersion"" -ForegroundColor Yellow
Write-Host ""
}
function WriteFile_Applications( [string] $filePath ) {
$filePath = "WriteFile_Applications.txt"
Write-Host "`nGenerating file listing installed applications (please wait) ..." -ForegroundColor Cyan
# paths: x86 and x64 registry keys are different
if ( [IntPtr]::Size -eq 4 ) {
$path = 'HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall\*'
} else {
$path = @(
'HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall\*'
'HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\*'
)
}
#Get-ItemProperty $path
# get all data
<#
Get-ItemProperty $path |
# use only with name and unistall information
.{ process { if ( $_.DisplayName -and $_.UninstallString ) { $_ } } } |
#select more or less common subset of properties
#Select-Object DisplayName, Publisher, InstallDate, DisplayVersion, HelpLink, UninstallString | Sort-Object DisplayName | Out-File $filePath
Select-Object DisplayName, DisplayVersion, InstallSource, Publisher | Sort-Object DisplayName | Out-File $filePath
#>
Get-WindowsDriver -Online -All | .{process{ if ($_.Driver -and $_.Version) { $_ } }} | Select-Object Driver, Version | Sort-Object Driver | Out-File $filePath
#$AllData | WriteTextFile $filePath
#Get-WindowsDriver -Online -All | WriteCsvFile $filePath
Write-Host "`nScanning complete. Check $filePath" -ForegroundColor Cyan
}
function WriteTextFile {
param ( [string] $filePath )
$PipedInput = $_
$PipedInput | Out-File $filePath
}
function WriteCsvFile {
param ( [string] $filePath, [string] $propertyString )
$PipedInput = $_
$PipedInput | export-csv -Property $propertyString $filePath -NoTypeInformation
}
<# --------------------------------------------------------------------- #>
Clear-History
Clear-Host
Write-Host ""
Write-Host "# -----------------------------------------------------------------------------" -ForegroundColor Red
Write-Host "# msi-drivers.ps1 $(Get-Date)" -ForegroundColor Red
Write-Host "# -----------------------------------------------------------------------------" -ForegroundColor Red
Write-Host ""
Write-Host "# Read a directory for ChildItem executable files." -ForegroundColor Cyan
Write-Host "#`tExtract Description name and Varsion info from the files and store them in an array of objects." -ForegroundColor Cyan
# Make an array of objects containing *.exe attributes
[string] $msiDir = "D:\Software DL\Inspiron 15 7000 Drivers\Dell Driver Bundle Dec2017\*.exe"
Write-Host "`n# List children in parent directory:" -ForegroundColor Cyan
Get-ChildItem $msiDir -Include ("*.exe", "*.msi")
Write-Host "# Directory children:`n#`t$msiDir" -ForegroundColor Cyan
Write-Host ""
$ObjArr = ReturnObjectArr_MsiDesc $msiDir
Write-Host "`n# Query if a package executable in the directory is installed on the current system." -ForegroundColor Cyan
[int] $idx = 2
Write-Host "`n# Query Index:`t" $idx -ForegroundColor Yellow
Write-Host "# Query Desc:`t" $ObjArr[$idx].Desc -ForegroundColor Yellow
Write-Host "# Query Version:" $ObjArr[$idx].Version -ForegroundColor Yellow
Write-Host "# Query Length:`t" ($ObjArr.Length - 1) -ForegroundColor Yellow
## Parse out just the the name
$matchString = $ObjArr[$idx].Desc -split '(: )'
[string] $matchString = $matchString[2]
Write-Host "`n# Query if $matchString is installed." -ForegroundColor Cyan
# Check if file description is allready installed
GetInstalledWmi $ObjArr[$idx].Desc
#WriteFile_Applications "InstalledProgramms.csv"
## Write values text file
Remove-Item "GetInstalledWmi.txt"
#Write-Host "$installedName $installedVersion"
$Win32Product = Get-WmiObject Win32_Product
$Win32Product | Out-File "GetInstalledWmi.txt"
$Win32Product | Select-Object -Property Description, IdentifyingNumber, Version | export-csv "GetInstalledWmi.csv" -NoTypeInformation
if ( [IntPtr]::Size -eq 4 ) {
$path = 'HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall\*'
} else {
$path = @(
'HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall\*'
'HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\*'
)
}
Remove-Item "WriteFile_Applications.txt"
Get-ItemProperty $path | Select-Object -Property DisplayName, DisplayVersion, PSChildName | export-csv -NoTypeInformation "WriteFile_Applications.csv"
$file = "styles.css"
( Get-Content $file ) | ForEach-Object {
Write-Host "record: $_ "
}
Select-String -Path $file -pattern "td"
[int] $count = 0
( Select-String -Path $file -pattern "td" ) | ForEach-Object {
$count = $count + 1
Write-Host "$count record: $_ "
}

process notes

About

Notes regarding controlling the Win10 window manager.

killall

## kill process
Stop-Process -Name "< the process you want stopped >"

con down

## list of adapters
Get-NetAdapter

## Disable/Enable adapters
Disable-NetAdapter -Name "< my adapter >" -Confirm:$false
Enable-NetAdapter  -Name "< my adapter >" -Confirm:$false

Shutdown

Complete shutdown

shutdown /s /f /t 0

Power off

Stop-Computer

Enable PS scripts

Set-ExecutionPolicy RemoteSigned -Scope CurrentUser

Launch MS Apps

settings browser

guidance

## wifi configs
Start-Process "ms-settings:network-wifi"

## developers configs
Start-Process "ms-settings:developers"

## win10 update
Start-Process "ms-settings:windowsupdate"

microsoft Edge

start microsoft-edge:<web url>

## not tested, idk if these works

$wshell = NewObject -ComObject wscript.shell
$wshell.AppActive('<Website>')
Sleep 2
$wshell.SendKeys( '{Fill}' )

## Start in private mode

Start-Process -FilePath ( $Env:WinDir + "\explorer.exe" ) 
    -ArgumentList "shell:Appsfolder\Microsoft.MicrosoftRdge_8wekb3d8bbwe!MicrosoftEdge"
    Start-Sleep -Seconds 1
    [Sysytem.Windows.Forms.SendKeys]::SendWait( "^+{P}" )
<#PSScriptInfo
.VERSION 1.0.0.0
.GUID 084a184a-faa1-47e4-9f1a-5d9ecede68c3
.AUTHOR Jeffrey Snover
.COMPANYNAME
.COPYRIGHT
.TAGS
.LICENSEURI
.PROJECTURI
.ICONURI
.EXTERNALMODULEDEPENDENCIES
.REQUIREDSCRIPTS
.EXTERNALSCRIPTDEPENDENCIES
.RELEASENOTES
#>
<#
.DESCRIPTION
Set the desktop background to an RGB color.
The core of this code was produced by http://stackoverflow.com/users/3281719/wheatfairies who
published it http://stackoverflow.com/questions/25774494/powershell-make-desktop-background-changes-take-effect-immediately
#>
param(
[Parameter(Position=0)]
$R=255,
[Parameter(Position=1)]
$G=255,
[Parameter(Position=2)]
$B=255
)
$code = @'
using System;
using System.Drawing;
using System.Runtime.InteropServices;
using Microsoft.Win32;
namespace CurrentUser
{
public class Desktop
{
[DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]
private static extern int SystemParametersInfo(int uAction, int uParm, string lpvParam, int fuWinIni);
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern int SetSysColors(int cElements, int[] lpaElements, int[] lpRgbValues);
public const int UpdateIniFile = 0x01;
public const int SendWinIniChange = 0x02;
public const int SetDesktopBackground = 0x0014;
public const int COLOR_DESKTOP = 1;
public int[] first = {COLOR_DESKTOP};
public static void RemoveWallPaper()
{
SystemParametersInfo( SetDesktopBackground, 0, "", SendWinIniChange | UpdateIniFile );
RegistryKey regkey = Registry.CurrentUser.OpenSubKey("Control Panel\\Desktop", true);
regkey.SetValue(@"WallPaper", 0);
regkey.Close();
}
public static void SetBackground(byte r, byte g, byte b)
{
int[] elements = {COLOR_DESKTOP};
RemoveWallPaper();
System.Drawing.Color color = System.Drawing.Color.FromArgb(r,g,b);
int[] colors = { System.Drawing.ColorTranslator.ToWin32(color) };
SetSysColors(elements.Length, elements, colors);
RegistryKey key = Registry.CurrentUser.OpenSubKey("Control Panel\\Colors", true);
key.SetValue(@"Background", string.Format("{0} {1} {2}", color.R, color.G, color.B));
key.Close();
}
}
}
'@
try
{
Add-Type -TypeDefinition $code -ReferencedAssemblies System.Drawing.dll
}catch{
# An error is thrown if the type [CurrentUser.Desktop] is already created
# so we ignore it.
}
finally
{
[CurrentUser.Desktop]::SetBackground($R, $G, $B)
}
Function Set-WallPaper($Image) {
<#
.SYNOPSIS
Applies a specified wallpaper to the current user's desktop
.PARAMETER Image
Provide the exact path to the image
.EXAMPLE
Set-WallPaper -Image "C:\Wallpaper\Default.jpg"
SOURCE:
https://www.joseespitia.com/2017/09/15/set-wallpaper-powershell-function/
#>
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)
}
<#
Kill known background process and turn off computer
#>
## Kill steam
Stop-Process -ProcessName steam
Start-Sleep 1
## Kill gamebar
cmd /k taskkill /f /im GameBar.exe
cmd /k taskkill /f /im RuntimeBarker.exe
Start-Sleep 1
## Kill ms-edge
cmd /k taskkill /f /im MicrosoftEdge.exe /t
Start-Sleep 1
## Shutdown ?
Stop-Computer
/* Table style for a Powershell generated csv to html file */
th {
background-color: gray;
color: white;
}
td {
vertical-align: center;
}
table, th, td, tr {
border: 1px solid black;
}
<#
Warhammer 40K: Soulstorm Mods (Tested in Winter 2021)
Enable Poswershell Script:
Current instance only: "Set-ExecutionPolicy Bypass -Scope Process -Force"
Current User: "Set-ExecutionPolicy Bypass -Scope CurrentUser -Force"
Current Machine: "Set-ExecutionPolicy Unrestricted -Scope LocalMachine -Force"
Mod Homepages:
* Ultimate Appocalypse: https://www.moddb.com/mods/ultimate-apocalypse-mod
https://www.mediafire.com/file/kuivpyohwhacm0m/Ultimate_Apocalypse_1.89_Full_-_Unpack_&_Play.rar/file
* Unification Mod: https://www.moddb.com/mods/unification-mod-dawn-of-war-soulstorm/
* Dark Prophecy: https://www.gamefront.com/games/dawn-of-war-soulstorm/file/dark-prophecy-0-4-8
https://www.gamefront.com/games/dawn-of-war-soulstorm/file/dark-prophecy
* Tyranids: https://www.moddb.com/mods/tyranid-mod/downloads/tyranid-mod-v05b2-for-soulstorm
https://www.moddb.com/mods/tyranid-mod/downloads/tyranid-mod-v05b3
* Chaos Daemons: https://www.moddb.com/mods/daemons-mod/
* FreeUI: https://www.moddb.com/mods/unification-mod-dawn-of-war-soulstorm/downloads/freeui
* objective_points_SS: https://www.moddb.com/mods/unification-mod-dawn-of-war-soulstorm/downloads/objective-points-ss-v1742020-for-dowdc-and-dowss
## Conflicts:
You can add UM to DA, but not the other way arround
Tyranids v0.5.2 works on UA but not UM
Tyranids v0.5.3 works on UM but not UA
## Personalized Race Hacks: *.ai (Lua script)
Manually edit unit stats. I like to make the dreadnoughts, basic grey knights, and rhinos more durable.
C:\Program Files (x86)\Steam\steamapps\common\Dawn of War Soulstorm\UltimateApocalypse_THB\data\ai\races\<YOUR_RACE>\
C:\Program Files (x86)\Steam\steamapps\common\Dawn of War Soulstorm\Unification_Bugfix\Data\ai\races\<YOUR_RACE>\
#>
function InitializeGlobalVariables {
## Declare file path variable in an object
## Steam Soulstorm directory
$global:SSPaths = [PSCustomObject] @{
Tyranids = "C:\Program Files (x86)\Steam\steamapps\common\Dawn of War Soulstorm\Tyranids"
Tyranids_Art = "C:\Program Files (x86)\Steam\steamapps\common\Dawn of War Soulstorm\Tyranids_Art"
Tyranids_module = "C:\Program Files (x86)\Steam\steamapps\common\Dawn of War Soulstorm\Tyranids.module"
Tyranids_Art_module = "C:\Program Files (x86)\Steam\steamapps\common\Dawn of War Soulstorm\Tyranids_Art.module"
Tyranid_Mod_Uninstall = "C:\Program Files (x86)\Steam\steamapps\common\Dawn of War Soulstorm\Tyranid_Mod-Uninstall.exe"
TyranidsUninstall = "C:\Program Files (x86)\Steam\steamapps\common\Dawn of War Soulstorm\TyranidsUninstall.exe"
SteamName = "steam"
SteamExe = "C:\Program Files (x86)\Steam\Steam.exe"
SoulstormName = "soulstorm"
SoulstormExe = "C:\Program Files (x86)\Steam\steamapps\common\Dawn of War Soulstorm\Soulstorm.exe"
AiUa = "C:\Program Files (x86)\Steam\steamapps\common\Dawn of War Soulstorm\UltimateApocalypse_THB\data\ai\races\"
AiUm = "C:\Program Files (x86)\Steam\steamapps\common\Dawn of War Soulstorm\Unification_Bugfix\Data\ai\races\"
}
## My external storage containing Soulstorm mods
$global:DefaultModPaths = [PSCustomObject] @{
Tyranid_Mod_0_5b2 = "D:\Software DL\DOW Soulstorm MOD\Additional-Races\Race-Executables\Tyranid_Mod_0.5b2_Installer.exe"
Tyranid_Mod_0_5b3 = "D:\Software DL\DOW Soulstorm MOD\Additional-Races\Race-Executables\Tyranid_Mod_v0.5b3.exe"
}
}
function EditSourcePath {
[bool] $isTyranid_Mod_0_5b2 = IsPath $DefaultModPaths.Tyranid_Mod_0_5b2
[bool] $isTyranid_Mod_0_5b3 = IsPath $DefaultModPaths.Tyranid_Mod_0_5b3
if ( !$isTyranid_Mod_0_5b2 -and !$isTyranid_Mod_0_5b3 ) {
Write-Host " ## Modify Tyranid Mod installer path" -ForegroundColor Blue
Write-Host "`tDefault directory set by script:"
Write-Host "`t- Tyranid_Mod_0.5b2_Installer.exe`n`t"$DefaultModPaths.Tyranid_Mod_0_5b2""
Write-Host "`t- Tyranid_Mod_v0.5b3.exe`n`t"$DefaultModPaths.Tyranid_Mod_0_5b3""
Write-Host ""
[string] $promptString = " Enter the parent directory path for Tyranid_Mod_0.5b2_Installer.exe"
[string] $parentTyranid_Mod_0_5b2 = Read-Host -Prompt $promptString
#$parentTyranid_Mod_0_5b2 = "D:\Software DL\DOW Soulstorm MOD\Additional-Races\Race-Executables"
$promptString = " Enter the parent directory path for Tyranid_Mod_v0.5b3.exe`n`t[ $parentTyranid_Mod_0_5b2 ]"
[string] $parentTyranid_Mod_0_5b3 = Read-Host -Prompt $promptString
#$parentTyranid_Mod_0_5b3 = "D:\Software DL\DOW Soulstorm MOD\Additional-Races\Race-Executables"
# Redefine variables
$DefaultModPaths.Tyranid_Mod_0_5b2 = "$parentTyranid_Mod_0_5b2\Tyranid_Mod_0.5b2_Installer.exe"
$DefaultModPaths.Tyranid_Mod_0_5b3 = "$parentTyranid_Mod_0_5b3\Tyranid_Mod_v0.5b3.exe"
Write-Host ""
Remove-Variable -Name parentTyranid_Mod_0_5b2
Remove-Variable -Name parentTyranid_Mod_0_5b3
}
Remove-Variable -Name isTyranid_Mod_0_5b2
Remove-Variable -Name isTyranid_Mod_0_5b3
}
function About {
[bool] $isSteam = Test-Path $SSPaths.SteamExe
[bool] $isSS = Test-Path $SSPaths.SoulstormExe
[bool] $is5_2 = Test-Path $DefaultModPaths.Tyranid_Mod_0_5b2
[bool] $is5_3 = Test-Path $DefaultModPaths.Tyranid_Mod_0_5b3
Write-Host "---" -ForegroundColor Magenta
Write-Host " ## About" -ForegroundColor Blue
Write-Host " This is a script used to automate the Install/Uninstall configuration of the Tyranids Mod for `"Warhammer 40,000: Soulstorm`"." -ForegroundColor Magenta
Write-Host " Existing versions of the Tyrandids mod will be uninstalled before installing a Tyranid mod." -ForegroundColor Magenta
Write-Host " ## Dependencies:" -ForegroundColor Blue
## Flag true flase
if ( !$isSteam -or !$isSS ) {
Write-Host " Install necessary programs." -ForegroundColor DarkYellow
} else {
Write-Host " Steam dependency satisfied." -ForegroundColor DarkYellow
}
Write-Host " This script assume you have both Steam [$isSteam], and `"Warhammer 40,000: Soulstorm`" [$isSS], installed." -ForegroundColor Magenta
Write-Host " This script assume you have the Tyranid Mod installer." -ForegroundColor Magenta
Write-Host " [$is5_2] "$DefaultModPaths.Tyranid_Mod_0_5b2"" -ForegroundColor Magenta
Write-Host " [$is5_3] "$DefaultModPaths.Tyranid_Mod_0_5b3"" -ForegroundColor Magenta
## Flag true flase
if ( !$is5_2 -or !$is5_3 ) {
Write-Host " Modify file paths as necessary." -ForegroundColor DarkYellow
} else {
Write-Host " Tyranid dependency satisfied." -ForegroundColor DarkYellow
}
Write-Host "---" -ForegroundColor Magenta
Write-Host ""
Remove-Variable -Name isSteam
Remove-Variable -Name isSS
Remove-Variable -Name is5_2
Remove-Variable -Name is5_3
}
function IsPath {
param ( [string] $dirPath )
[bool] $isDir = $false
if ( $dirPath ) {
$isDir = Test-Path "$dirPath"
} else {
Write-Host "Path does `"$dirPath`" not exist." -ForegroundColor Red
}
return $isDir
}
<# Lanuch *.exe file #>
function RunExecutable {
param ( [string] $ExePath )
[bool] $isFile = IsPath $ExePath
if ( $isFile -eq $true ) {
Write-Host " Launch $ExePath" -ForegroundColor Cyan
Write-Host ""
Start-Process -wait $ExePath -ErrorVariable ErrorFlag -ErrorAction SilentlyContinue -Verb RunAs
## Quit installer is installer was canceld by user or there was an administator privalege block.
if ( $ErrorFlag ) {
Write-Host "Canceled Tyranid modification because you aborted the following executable." -BackgroundColor Red -ForegroundColor Black
Write-Host " $ExePath" -BackgroundColor Red -ForegroundColor Black
Exit
}
} else {
Write-Host ""
Write-Host " Can't launch $ExePath`n`tFile path does not exist.`n" -ForegroundColor Red
}
Write-Host " 3 sec. pause ...`n" -ForegroundColor Blue
Start-Sleep 3
Remove-Variable -Name isFile
}
function MenuPrompt {
## Is the tyranids mod installed
[bool] $isTyranids = IsPath $SSPaths.Tyranids
[bool] $isTyranids_Art = IsPath $SSPaths.Tyranids_Art
if ( $isTyranids_Art ) {
Write-Host " Tyranid_Mod_v0.5b3 is installed.`n`tCurrently UM compatible, yet not UA compatible.`n" -ForegroundColor Green
[string] $defaulAnswer = "1"
} elseif ( $isTyranids ) {
Write-Host " Tyranid_Mod_v0.5b2 is installed.`n`tCurrently UA compatible, yet not UM compatible.`n" -ForegroundColor Green
[string] $defaulAnswer = "2"
} else {
Write-Host "The Tyranid Mod is not installed.`n" -ForegroundColor Red
[string] $defaulAnswer = "1"
}
[string] $promptString = " Select modification option:`n 1.`t`tInstall Tyranid_Mod_v0.5b2 [UA]`n 2.`t`tInstall Tyranid_Mod_v0.5b3 [UM]`n edit.`t`tOpen race *.ai Lua for editing.`n no.`t`tCancel installer`n`n Enter selection value ( 1, 2, edit, no ) [ default = $defaulAnswer ]"
## Prompt to switch tyranid installation
$promptAnswer = Read-Host -Prompt "$promptString"
if ( $promptAnswer -eq "" ) {
$promptAnswer = $defaulAnswer.Substring(0, 1).ToLower()
} else {
$promptAnswer = $promptAnswer.Substring(0, 1).ToLower()
}
Write-Host ""
Remove-Variable -Name isTyranids
Remove-Variable -Name isTyranids_Art
Remove-Variable -Name defaulAnswer
Remove-Variable -Name promptString
return $promptAnswer
}
function TerminateSoulstorm {
param ( [string] $processName )
$runningProcess = Get-Process -Name "$processName" -ErrorAction SilentlyContinue
if ( $runningProcess ) {
$runningProcess.CloseMainWindow()
Write-Host " 3 sec. pause ...`n" -ForegroundColor Blue
Start-Sleep 3
}
if ( !$runningProcess.HasExited ) {
$runningProcess | Stop-Process -Force
} else {
Write-Host " Killed $processName ..." -ForegroundColor Yellow
}
Remove-Variable -Name runningProcess
}
function OpenLuaDir {
[bool] $isTyranids = IsPath $SSPaths.Tyranids
[bool] $isTyranids_Art = IsPath $SSPaths.Tyranids_Art
if ( $isTyranids_Art ) {
Write-Host " Opening Lua script directory for UM." -ForegroundColor Black -BackgroundColor Cyan
Invoke-Item $SSPaths.AiUm
} elseif ( $isTyranids ) {
Write-Host " Opening Lua script directory for UA." -ForegroundColor Black -BackgroundColor Cyan
Invoke-Item $SSPaths.AiUa
} else {
Write-Host " Missing Tyranid dependencies for both UA and UM." -Red
}
Remove-Variable -Name isTyranids
Remove-Variable -Name isTyranids_Art
}
function IsTyranidRemoved {
# Confirm deletion of old Tyranic mod
[bool] $isTyranids = IsPath $SSPaths.Tyranids
[bool] $isTyranids_Art = IsPath $SSPaths.Tyranids_Art
[bool] $isTyranids_Art_module = IsPath $SSPaths.Tyranids_Art_module
if ( $isTyranids -or $isTyranids_Art -or $isTyranids_Art_module ) {
Write-Host " Previous Tyranids files still exist in Soulstorm directory.`n" -ForegroundColor Red
[bool] $IsRemoved = $false
} else {
Write-Host " No Tyranid Mod in Soulstorm directory.`n" -ForegroundColor Green
[bool] $IsRemoved = $true
}
Remove-Variable -Name isTyranids
Remove-Variable -Name isTyranids_Art
Remove-Variable -Name isTyranids_Art_module
Return $IsRemoved
}
function InstallTyrandsUM {
[string] $installPath = $DefaultModPaths.Tyranid_Mod_0_5b3
## Terminate Steam Game
TerminateSoulstorm $SSPaths.SoulstormName
TerminateSoulstorm $SSPaths.SteamName
# Uninstall
Write-Host " Uninstalling Tyranids" -BackgroundColor Yellow -ForegroundColor Black
RunExecutable $SSPaths.Tyranid_Mod_Uninstall
RunExecutable $SSPaths.TyranidsUninstall
# Confirm deletion of old Tyranic mod
[bool] $isUninstalled = IsTyranidRemoved
# Install Tyranid_Mod_v0.5b3
if ( $isUninstalled ) {
[string] $installPath = $DefaultModPaths.Tyranid_Mod_0_5b3
Write-Host " Installing Tyranids > $installPath" -BackgroundColor Green -ForegroundColor Black
RunExecutable "$installPath"
} else {
Write-Host " Script aborted.`n`tPrevious Tryanid files still exist in Soulstorm directory." -BackgroundColor Red -ForegroundColor White
}
Remove-Variable -Name installPath
Remove-Variable -Name isUninstalled
}
function InstallTyrandsUA {
[string] $installPath = $DefaultModPaths.Tyranid_Mod_0_5b2
## Terminate Steam Game
TerminateSoulstorm $SSPaths.SoulstormName
TerminateSoulstorm $SSPaths.SteamName
# Uninstall
Write-Host " Uninstalling Tyranids" -BackgroundColor Yellow -ForegroundColor Black
RunExecutable $SSPaths.Tyranid_Mod_Uninstall
RunExecutable $SSPaths.TyranidsUninstall
# Confirm deletion of old Tyranic mod
[bool] $isUninstalled = IsTyranidRemoved
# Install Tyranid_Mod_v0.5b2
if ( $isUninstalled ) {
Write-Host " Installing Tyranids > $installPath" -BackgroundColor Green -ForegroundColor Black
RunExecutable "$installPath"
} else {
Write-Host " Script aborted.`n`tPrevious Tryanid files still exist in Soulstorm directory." -BackgroundColor Red -ForegroundColor White
}
Remove-Variable -Name installPath
Remove-Variable -Name isUninstalled
}
<# Main() #>
function Main {
Clear-Host
# Declare global file path variables
InitializeGlobalVariables
# Display about message
About
# Edit Tyranid installer path if necessary
EditSourcePath
## Menu Prompt Input
$promptAnswer = MenuPrompt
## Perform menu option
switch ( $promptAnswer ) {
1 { # Install Tyranid_Mod_v0.5b2
InstallTyrandsUA }
2 { # Install Tyranid_Mod_v0.5b3
InstallTyrandsUM }
"e" { # Open Lua *.ai directory
OpenLuaDir }
default { # Cancel
Write-Host " Canceled Tyranid modification." -ForegroundColor Red }
}
Write-Host "`n Done.`n" -ForegroundColor DarkYellow
}
<# Run #>
Main
<#
Write CSV files containing attibutes of Application files.
Installed drivers Win32Product.csv
Installed programms Uninstall_HKLM.csv
Installer files Exec_FileVersionInfo.csv
#>
Clear-History
Clear-Host
<# #############################################
## Parse String
############################################# #>
function ConfirmOutfile {
param ( [string] $filePath )
$fullPath = (Resolve-Path $filePath).Path
if ( Test-Path $fullPath ) {
Write-Host "File exists: $fullPath" -ForegroundColor Green
}
}
function ReplaceString {
param ( [string] $inputString, [string] $stringPattern, [string] $replaceString )
[bool] $isMatch = $inputString -match $stringPattern
if ( $isMatch ) {
[string] $outString = $inputString -replace $stringPattern, $replaceString
} else {
[string] $outString = $inputString
}
return $outString
}
function RemFirstWhitespace {
param ( [string] $inputString )
[int] $tmpLen = $inputString.Length - 1
[string] $firstChar = $inputString.Substring( 0, 1 )
if ( $firstChar -eq " " ) {
[string] $outstring = $inputString.Substring( 1, $inputString.Length - 1 ) ## Parse out the 1st white space from string
} else {
[string] $outstring = $inputString
}
return $outstring
}
<# #############################################
## Write Csvs
############################################# #>
function WriteInstalledCsv_Drivers {
[string] $outFile = "Win32Product.csv"
$Win32Product = Get-WmiObject Win32_Product
$Win32Product | Select-Object -Property Description, IdentifyingNumber, Version | export-csv $outFile -NoTypeInformation
ConfirmOutfile $outFile
}
function WriteInstalledCsv_Uninstallers {
[string] $outFile = "Uninstall_HKLM.csv"
## x86 or x64 system
if ( [IntPtr]::Size -eq 4 ) {
$path = 'HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall\*'
} else {
$path = @(
'HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall\*'
'HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\*'
)
}
$Uninstall_HKLM = Get-ItemProperty $path
$Uninstall_HKLM | Select-Object -Property DisplayName, DisplayVersion, PSChildName | export-csv -NoTypeInformation $outFile
ConfirmOutfile $outFile
}
Function WriteInstalledCsv_Installers {
[string] $ExeDir = "D:\Software DL\Inspiron 15 7000 Drivers\Dell Driver Bundle Dec2017\*"
[bool] $isDir = Test-Path $ExeDir
[string] $outFile = "Exec_FileVersionInfo.csv"
if ( !$isDir ) {
Write-Host "Path does `"$ExeDir`" not exist." -ForegroundColor Red
Exit
}
## "PSPath","PSParentPath","PSChildName","PSDrive","PSProvider","PSIsContainer","Mode","VersionInfo","BaseName","Target","LinkType","Name","Length","DirectoryName","Directory","IsReadOnly","Exists","FullName","Extension","CreationTime","CreationTimeUtc","LastAccessTime","LastAccessTimeUtc","LastWriteTime","LastWriteTimeUtc","Attributes"
#$ExeChildren = Get-ChildItem $ExeDir -Include ("*.exe", "*.msi")
#$ExeChildren | Select-Object -Property FileDescription | export-csv -NoTypeInformation "Exec_FileVersionInfo.csv"
$FileVersionInfo_FileDescription = @()
Get-ChildItem $ExeDir | ForEach-Object {
# Declare a new object for the array
$AttrObject = [PSCustomObject] @{
FileDescription = ""
Version = ""
}
## get exe attribute meta from child item
$attrString = [System.Diagnostics.FileVersionInfo]::GetVersionInfo($_).FileDescription
if ( $attrString ) {
## Package Name
$exeFileDescription = $attrString.Split(",")[0]
$dellString = $exeFileDescription.Split(":") ## Parse out "Dell Update Package:"
if ( $dellString ) {
$exeFileDescription = $dellString[1] ## Parse out the 1st white space from string
}
$exeFileDescription = ReplaceString $exeFileDescription "Intel` " "Intel`(R`)` " ## Make "Intel " "Intel(R) "
## Version Number
$exeVeresion = $attrString.Split(",")[1]; ## Parse out the version number
# Populate object variable
$AttrObject.FileDescription = RemFirstWhitespace $exeFileDescription
$AttrObject.Version = RemFirstWhitespace $exeVeresion
#Append Array
$FileVersionInfo_FileDescription+=$AttrObject
}
}
$FileVersionInfo_FileDescription | export-csv -NoTypeInformation $outFile
ConfirmOutfile $outFile
}
function WriteCsvFiles {
Write-Host "# Write CSV files for string debigging." -ForegroundColor Yellow
WriteInstalledCsv_Drivers
WriteInstalledCsv_Uninstallers
WriteInstalledCsv_Installers
}
<# #############################################
## Populate Objects
############################################# #>
function Return_Win32Product_Object {
$Win32Product = Get-WmiObject Win32_Product
$OutputObject = $Win32Product | Select-Object -Property Description, IdentifyingNumber, Version
return $OutputObject
}
function Return_HKLM_Object {
## x86 or x64 system
if ( [IntPtr]::Size -eq 4 ) {
$path = 'HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall\*'
} else {
$path = @(
'HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall\*'
'HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\*'
)
}
$Uninstall_HKLM = Get-ItemProperty $path
$OutputObject = $Uninstall_HKLM | Select-Object -Property DisplayName, DisplayVersion, PSChildName
return $OutputObject
}
Function Return_InstallerAttr_Object {
param ( [string] $ExeDir )
#[string] $ExeDir = "D:\Software DL\Inspiron 15 7000 Drivers\Dell Driver Bundle Dec2017\*"
[bool] $isDir = Test-Path $ExeDir
[string] $outFile = "Exec_FileVersionInfo.csv"
if ( !$isDir ) {
Write-Host "Path does `"$ExeDir`" not exist.`n`tScript Exited." -ForegroundColor Red
Exit
}
## "PSPath","PSParentPath","PSChildName","PSDrive","PSProvider","PSIsContainer","Mode","VersionInfo","BaseName","Target","LinkType","Name","Length","DirectoryName","Directory","IsReadOnly","Exists","FullName","Extension","CreationTime","CreationTimeUtc","LastAccessTime","LastAccessTimeUtc","LastWriteTime","LastWriteTimeUtc","Attributes"
#$ExeChildren = Get-ChildItem $ExeDir -Include ("*.exe", "*.msi")
#$ExeChildren | Select-Object -Property FileDescription | export-csv -NoTypeInformation "Exec_FileVersionInfo.csv"
$OutputObject = @()
Get-ChildItem $ExeDir | ForEach-Object {
$thisExe_Path = (Resolve-Path $_).Path
# Declare a new object for the array
$AttrObject = [PSCustomObject] @{
FileDescription = ""
Version = ""
Path = ""
}
## get exe attribute meta from child item
$attrString = [System.Diagnostics.FileVersionInfo]::GetVersionInfo( $thisExe_Path ).FileDescription
if ( $attrString ) {
## Package Name
$exeFileDescription = $attrString.Split(",")[0]
$dellString = $exeFileDescription.Split(":") ## Parse out "Dell Update Package:"
if ( $dellString ) {
$exeFileDescription = $dellString[1] ## Parse out the 1st white space from string
}
$exeFileDescription = ReplaceString $exeFileDescription "Intel` " "Intel`(R`)` " ## Make "Intel " "Intel(R) "
## Version Number
$exeVeresion = $attrString.Split(",")[1]; ## Parse out the version number
# Populate object variable
$AttrObject.FileDescription = RemFirstWhitespace $exeFileDescription
$AttrObject.Version = RemFirstWhitespace $exeVeresion
$AttrObject.Path = $thisExe_Path
#Append Array
$OutputObject+=$AttrObject
}
}
return $OutputObject
}
function IsExeMatchWin32 {
Write-Host "IsExeMatchWin32 ..." -ForegroundColor Yellow
$Win32Product_Object = Return_Win32Product_Object
$InstallerAttr_Object = Return_InstallerAttr_Object "D:\Software DL\Inspiron 15 7000 Drivers\Dell Driver Bundle Dec2017\*"
[int] $idx = 0
$InstallerAttr_Object | ForEach-Object {
$FileDescription = $_.FileDescription
#$Win32Product_Object -contains $FileDescription
$Win32Product_Object | ForEach-Object {
$win32_Description = $_.Description
if ( $win32_Description -match $FileDescription ) { Write-Host "Match:`t$win32_Description`t$FileDescription " -ForegroundColor Green; }
<#
$WordArr = $FileDescription.Split(" ")
$WordArr | ForEach-Object {
if ( $win32_Description -match $_ ) { Write-Host "Match:`t$win32_Description`t$_ " -ForegroundColor Green; }
#else { Write-Host "No Match:`t$win32_Description`t$_ " -ForegroundColor Red; break }
}#>
}
}
}
function IsExeMatchHklm {
Write-Host "IsExeMatchHklm ..." -ForegroundColor Yellow
$HKLM_Object = Return_HKLM_Object
$InstallerAttr_Object = Return_InstallerAttr_Object "D:\Software DL\Inspiron 15 7000 Drivers\Dell Driver Bundle Dec2017\*"
$ObjAccumulator_Installed = @()
$ObjAccumulator_UnInstalled = @()
$InstallerAttr_Object | ForEach-Object {
$thisObj_Exe = $_
$FileDescription = $thisObj_Exe.FileDescription
#$HKLM_Object -contains $DisplayName
$HKLM_Object | ForEach-Object {
$thisObj_hklm = $_
$hklm_DisplayName = $thisObj_hklm.DisplayName
#Write-Host "Match:`t$hklm_DisplayName`t$FileDescription " -ForegroundColor Magenta;
<#if ( $hklm_DisplayName -match $FileDescription ) {
Write-Host "Match:`t$hklm_DisplayName`t$FileDescription " -ForegroundColor Green;
} #>
[int] $matchCount = 0
$WordArr = $FileDescription.Split(" ")
[int] $WordArrLength = $WordArr.Length
$WordArr | ForEach-Object {
if ( $hklm_DisplayName -match $_ ) {
if ( $WordArrLength -lt 2 ) {
$matchCount=2;
}
$matchCount++;
}
if ( $matchCount -gt 2 ) {
Write-Host "Match:`t$hklm_DisplayName`t`|`t$FileDescription" -ForegroundColor Green;
$ObjAccumulator_Installed += $thisObj_Exe
$matchCount = 0
}
}
#$ObjAccumulator_UnInstalled += $thisObj_Exe
}
}
$a = $ObjAccumulator_Installed | Sort-Object -Property FileDescription -Unique
#$b = $ObjAccumulator_UnInstalled | Sort-Object -Property FileDescription -Unique
$a | ForEach-Object {
#Write-Host $_.Path -ForegroundColor Magenta
Write-Host $_.FileDescription -ForegroundColor Magenta
}
"Intel(R) HID Event Filter Driver" -match $a
$a | Where-Object { $_.FileDescription -like "Intel(R) HID Event Filter Driver" }
$a | Where-Object { $_.FileDescription -like "Quickset" }
$a | Where-Object { $_.FileDescription -like "SmartByte" }
$a | Where-Object { $_.FileDescription -like "*HID Event Filter Driver" }
}
<# ############################################# #>
WriteCsvFiles
#$Win32Product_Object = Return_Win32Product_Object
#IsExeMatchWin32
IsExeMatchHklm
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment