Skip to content

Instantly share code, notes, and snippets.

@schittli
Last active August 14, 2022 13:31
Show Gist options
  • Save schittli/812fe5497fd3f8eb88c8ba977e7a1143 to your computer and use it in GitHub Desktop.
Save schittli/812fe5497fd3f8eb88c8ba977e7a1143 to your computer and use it in GitHub Desktop.
Tom-Chocolatey-Tools.ps1 #PowerShell #Choco
# Funktionen für
# Chocolatey, Choco
# Nuget Packages
# BoxStarter
#
#
# Download / In die aktuelle PS Session laden
# •••••••••••••••••••••••••••••••••••••••••••
# $UrlTools = 'https://gitlab.com/jig-opensource/source-code/chocolatey/-/raw/main/Tom-Chocolatey-Tools.ps1'
#
# In die aktuelle PS Session laden
# iex ((New-Object System.Net.WebClient).DownloadString( $UrlTools ))
#
# Klappt nun:
# Wait-For-UserInput 'Titel' 'Bist Du bereit?' @('&Yes', '&Ja', '&No', '&Nein') 'Ja'
#
# Download des Scripts
# Invoke-WebRequest $UrlTools | Select-Object -ExpandProperty Content | Out-File 'file.ps1'
#
#
# Funktionen
# Wait-For-UserInput
# Has-Reg-Value
# Update-Or-Create-RegValue
# Pin-App
# Pin-App-by-Path
# Restart-Explorer
# Refresh-Explorer
# Is-SW-Installed
# Get-Installed-Software
# Get-Installed-VcRedist
# Map-Network
# Delete-Coco-Lib-Delayed
# Is-Path-Relative
# Find-Shim-File
# Get-Shim-exe-Target
# Get-Shim-bat-Target
# If-Shim-Target-Exists
# Remove-Executable-Shims
# Add-Shim-Ignore
#
#
# Noch fertigstellen!:
# Remove-Executable-Shims
#
#
#
# 001, 211208, tom@jig.ch
# 002, 220724
# Pin-App
# Neu: $Ident
# 003, 220731
# Neu:
# Delete-Coco-Lib-Delayed
# 004
# Neu:
# Has-Reg-Value
# Update-Or-Create-RegValue
# Noch fertigstellen
# Remove-Executable-Shims
# 005
# 006
# Neu: Ask-User-Select-CheckBoxes
# 007
# Entfernt: Ask-User-Select-CheckBoxes
# 008
# Fix: --params muss unedingt mit "''" umschlossen werden
#
$DbgLog = $False
Function Dbg-To($Log) { If ($DbgLog) { Write-Host -ForegroundColor Yellow -Object "WiSe To: $Log" } }
# Wartet auf eine Antwort vom Benutzer
# Wait-For-UserInput 'Titel' 'Bist Du bereit?' @('&Yes', '&Ja', '&No', '&Nein') 'Ja'
Dbg-To '1000'
Function Wait-For-UserInput($Titel, $Msg, $Options, $Default) {
# Optionen ohne '&'
$OptionsArrTxt = $Options | % { $_.Replace('&','') }
$DefaultIdx = $OptionsArrTxt.indexof($Default)
$Response = $Host.UI.PromptForChoice($Titel, $Msg, $Options, $DefaultIdx)
Return $OptionsArrTxt[$Response]
}
# Liefert True, wenn in der Registry ein Key existiert
Dbg-To '1010'
Function Has-Reg-Value {
Param (
[Parameter(Mandatory)]
[ValidateNotNullOrEmpty()][String]$RegPath,
[Parameter(Mandatory)]
[ValidateNotNullOrEmpty()][String]$PropertyName
)
If (Test-Path $RegPath) {
Try {
Get-ItemProperty -Path $RegPath | Select-Object -ExpandProperty $PropertyName -ErrorAction Stop | Out-Null
return $true
}
Catch {
return $false
}
} Else {
return $false
}
}
Dbg-To '1020'
Function Update-Or-Create-RegValue() {
Param (
[Parameter(Mandatory)]
[ValidateNotNullOrEmpty()][String]$RegPath,
[Parameter(Mandatory)]
[ValidateNotNullOrEmpty()][String]$PropertyName,
[Parameter(Mandatory)]
[ValidateNotNullOrEmpty()][String]$RegValue,
[ValidateNotNullOrEmpty()][String]$PropertyType
)
If (-not (Test-Path $RegPath)) {
New-Item -Path $RegPath -Force | Out-Null
}
If (Has-Reg-Value -RegPath $RegPath -PropertyName $PropertyName) {
Set-ItemProperty -Path $RegPath -Name $PropertyName -Value $RegValue -Force
} Else {
$Null = New-ItemProperty -Path $RegPath -Name $PropertyName -Value $RegValue -PropertyType $PropertyType -Force
}
}
# Ex, funktionieren!:
# Pin-App 'Microsoft Edge' -unpin -taskbar
# Pin-App 'Mail' -unpin -taskbar
# !Q
# https://www.tenforums.com/customization/21002-how-automatically-cmd-powershell-script-unpin-all-apps-start.html
Dbg-To '1030'
Function Pin-App ([string]$appname, [switch]$unpin, [switch]$start, [switch]$taskbar, [string]$path, [Int]$Ident = 0) {
$Ident = 2 * $Ident
if ($unpin.IsPresent) {
$action = 'Unpin'
} else {
$action = 'Pin'
}
if (-not $taskbar.IsPresent -and -not $start.IsPresent) {
Write-Host "$(' ' * $Ident)Specify -taskbar and/or -start!" -ForegroundColor Red
}
if ($taskbar.IsPresent) {
try {
$exec = $false
if ($action -eq 'Unpin') {
((New-Object -Com Shell.Application).NameSpace('shell:::{4234d49b-0245-4df3-b780-3893943456e1}').Items() | ?{$_.Name -eq $appname}).Verbs() | ?{$_.Name.replace('&','') -match 'Unpin from taskbar'} | %{$_.DoIt(); $exec = $true}
if ($exec) {
Write-Host "$(' ' * $Ident)App '$appname' unpinned from Taskbar"
} else {
if (-not $path -eq '') {
Pin-App-by-Path $path -Action $action
} else {
# Wohl bereits unpinned
# Write "'$appname' not found or 'Unpin from taskbar' not found on item!"
}
}
} else {
((New-Object -Com Shell.Application).NameSpace('shell:::{4234d49b-0245-4df3-b780-3893943456e1}').Items() | ?{$_.Name -eq $appname}).Verbs() | ?{$_.Name.replace('&','') -match 'Pin to taskbar'} | %{$_.DoIt(); $exec = $true}
if ($exec) {
Write-Host "$(' ' * $Ident)App '$appname' pinned to Taskbar"
} else {
if (-not $path -eq '') {
Pin-App-by-Path $path -Action $action
} else {
# Wohl bereits unpinned
# Write "'$appname' not found or 'Pin to taskbar' not found on item!"
}
}
}
} catch {
Write-Host "$(' ' * $Ident)Error Pinning/Unpinning $appname to/from taskbar!" -ForegroundColor Red
}
}
if ($start.IsPresent) {
try {
$exec = $false
if ($action -eq 'Unpin') {
((New-Object -Com Shell.Application).NameSpace('shell:::{4234d49b-0245-4df3-b780-3893943456e1}').Items() | ?{$_.Name -eq $appname}).Verbs() | ?{$_.Name.replace('&','') -match 'Unpin from Start'} | %{$_.DoIt(); $exec = $true}
if ($exec) {
Write-Host "$(' ' * $Ident)App '$appname' unpinned from Start"
} else {
if (-not $path -eq '') {
Pin-App-by-Path $path -Action $action -start
} else {
# Wohl bereits unpinned
# Write "'$appname' not found or 'Unpin from Start' not found on item!"
}
}
} else {
((New-Object -Com Shell.Application).NameSpace('shell:::{4234d49b-0245-4df3-b780-3893943456e1}').Items() | ?{$_.Name -eq $appname}).Verbs() | ?{$_.Name.replace('&','') -match 'Pin to Start'} | %{$_.DoIt(); $exec = $true}
if ($exec) {
Write-Host "$(' ' * $Ident)App '$appname' pinned to Start"
} else {
if (-not $path -eq '') {
Pin-App-by-Path $path -Action $action -start
} else {
# Wohl bereits unpinned
# Write "'$appname' not found or 'Pin to Start' not found on item!"
}
}
}
} catch {
Write-Host "$(' ' * $Ident)Error Pinning/Unpinning $appname to/from Start!" -ForegroundColor Red
}
}
}
Dbg-To '1040'
function Pin-App-by-Path([string]$Path, [string]$Action, [switch]$start, [Int]$Ident = 0) {
$Ident = 2 * $Ident
if ($Path -eq '') {
Write-Host "$(' ' * $Ident)You need to specify a Path" -ForegroundColor Red -ErrorAction Stop
}
if ($Action -eq '') {
Write-Host "$(' ' * $Ident)You need to specify an action: Pin or Unpin" -ForegroundColor Red -ErrorAction Stop
}
if ($null -eq (Get-Item -Path $Path -ErrorAction SilentlyContinue)){
Write-Host "$(' ' * $Ident)$Path not found" -ForegroundColor Red -ErrorAction Stop
}
$Shell = New-Object -ComObject 'Shell.Application'
$ItemParent = Split-Path -Path $Path -Parent
$ItemLeaf = Split-Path -Path $Path -Leaf
$Folder = $Shell.NameSpace($ItemParent)
$ItemObject = $Folder.ParseName($ItemLeaf)
$Verbs = $ItemObject.Verbs()
if ($start.IsPresent) {
switch($Action){
'Pin' {$Verb = $Verbs | Where-Object -Property Name -EQ '&Pin to Start'}
'Unpin' {$Verb = $Verbs | Where-Object -Property Name -EQ 'Un&pin from Start'}
default { Write-Host "$(' ' * $Ident)Invalid action, should be Pin or Unpin" -ForegroundColor Red -ErrorAction Stop }
}
} else {
switch($Action){
'Pin' {$Verb = $Verbs | Where-Object -Property Name -EQ 'Pin to Tas&kbar'}
'Unpin' {$Verb = $Verbs | Where-Object -Property Name -EQ 'Unpin from Tas&kbar'}
default { Write-Host "$(' ' * $Ident)Invalid action, should be Pin or Unpin" -ForegroundColor Red -ErrorAction Stop }
}
}
if($null -eq $Verb){
Write-Host "$(' ' * $Ident)That action is not currently available on this Path" -ForegroundColor Red -ErrorAction Stop
} else {
$Result = $Verb.DoIt()
}
}
# Startet den Explorer neu
Dbg-To '1050'
Function Restart-Explorer() {
Stop-Process -ProcessName Explorer -Force -ErrorAction SilentlyContinue
Start-Sleep -Milliseconds 3000
# Wurde der Explorer automatisch wieder gestartet?
$ProcExplorer = Get-Process | ? { -not [String]::IsNullOrEmpty($_.Path) -and $_.Path -like '*Explorer.exe' } | select -First 1
If ($null -eq $ProcExplorer) {
Start-Process "$($env:SystemRoot)\explorer.exe"
}
}
# Refresh Desktop Icons
Dbg-To '1060'
Function Refresh-Explorer() {
# Refresh Desktop
$definition = @'
[System.Runtime.InteropServices.DllImport("Shell32.dll")]
private static extern int SHChangeNotify(int eventId, int flags, IntPtr item1, IntPtr item2);
public static void Refresh() {
SHChangeNotify(0x8000000, 0x1000, IntPtr.Zero, IntPtr.Zero);
}
'@
Try {
Add-Type -MemberDefinition $definition -Namespace WinAPI -Name Explorer -ErrorAction Stop
} Catch {}
[WinAPI.Explorer]::Refresh()
rundll32.exe user32.dll, UpdatePerUserSystemParameters
}
# Liefert True, wenn in der Registry eine SW installiert ist
Dbg-To '1070'
Function Is-SW-Installed($Name) {
$x86 = ((Get-ChildItem 'HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall') |
Where-Object { $_.GetValue( 'DisplayName' ) -like "*$name*" } ).Length -gt 0;
$x64 = ((Get-ChildItem 'HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall') |
Where-Object { $_.GetValue( 'DisplayName' ) -like "*$name*" } ).Length -gt 0;
Return $x86 -or $x64;
}
# Liefert aus der Registry alle installierte SW zurück
# 001, 211208 Ori
# 002, 211208 tom@jig.ch
# Nicht mehr nur die Applikationen anzeigen, die einen Product-Code als GUID haben
#
# !Q https://www.powershellgallery.com/packages/VcRedist/3.0.292/Content/Private%5CGet-InstalledSoftware.ps1
Dbg-To '1080'
Function Get-Installed-Software {
<#
.SYNOPSIS
Retrieves a list of all software installed
.EXAMPLE
Get-Installed-Software
This example retrieves all software installed on the local computer
.PARAMETER Name
The software title you'd like to limit the query to.
.NOTES
Author: Adam Bertram
URL: https://4sysops.com/archives/find-the-product-guid-of-installed-software-with-powershell/
#>
[OutputType([System.Management.Automation.PSObject])]
[CmdletBinding()]
Param (
[Parameter()]
[ValidateNotNullOrEmpty()]
[System.String] $Name
)
$UninstallKeys = 'HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall', 'HKLM:\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall'
$null = New-PSDrive -Name 'HKU' -PSProvider 'Registry' -Root 'Registry::HKEY_USERS'
$UninstallKeys += Get-ChildItem -Path 'HKU:' -ErrorAction SilentlyContinue | Where-Object { $_.Name -match 'S-\d-\d+-(\d+-){1,14}\d+$' } | `
ForEach-Object { "HKU:\$($_.PSChildName)\Software\Microsoft\Windows\CurrentVersion\Uninstall" }
If (-not $UninstallKeys) {
Write-Verbose -Message "$($MyInvocation.MyCommand): No software registry keys found."
}
Else {
ForEach ($UninstallKey in $UninstallKeys) {
# Write-Host "tomtom: $UninstallKey"
# tomtom: Nicht nur die Applikationen anzeigen, die einen Product-Code als GUI haben
# If ($PSBoundParameters.ContainsKey('Name')) {
# $WhereBlock = { ($_.PSChildName -match '^{[A-Z0-9]{8}-([A-Z0-9]{4}-){3}[A-Z0-9]{12}}$') -and ($_.GetValue('DisplayName') -like "$Name*") }
# }
# Else {
# $WhereBlock = { ($_.PSChildName -match '^{[A-Z0-9]{8}-([A-Z0-9]{4}-){3}[A-Z0-9]{12}}$') -and ($_.GetValue('DisplayName')) }
# }
If ([String]::IsNullOrEmpty($Name)) {
$WhereBlock = { $True }
} Else {
$WhereBlock = { $_.Name -like "*$($Name)*" }
}
$gciParams = @{
Path = $UninstallKey
ErrorAction = 'SilentlyContinue'
}
$selectProperties = @(
@{n = 'Publisher'; e = { $_.GetValue('Publisher') } },
@{n = 'Name'; e = {
If([String]::IsNullOrEmpty($_.GetValue('DisplayName'))) {
$_.PSChildName
} Else {
$_.GetValue('DisplayName')
} } },
@{n = 'Version'; e = { $_.GetValue('DisplayVersion') } },
@{n = 'ProductCode'; e = { $_.PSChildName } },
@{n = 'BundleCachePath'; e = { $_.GetValue('BundleCachePath') } },
@{n = 'Architecture'; e = { If ($_.GetValue('DisplayName') -like '*x64*') { 'x64' } Else { 'x86' } } },
@{n = 'Release'; e = { If ($_.GetValue('DisplayName') -match [RegEx]'(\d{4})\s+') { $matches[0].Trim(' ') } } },
@{n = 'UninstallString'; e = { $_.GetValue('UninstallString') } },
@{n = 'QuietUninstallString'; e = { $_.GetValue('QuietUninstallString') } },
@{n = 'UninstallKey'; e = { $UninstallKey } }
)
# tomtom
# Get-ChildItem @gciParams | Where-Object $WhereBlock | Select-Object -Property $selectProperties
Get-ChildItem @gciParams | Select-Object -Property $selectProperties | Where-Object $WhereBlock
}
}
}
# Gibt die VC++ Resistributions zurück
# 001, 211128, tom@jig.ch
#
# !Q
# https://www.powershellgallery.com/packages/VcRedist/3.0.292/Content/Public%5CGet-InstalledVcRedist.ps1
Dbg-To '1090'
Function Get-Installed-VcRedist {
<#
.EXTERNALHELP VcRedist-help.xml
#>
[CmdletBinding(SupportsShouldProcess = $False, HelpURI = 'https://stealthpuppy.com/vcredist/get-installedvcredist/')]
[OutputType([System.Management.Automation.PSObject])]
Param (
[Parameter(Mandatory = $False)]
[System.Management.Automation.SwitchParameter] $ExportAll
)
# Get all installed Visual C++ Redistributables installed components
Write-Verbose -Message "$($MyInvocation.MyCommand): Matching installed VcRedists with: [(Microsoft Visual C.*)(\bRedistributable|\bRuntime).*]."
$VcRedists = Get-InstalledSoftware | Where-Object { $_.Name -match '(Microsoft Visual C.*)(\bRedistributable|\bRuntime).*' }
# Add Architecture property to each entry
Write-Verbose -Message "$($MyInvocation.MyCommand): Adding Architecture property."
$VcRedists | ForEach-Object { If ($_.Name -contains 'x64') { $_ | Add-Member -NotePropertyName 'Architecture' -NotePropertyValue 'x64' } }
# If -ExportAll used, export everything instead of filtering for the primary Redistributable
If ($PSBoundParameters.ContainsKey('ExportAll')) {
# Write the installed VcRedists to the pipeline
Write-Output -InputObject $VcRedists
}
Else {
Write-Verbose -Message "$($MyInvocation.MyCommand): Filtering output."
$Output = $VcRedists | ForEach-Object { If (-not (Select-String -InputObject $_ -Pattern 'Additional|Minimum')) { $_ } } | Sort-Object -Property 'Name'
# Write the filtered installed VcRedists to the pipeline
Write-Output -InputObject $Output
}
}
# Testet den Zugriff auf $Share
# und fragt allenfalls nach dem Login
#
# Ex
# Map-Network '\\Akros.ch\Ablage'
Dbg-To '1100'
Function Map-Network($Share) {
Try {
$Null = Get-Item -LiteralPath $Share -ErrorAction Stop
} Catch {
$ServerShare = ($Share -split '\\' | ? { $_ })[0..1] -join '\'
$ServerShare = ('\\{0}' -f $ServerShare)
Do {
$NetError = $True
$Cred = Get-Credential -Message "Login für: $Share"
Try {
$Res = New-PSDrive -Name 'Setup' -PSProvider 'FileSystem' -Root $ServerShare -Credential $Cred -ErrorAction Stop
$NetError = $False
} Catch {
Write-Host 'Zugriff verweigert' -ForegroundColor Red
}
} While ($NetError -eq $True)
}
}
### Choco Tools
## Choco Libs im lokalen Choco Repository in:
## $Env:ChocolateyInstall\lib\
# Startet einen neuen Prozess, der nach ein paar Sekunden dieses Coco-Paket löscht,
# weil es ja kein SW-Paket ist
# 220731
Dbg-To '1110'
Function Delete-Coco-Lib-Delayed() {
[CmdletBinding()]
Param (
# e.g. Win-Cfg-Audiolevel0-Tom
[String]$PackageID = $Env:ChocolateyPackageName,
[Int]$DelayMs = 5000,
[Switch]$KeepWindowOpen
)
Dbg-To '11101'
Write-Host ' » The Choco-Package will remove itself from Choco Lib' -Foregroundcolor Cyan
Dbg-To '11102'
# https://docs.chocolatey.org/en-us/create/functions/#environment-variables
$PackageInstalledLibDir = "$Env:ChocolateyInstall\lib\$PackageID"
# !M https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_powershell_exe?view=powershell-5.1
Dbg-To '11103'
If ($KeepWindowOpen) {
Start-Process -FilePath PowerShell.exe -ArgumentList "-NoExit -NonInteractive -NoLogo -NoProfile -ExecutionPolicy ByPass -Command &{ Set-Variable -Name Variable:Global:ProgressPreference -Value SilentlyContinue; Write-Host `"Lösche: $PackageInstalledLibDir`"; Start-Sleep -Milli $DelayMs; Remove-Item $PackageInstalledLibDir -Recurse -Force; }"
} Else {
Start-Process -WindowStyle Hidden -FilePath PowerShell.exe -ArgumentList "-NonInteractive -NoLogo -NoProfile -ExecutionPolicy ByPass -Command &{ Set-Variable -Name Variable:Global:ProgressPreference -Value SilentlyContinue; Write-Host `"Lösche: $PackageInstalledLibDir`"; Start-Sleep -Milli $DelayMs; Remove-Item $PackageInstalledLibDir -Recurse -Force; Exit }"
}
}
# Liefert True, wenn $Path relativ ist
Dbg-To '1120'
Function Is-Path-Relative($Path) {
If ([String]::IsNullOrEmpty($Path)) { Return }
If ($Path.StartsWith('\\')) { Return $False }
If ($Path.StartsWith('.\')) { Return $True }
If ($Path.Contains(':')) { Return $False }
Return $true
}
# Sucht eine Choco Shim-Datei
#
# Klappt alles:
# Find-Shim-File 'Choco-Cleaner'
# Find-Shim-File 'Choco-Cleaner.bat'
# Find-Shim-File 'C:\ProgramData\chocolatey\bin\Choco-Cleaner'
# Find-Shim-File 'C:\ProgramData\chocolatey\bin\Choco-Cleaner.bat'
#
# Res
# $Exists, $Target = Find-Shim-File 'C:\ProgramData\chocolatey\bin\notepad++.exe'
Dbg-To '1130'
Function Find-Shim-File {
Param (
[String][Parameter(Mandatory, ValueFromPipeline)]$ShimFile,
[Switch]$DontShowError
)
$OriShimFileArg = $ShimFile
# Schon gefunden?
If (Test-Path -LiteralPath $ShimFile -PathType Leaf) {
Return @($True, $ShimFile)
}
# Wenn der ShimFileName relativ ist,
# dann den Pfad zu den Shim-Files automatisch ergänzen
If (Is-Path-Relative $ShimFile) {
Write-Host "Log, ShimFile: '$ShimFile'" -ForegroundColor Cyan
$ShimFile = Join-Path "$Env:ChocolateyInstall\Bin" $ShimFile
}
# Schon gefunden?
If (Test-Path -LiteralPath $ShimFile -PathType Leaf) {
Return @($True, $ShimFile)
}
# Wenn die Datei nicht existiert,
# wurde nur ein Choco-Package Name angegeben
# und die Shim-Datei wird gesucht
$Files = @(Get-ChildItem -Path "$ShimFile.*")
Switch ($Files.Count) {
0 {
If ($DontShowError -eq $False) {
Write-Host "Keine Shim-Files gefunden für: $OriShimFileArg" -ForegroundColor Red
}
Return @($False, $Null)
}
1 {
Return @($True, $Files[0].FullName)
}
}
If ($DontShowError -eq $False) {
Write-Host "Mehrere Shim-Files gefunden für: $OriShimFileArg" -ForegroundColor Red
}
Return @($False, $Null)
}
# Sucht für ein Shim.exe den ZielPfad
# $ShimFile
# Siehe: Function Find-Shim-File
#
# Res:
# $Exists, $Target = Get-Shim-exe-Target 'C:\ProgramData\chocolatey\bin\notepad++.exe'
Dbg-To '1140'
Function Get-Shim-exe-Target {
Param (
[String][Parameter(Mandatory, ValueFromPipeline)]$ShimFile
)
$Exists, $ShimFile = Find-Shim-File $ShimFile -DontShowError
If ($Exists) {
# run shim exe and report if the target program exists or not
$Res = & "$ShimFile" --shimgen-help
$TargetExists = ($Res | Select-String -pattern "Target Exists: 'True'") -ne $Null
# Write-Host "TargetExists: $TargetExists"
$rgx ='\s*Target:\s(?<ZielPfad>.*)$'
$HasMatch = $Res | ? { $_ -match $rgx } | Select -First 1
If ($HasMatch) {
Return @($TargetExists, $Matches.ZielPfad.Trim("'"))
}
}
Return @($TargetExists, $Null)
}
# Sucht für ein Shim.cmd|bat den ZielPfad
# $ShimFile
# Siehe: Function Find-Shim-File
#
# Res:
# $Exists, $Target = Get-Shim-bat-Target 'C:\ProgramData\chocolatey\bin\Choco-Cleaner.bat'
Dbg-To '1160'
Function Get-Shim-bat-Target {
Param (
[String][Parameter(Mandatory, ValueFromPipeline)]$ShimFile
)
$Exists, $ShimFile = Find-Shim-File $ShimFile -DontShowError
If ($Exists) {
$Content = Get-Content $ShimFile
# Ex
# powershell -NoProfile -ExecutionPolicy unrestricted -Command "& 'C:\Bin-Choco\Choco-Cleaner\Choco-Cleaner.ps1' %*"
$rgx ='"&\s*(?<ZielPfad>.*)\s*%\*"$'
$HasMatch = $Content | ? { $_ -match $rgx } | Select -First 1
If ($HasMatch) {
$Ziel = $Matches.ZielPfad.Trim().Trim("'")
$TargetExists = Test-Path -LiteralPath $Ziel -PathType Leaf
Return @($TargetExists, $Ziel)
}
}
Return @($False, $Null)
}
# Liefert True, wenn das Ziel eines Shim-Exe existiert
# $ShimFile
# Siehe: Function Find-Shim-File
Dbg-To '1170'
Function If-Shim-Target-Exists {
Param (
[String][Parameter(Mandatory, ValueFromPipeline)]$ShimFile
)
Dbg-To '11701'
$ShimFile = Find-Shim-File $ShimFile -DontShowError
If ($ShimFile -ne $null) {
Dbg-To '11702'
# run shim exe and report if the target program exists or not
$TargetExists = & "$ShimFile" "--shimgen-help" | Select-String -pattern "Target Exists: 'True'"
Dbg-To '11702'
Return $TargetExists -ne $null
}
Return $False
}
# Mit Shims erfasst choco install alle installierten Exe-Files
# und erfasst für jedes ein Shim, womit die exe im Pfad sind
#
# Wenn keine Shims erzeugt werden sollen,
# muss im Quell- oder Ziel-Verzeichnis mit dem exe
# eine .ignore Datei erzeugt werden
#
# !9 Gross-/Kleinschreibung ist wichtig!
#
# !Ex
# https://github.com/ferventcoder/chocolatey-packages/blob/6ea7c087bd999d428a564b5d7e236ae998ef72e9/automatic/git.commandline/tools/chocolateyInstall.ps1#L13-L20
Dbg-To '1180'
Function Add-Shim-Ignore() {
[CmdletBinding()]
Param (
[String]$ZielDir,
[String[]]$Whitelist
)
$files = Get-ChildItem $ZielDir -Include *.exe -Recurse -File
foreach ($file in $files) {
if (!($file.Name.Contains('git.exe')) -and !($file.Name.Contains('ssh'))) {
#generate an ignore file
New-Item "$file.ignore" -type file -force | Out-Null
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment