<# .SYNOPSIS Librairies PowerShell Indépendantes de la version de PowerShell utilisée .NOTES VERSION:0.1 #> $memory_formfactor = @( 'Unknown', 'Other', 'SIP', 'DIP', 'ZIP', 'SOJ', 'Proprietary', 'SIMM', 'DIMM', 'TSOP', 'PGA', 'RIMM', 'SODIMM', 'SRIMM', 'SMD', 'SSMP', 'QFP', 'TQFP', 'SOIC', 'LCC', 'PLCC', 'BGA', 'FPBGA', 'LGA' ) ################################################################################### # Utility cmdlets ################################################################################### Function Get-PowerShellVersion { Write-Output $PSVersionTable.PSVersion.Major } Function Split-Array { <# .SYNOPSIS Retourne un tableau sous la forme d'une chaine de charactère. .DESCRIPTION Le characère de séparation est défini par défaut à ",", mais peut-être configuré en utilisant le paramètre Separator .PARAMETER Data String[] Tableau a transformé .PARAMETER Separator String[] Chractère de séparation .INPUTS String[] .OUTPUTS String #> [CmdletBinding()] [OutputType([Hashtable])] Param( [Parameter( Position = 0, Mandatory = $True, ValueFromPipeline = $True, ValueFromPipelineByPropertyName = $True) ] [String[]]$Data, [Parameter( Position = 1, Mandatory = $False, ValueFromPipeline = $False, ValueFromPipelineByPropertyName = $True) ] [String]$Separator = "," ) Begin { $Output = "" } Process { $Data | Foreach-Object { $Output += "{0}{1}" -f $_, $Separator } } End { Write-Output ($Output -replace "${Separator}$", "") } } Function Get-IniContent { <# .SYNOPSIS Retounre un fichier au format .ini sous forme de tableau associatif .DESCRIPTION Le fichier est traité ligne par ligne. Les lignes de commentaires sont ignorées Monte une exeception si le fichier n'existe pas .PARAMETER Path Chemin du fichier .ini a traiter .INPUTS String .OUTPUTS Hashtable #> [CmdletBinding()] [OutputType([Hashtable])] Param ( [Parameter(Mandatory = $True, Position = 0)] [ValidateScript({Test-Path $_})] [String]$Path ) Try { $Output = @{} Switch -regex -file $Path { "^(?:\[)?([^\]\r\n]+)](?:\r?\n(?:[^[\r\n].*)?)*" { # Section $Section = $matches[1] $Output[$Section] = @{} } "^([^=;\r\n]+)=([^;\r\n]*)" { # Key $Name, $Value = $matches[1..2] If ($Value -ne "") { $Output[$Section][$Name] = $Value } } } } Catch { Write-LogError "Erreur durant l'analyse de $Path " Write-LogException $_ $Output = $Null } Write-Output $Output } Function Invoke-ZipExtraction { [CmdletBinding()] [OutputType([Boolean])] Param ( [Parameter(Mandatory = $True, Position = 0)] [ValidateScript({Test-Path $_})] [String] $Source, [Parameter(Mandatory = $True, Position = 1)] [String] $Destination, [Parameter(Mandatory = $False)] [String] $ExtractionOptions = "" ) Write-LogVerbose "7zip - Extraction de $Source vers $Destination" $Params = "$ExtractionOptions $source -y -o$destination --" Write-LogDebug "Commande 7zip $7zipBin $params" Start-Process -FilePath $7zipBin -ArgumentList $params -Wait -NoNewWindow # TODO: Recherche de 7ZIP } Function Test-ZipArchive { [CmdletBinding()] [OutputType([Boolean])] Param ( [Parameter(Mandatory = $True, Position = 0)] [ValidateScript({Test-Path $_})] [String] $Path, [Parameter(Mandatory = $False)] [String] $TestOptions = "" ) Write-LogVerbose "7zip - Verificaton de $Path" $Params = "t $TestOptions $Path" Write-LogDebug "Commande 7zip $7zipBin $Params" $Process = Start-Process -FilePath $7zipBin -ArgumentList $params -Wait -NoNewWindow -PassThru If ($Process.ExitCode -eq 0) { $Output = $True } Else { $Output = $False } Write-Output $Output # TODO: Recherche de 7ZIP # TODO: Logs de code de sortit # TOTO: Commentaire } Function ConvertTo-Base64 { <# .SYNOPSIS Encode une chaine au format Base64 .DESCRIPTION Monte une exception si la chaine n'est pas au format String .INPUTS String .OUTPUTS String .PARAMETER Data Chaine a convertir #> [CmdletBinding()] [OutputType([String])] Param( [Parameter( Position = 0, Mandatory = $True, ValueFromPipeline = $True, ValueFromPipelineByPropertyName = $true) ] [String]$Data ) Begin { $Output = "" } Process { $Output = [Convert]::ToBase64String([System.Text.Encoding]::Unicode.GetBytes($Data)) } End { Write-Output $Output } } Function Get-MDTTatoo { <# .SYNOPSIS Renvoie les informations liees au deploiement MDT .DESCRIPTION Retourne et . Les valeurs sont nulles si les cles de registre n'existe pas .INPUTS Aucune .OUTPUTS [Hashtable] #> [CmdletBinding()] [OutputType([Hashtable])] Param() Process { $Output = @{ "mdt_tsname" = $Null "mdt_tsversion" = $Null } $Path = "HKLM:\Software\Microsoft\Deployment 4" If (Test-Registry -Path $Path) { $Output = @{ "mdt_tsname" = Get-Registry -Path $Path -Property "Task Sequence Name" "mdt_tsversion" = Get-Registry -Path $Path -Property "Task Sequence Version" } } Write-Output $Output } } Function New-Shortcut { <# .SYNOPSIS Crée un raccourci .DESCRIPTION Le raccourci va de Path vers Target .PARAMETER Path Emplacement du raccourci .PARAMETER Target Destination du raccourci #> [CmdletBinding()] [OutputType([Hashtable])] Param ( [Parameter(Mandatory = $True)] [ValidateScript({Test-Path $_})] [String] $Path, $Target, [Parameter(Mandatory = $False)] [ValidateScript({Test-Path $_})] [String] $WorkingDirectory ) $Shell = New-Object -ComObject WScript.Shell $Link = $Shell.CreateShortcut($Path) $Link.TargetPath = $Target If ($WorkingDirectory -ne "") { $Link.WorkingDirectory = $WorkingDirectory } $Link.Save() } ################################################################################### # Logging cmdlets ################################################################################### Function Write-LogDebug ($Message) { If ($DebugPreference -ne "Continue") { Return } $Date = Get-Date -Format 'yyyy/MM/dd HH:mm:ss' $Line = "{0} [DEBUG] {1}" -f $Date, $Message Write-Host $Line -ForegroundColor "Yellow" if ($LogParams) { $Line | Out-File @LogParams } } Function Write-LogVerbose ($Message) { If ($VerbosePreference -ne "Continue") { Return } $Date = Get-Date -Format 'yyyy/MM/dd HH:mm:ss' $Line = "{0} [VERBOSE] {1}" -f $Date, $Message Write-Host $Line -ForegroundColor "Green" if ($LogParams) { $Line | Out-File @LogParams } } Function Write-LogInfo ($Message) { If ($InformationPreference -ne "Continue") { Return } $Date = Get-Date -Format 'yyyy/MM/dd HH:mm:ss' $Line = "{0} [INFO] {1}" -f $Date, $Message Write-Host $Line -ForegroundColor "White" if ($LogParams) { $Line | Out-File @LogParams } } Function Write-LogWarn ($Message) { $Date = Get-Date -Format 'yyyy/MM/dd HH:mm:ss' $Line = "{0} [WARN] {1}" -f $Date, $Message Write-Host $Line -ForegroundColor "White" if ($LogParams) { $Line | Out-File @LogParams } } Function Write-LogError ($Message) { $Date = Get-Date -Format 'yyyy/MM/dd HH:mm:ss' $Line = "{0} [ERROR] {1}" -f $Date, $Message Write-Host $Line -ForegroundColor "Red" if ($LogParams) { $Line | Out-File @LogParams } } Function Write-LogException ($e) { $Date = Get-Date -Format 'yyyy/MM/dd HH:mm:ss' $Line = "{0} [ERROR] {1} {2}" -f $Date, $e.InvocationInfo.ScriptLineNumber, $e Write-Host $Line -ForegroundColor "Red" if ($LogParams) { $Line | Out-File @LogParams } } Function Start-Log { [CmdletBinding()] [OutputType([psobject])] Param ( [Parameter(Mandatory=$true, Position=0)] [String] $Path, [Parameter()] [Switch] $Clear ) $ParentFolder = Split-Path $Path if (!(Test-Path $ParentFolder)) { try { Write-Host "Creation du repertoire de logs" -ForegroundColor "White" New-Item -ItemType Directory -Path $ParentFolder -ErrorAction Stop | Out-Null } catch { Throw "Impossible de creer le repertoire de logs" } } $SCRIPT:LogParams = @{ "FilePath" = $Path "Append" = $True; "Encoding" = "utf8" } $Error.Clear() If ($Clear) { If (Test-Path -Path $Path) { Clear-Content -Path $Path } } } Function Stop-Log { Write-LogInfo ("{0} Erreur(s)" -f $Error.Count) $Error | ForEach-Object { Write-LogException $_ } } Function Split-DebugOutput { # TODO: Verificer son fonctionnement Param( [Parameter( Position = 0, Mandatory = $True, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true) ] [Hashtable]$hashtable ) Begin { $output = "" } Process { ForEach ($property in $hashtable.GetEnumerator()) { $output += "{0}='{1}' " -f $property.Name, $property.Value } } End { Write-Output $output } } Function Get-Error { # TODO: Verificer son fonctionnement $output = @() $error | ForEach-Object { $e = $_ $output += @{ 'scriptName' = $e.InvocationInfo.ScriptName 'lineNumber' = $e.InvocationInfo.ScriptLineNumber 'message' = ( $e.Exception.Message | Out-String ) -replace "`"", "'" } } Write-Output $output } ################################################################################### # Registry cmdlets ################################################################################### Function Test-Is64Bits { <# .SYNOPSIS Renvois $True si Windows est un 64bits. Je me base sur le BuildNumber de Win32_OperatingSystem pour les anciens systèmes .OUTPUTS Boolean #> [CmdletBinding()] [OutputType([Boolean])] Param () $OS = Get-WmiObject -Class Win32_OperatingSystem If ($OS.BuildNumber -match '^(5|4|3|2)') { # XP HOST $OSArchitecture = 32 } Else { $OSArchitecture = $os.OSArchitecture } If ($OSArchitecture -match '64') { $Output = $True } Else { $Output = $False } Write-Output $Output } Function ConvertTo-64BitRegistryPath { <# .SYNOPSIS Transforme un chemin registre en ajoutant Wow6432Node .PARAMETER Path Chemin de registre .INPUTS String .OUTPUTS String #> [CmdletBinding()] [OutputType([Boolean])] Param( [Parameter( Mandatory = $True, ValueFromPipeline = $true) ] [String]$Path ) Begin { $Output = "" } Process { If (Test-Is64Bits) { $Output = $Path -replace "SOFTWARE\\", "SOFTWARE\Wow6432Node\" } } End { Write-Output $Output } } Function Test-Registry { <# .SYNOPSIS Verifie l'existance de clé de registre .DESCRIPTION Renvois $True ou $False .PARAMETER Path Le chemin clé de registre au format HKEY_LOCAL_MACHINE\ .PARAMETER Property Propriété pour la quelle je dois vérifier son existanced .OUTPUTS Boolean #> [CmdletBinding()] [OutputType([Boolean])] Param ( [Parameter(Mandatory = $True)] [ValidatePattern("^HKLM|HKCU")] [String]$Path, [Parameter()] [String]$Property ) Process { if (Test-Path -Path $Path) { if ($Property -eq "") { $Output = $True } else { $Properties = Get-Item -Path $Path | Select-Object -ExpandProperty Property if ($Properties -contains $Property) { $Output = $True } else { $Output = $False } } } else { $Output = $False } Write-LogDebug ("Test-Registry|{0}!{1}|{2}" -f $Path, $Property, $Output) Write-Output $Output } } Function Get-Registry { <# .SYNOPSIS Renvois une valeur du registre .DESCRIPTION La propriété à retrouver doit exister. Si ce n'est pas le cas, une exception est montée. .PARAMETER Path Le chemin clé de registre au format HKEY_LOCAL_MACHINE\ .PARAMETER Property Propriété pour la quelle récuperer la valeur .OUTPUTS Object #> [CmdletBinding()] [OutputType([Object])] Param ( [Parameter(Mandatory = $True)] [ValidatePattern("^HKLM|HKCU")] [String]$Path, [Parameter()] [String]$Property ) If ($Property -eq "") { If (Test-Registry -Path $Path) { $Output = Get-ItemProperty -Path $Path } Else { $Message = "Impossible de recuperer les proprietes, la clé de registre n'existe pas" Write-LogError ("Get-RegistryProperty|{0}!{1}|{2}" -f $Path,$Property, $Message) Throw $Message } } Else { If (Test-Registry -Path $Path -Property $Property) { $Output = Get-ItemProperty -Path $Path | Select-Object -ExpandProperty $Property } Else { $Message = "Impossible de recuperer la propriete, la clé de registre n'existe pas" Write-LogError ("Get-RegistryProperty|{0}!{1}|{2}" -f $Path,$Property, $Message) Throw $Message } } Write-LogDebug ("Get-RegistryProperty|{0}!{1}|{2}" -f $Path, $Property, $Output) Write-Output $Output } Function Set-Registry { <# .SYNOPSIS Enregistre une valeur dans le registre .DESCRIPTION Vous devez etre administrateur, si ce n'est pas le cas, une exception est montée Cette fonction retourne $True sur succès et $False sur echec Le chemin clé de registre est crée si il n'existe pas .PARAMETER Path Le chemin clé de registre au format HKEY_LOCAL_MACHINE\ .PARAMETER Property La propriété à modifier .PARAMETER Value Valeur de cette propriété. Peut-etre $Null .PARAMETER Type https://msdn.microsoft.com/en-us/powershell/reference/5.0/microsoft.powershell.management/new-itemproperty .OUTPUTS Boolean #> [CmdletBinding()] [OutputType([Boolean])] Param ( [Parameter(Mandatory = $True)] [ValidatePattern("^HKLM|HKCU")] [String]$Path, [Parameter(Mandatory = $True)] [String] $Property, [AllowNull()] $Value, [ValidateSet("String", "ExpandString", "Binary", "DWord", "MultiString", "Qword", "Unknown")] [String]$Type = "String" ) If (-not (Test-Registry -Path $Path)) { New-Item -Path $Path -Force | Out-Null } try { Set-ItemProperty -Path $Path -Name $Property -Type $Type -Value $Value -ErrorAction Stop | Out-Null $Output = $True } catch { $Output = $False Write-LogError ("Set-Registry|{0}!{1}|{2}|{3}" -f $Path, $Property, $Type, $Value) Write-LogException $_ } Write-LogDebug ("Set-Registry|{0}!{1}|{2}|{3}|{4}" -f $Path, $Property, $Type, $Value, $Output) } ################################################################################### # File system cmdlets ################################################################################### Function Get-FolderSize { <# .SYNOPSIS Retourne la taille d'un dossier en octet. .DESCRIPTION Le chemin du dossier doit exister. .OUTPUTS Int32 .PARAMETER Path Chemin absolue du dossier a traiter #> [CmdletBinding()] [OutputType([Int32])] Param ( [Parameter(Mandatory = $True)] [ValidateScript({Test-Path $_})] [String]$Path ) $Output = $Nul Try { $Output = Get-ChildItem -Path $Path -Recurse | Where-Object {$_.Mode -notmatch "^d"} | Measure-Object -Property "Length" -Sum | Select-Object -ExpandProperty Sum } Catch { Write-LogError "Erreur inconnu c'est produite durant le calcul de la taille pour le dossier $Path" Write-LogException $_ } Write-Output $Output } Function Get-FileVersion { <# .SYNOPSIS Renvoie la version du fichier .DESCRIPTION Le fichier doit exister .PARAMETER Path Chemin absolue du fichier .OUTPUTS Version du fichier #> [CmdletBinding()] [OutputType([String])] Param ( [Parameter(Mandatory = $True, Position = 0)] [ValidateScript({Test-Path $_})] [String]$Path ) $Item = Get-ItemProperty -LiteralPath $Path $Output = $Item.VersionInfo.FileVersion Write-LogDebug ("Get-FileVersion|{0}|{1}" -f $Path, $Output) Write-Output $Output } ################################################################################### # Windows cmdlets ################################################################################### Function Get-WindowsUpdate { <# .SYNOPSIS Retourne la liste des mises à jour disponibles .OUTPUTS Tableau de dictionnaires contenant - Titre - Description - KB #> [CmdletBinding()] [OutputType([Array])] Param() $Output = @() Try { $UpdateSession = New-Object -ComObject Microsoft.Update.Session $UpdateSearcher = $UpdateSession.CreateUpdateSearcher() $SearchResult = $UpdateSearcher.Search("IsInstalled = 0 and Type='Software' and IsHidden = 0") } Catch { $SearchResult = $null Write-LogError "Get-WindowsUpdate|Impossible de parler avec Windows Update" Write-LogException $_ } If ($Null -ne $SearchResult) { ForEach ($Update in $SearchResult.Updates) { $Output += @{ "title" = $Update.title "description" = $Update.description "kb" = $Update.KBArticleIDs | Split-Array } Write-LogDebug $($Output[-1] | Split-DebugOutput) } } Write-Output $Output # TODO: Valider fonctionnement } Function Test-IsAdmin { <# .SYNOPSIS Retourne vrai si le la session courante dispose de haut privilège .DESCRIPTION Monte une exception si fichier existe pas .INPUTS Aucune .OUTPUTS $True si Administrateur $False si pas Administrateur $Null si impossible à déterminer #> [CmdletBinding()] [OutputType([Boolean])] Param() $Output = $False Try { $Identity = [Security.Principal.WindowsIdentity]::GetCurrent() $Principal = New-Object Security.Principal.WindowsPrincipal -ArgumentList $Identity $Output = $Principal.IsInRole( [Security.Principal.WindowsBuiltInRole]::Administrator ) } Catch { $Output = $Null Write-LogError "Test-IsAdmin|Impossible de déterminer mes droits actuels" Write-LogException $_ } Write-Output $Output } Function Get-InstalledSoftware { <# .SYNOPSIS Liste les logiciels installés pour tous les utilisateurs .DESCRIPTION Ne prends que les clé de registre ou un champ "DisplayName" est présent .INPUTS Aucune .OUTPUTS Array[psobject] #> [CmdletBinding()] [OutputType([Array])] Param() Write-LogVerbose "Get-InstalledSoftware" $Output = @() $Paths = "HKLM:\SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall", "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall" Foreach ($Path in $Paths) { If (Test-Registry -Path $Path) { $Softwares = Get-ChildItem -Path $Path Foreach ($Software in $Softwares) { If ($Null -ne $Software.GetValue("DisplayName")) { $Output += New-Object PSObject -Property @{ "name" = [String]$Software.PSChildName "publisher" = [String]$Software.GetValue("Publisher") -replace "`0", "" #Supprime le charactere ASCII nul "version_major" = [String]$Software.GetValue("VersionMajor") "version_minor" = [String]$Software.GetValue("VersionMinor") "display_name" = [String]$Software.GetValue("DisplayName") "display_version" = [String]$Software.GetValue("DisplayVersion") } } } } } Write-LogDebug $Output Write-Output $Output } Function Get-WindowsSecurityProduct { Write-LogVerbose "Get-WindowsSecurityProduct" $Output = @() $OS = Get-WmiObject -Class Win32_OperatingSystem If ($OS.Caption -notmatch "server|xp") { $antivirus = Get-WmiObject -Class AntiVirusProduct -Namespace ROOT\SecurityCenter2 $antispyware = Get-WmiObject -Class AntiSpywareProduct -Namespace ROOT\SecurityCenter2 $firewall = Get-WmiObject -Class FirewallProduct -Namespace ROOT\SecurityCenter2 If ($Null -ne $antivirus) { $antivirus | ForEach-Object { $Output += New-Object PSObject -Property @{ "Type" = "antivirus" "Nom" = $_.DisplayName } } } If ($Null -ne $antispyware) { $antispyware | ForEach-Object { $Output += New-Object PSObject -Property @{ "Type" = "antispyware" "Nom" = $_.DisplayName } } } If ($Null -ne $firewall) { $firewall | ForEach-Object { $Output += New-Object PSObject -Property @{ "Type" = "firewall" "Nom" = $_.DisplayName } } } } Write-LogDebug $Output Write-Output $Output } ################################################################################### # Outlook cmdlets ################################################################################### Function Get-OutlookFile { <# .SYNOPSIS Retourne la lites des fichiers outlooks 2007 -> 2016 .OUTPUTS Liste de dictionnaire contenant : - Chemin du fichier - Sa taille #> [CmdletBinding()] [OutputType([Array])] Param() $Output = @() #OST $Extension = "*.ost" $Folders = @("C:\Users\*\AppData\Local\Microsoft\Outlook\", "C:\Documents and Settings\*\Local Settings\Application Data\Microsoft\Outlook\") $Output += Get-ChildItem -Path $Folders -Include $Extension -Recurse -Depth 1 #PAB .pab $Extension = "*.pab" $Folders = @("C:\Users\*\AppData\Local\Microsoft\Outlook\", "C:\Documents and Settings\*\Local Settings\Application Data\Microsoft\Outlook\") $Output += Get-ChildItem -Path $Folders -Include $Extension -Recurse -Depth 1 #SIGNATURE .rtf .txt .htm $Extension = "*.rtf", "*.txt", "*.htm" $Folders = @("C:\Users\*\AppData\Roaming\Microsoft\Signatures\", "C:\Documents and Settings\*\Application Data\Microsoft\Signatures\") $Output += Get-ChildItem -Path $Folders -Include $Extension -Recurse -Depth 1 #PST $Extension = "*.pst" $Folders = @("C:\Users\*\Documents\Fichiers Outlook\", "C:\Users\*\Mes Documents\Fichiers Outlook\", "C:\Users\*\Roaming\Local\Microsoft\Outlook\", "C:\Documents and Settings\*\Mes Documents\Fichiers Outlook\", "C:\Users\*\AppData\Local\Microsoft\Outlook\", "C:\Documents and Settings\*\Local Settings\Application Data\Microsoft\Outlook\") $Output += Get-ChildItem -Path $Folders -Include $Extension -Recurse -Depth 1 #RULES .rwz $Extension = "*.rwz" $Folders = @("C:\Users\*\AppData\Roaming\Microsoft\Outlook\", "C:\Documents and Settings\*\Application Data\Microsoft\Outlook\") $Output += Get-ChildItem -Path $Folders -Include $Extension -Recurse -Depth 1 #Windows Live Mail $Extension = "*.eml" $Folders = @("C:\Users\*\AppData\Local\Microsoft\Windows Live Mail") $Output += Get-ChildItem -Path $Folders -Include $Extension -Recurse -Depth 1 Write-Output ($Output | Select-Object -Property "FullName", "Length") } Function Get-OutlookExpress { <# .SYNOPSIS Retourne la lites des fichiers Outlook Express .OUTPUTS Liste de dictionnaire contenant : - Chemin du fichier - Sa taille #> [CmdletBinding()] [OutputType([Array])] Param() Process { #Outlook Express $Output = @() $Extension = "*.dbx" $Folders = @("C:\Documents and Settings\*\Local Settings\Application Data\Identities\") $Output += Get-ChildItem -Path $Folders -Include $Extension -Recurse Write-Output ($Output | Select-Object -Property "FullName", "Length") } } ################################################################################### # INTERBASE cmdlets ################################################################################### Function Find-InterbaseRoot { <# .SYNOPSIS Chercher Interbase dans plusieurs location .DESCRIPTION Ordre de recherche : - HKEY_LOCAL_MACHINE\SOFTWARE\Borland\InterBase\Servers\gds_db (Interbase XE) - HKEY_LOCAL_MACHINE\SOFTWARE\Borland\Interbase\CurrentVersion (Interbase 7) Si Interbase est trouvé, deux variables sont retournées : - InterbaseRoot - InterbaseClient Si Interbase n'est pas trouvé, ces deux variables sont définies à $Null .EXAMPLE $InterbaseRoot, $InterbaseClient = Find-InterbaseRoot .OUTPUTS Tableau de taille 2 #> [CmdletBinding()] [OutputType([Array])] Param() If (Test-Registry -Path 'HKLM:\SOFTWARE\Borland\InterBase\Servers\gds_db' -Property 'RootDirectory') { # Interbase XE $v = Get-Registry -Path 'HKLM:\SOFTWARE\Borland\InterBase\Servers\gds_db' -Property 'RootDirectory' $InterbaseRoot = $v $InterbaseClient = $v + '\bin\isql.exe' Write-LogDebug "Find-InterbaseRoot : Interbase XE" } ElseIf (Test-Registry -Path 'HKLM:\SOFTWARE\Borland\Interbase\CurrentVersion' -Property 'RootDirectory') { # Interbase 7 $v = Get-Registry -Path 'HKLM:\SOFTWARE\Borland\Interbase\CurrentVersion' -Property 'RootDirectory' $InterbaseRoot = $v $InterbaseClient = $v + '\bin\isql.exe' Write-LogDebug "Find-InterbaseRoot : Interbase 7" } Else { $InterbaseRoot = $Null $InterbaseClient = $Null Write-LogDebug "Find-InterbaseRoot : Rien trouve" } Write-Output $InterbaseRoot, $InterbaseClient } Function Invoke-iSQLQuerry { <# .SYNOPSIS Execute une requete dans une base de données local .DESCRIPTION Retourne un tableau <[boolean],[string]> Si [boolean] est $False, la requete c'est mal éxécutée Utilise c:\temp pour travailler. (fichier temporaire) .INPUTS Aucune .PARAMETER Query Requete a éxécuter .PARAMETER Database Chemin de la base de données Par défault, celui de "${GINKOIA_ROOT}\data\ginkoia.ib" .PARAMETER Page Nombre de ligne à retourner, par défault 30 .EXAMPLE Invoke-iSQLQuerry -Query "SELECT * FROM USERS" -Database #> [CmdletBinding()] [OutputType([Array])] Param ( [Parameter(Mandatory = $True)] [String] $Query, [ValidateScript({Test-Path $_})] [String] $Database = "${GINKOIA_ROOT}\data\ginkoia.ib", [Parameter()] [Int]$Page = 30 ) Write-LogDebug 'Invoke-iSQLQuerry' If ($null -eq $InterbaseClient) { Write-LogError('Requete Interbase desactivee') @($False, 'Requete Interbase desactivee') return } Set-Content -Path "C:\temp\isql.txt" -Value @( "CONNECT ${Database}" "user 'sysdba' password 'masterkey';" "${Query}" ) $Command = "& '$InterbaseClient' -page $Page -i C:\temp\isql.txt -q 2`>`&1" Write-LogDebug ("iSQL COMMAND {0}" -f $Command) $Out = [string[]] (Invoke-Expression "$Command") if ($Out[0] -Match "^Database") { $Out | Out-File C:\temp\isql.out.txt # $out[2] -> en-tete colone # $out[3] -> ligne des '=' $Result = @() If ([String]::IsNullOrEmpty($Out[2]) -or [String]::IsNullOrEmpty($Out[3])) { Write-LogInfo "ISQL vide" } else { $column_size = $Out[3] -split ' (?! *$)' $column = @() $column_size | ForEach-Object {$i = 0} { $column_name = $out[2].Substring($i, $_.Length) -replace '^ *', '' -replace ' *$', '' $column += @{ 'column_name' = $column_name 'start_index' = $i 'end_index' = $_.Length } $i += $_.Length + 1 } for ($i = 5; $i -lt $out.Length; $i++) { if (!([System.String]::IsNullOrEmpty($out[$i]))) { $line = $out[$i] $tmp = @{} $column | ForEach-Object { $tmp += @{ $_.column_name = $line.Substring($_.start_index, $_.end_index) -replace '^ *', '' -replace ' *$', '' } } $result += $tmp } } } $output = @($True, $result) } Else { $error_message = $out[2] -split '\r\n' $output = @($False, $error_message[0]) } Write-Output $output } Function Get-InterbaseVersion { <# .SYNOPSIS Retourne la version d'Interbase .DESCRIPTION Execute la requete SHOW VERSION; A besoin d'un client Interbase pour fonctionner .OUTPUTS String #> [CmdletBinding()] [OutputType([String])] Param() Write-LogDebug "Get-InterbaseVersion" If ($Null -eq $InterbaseClient) { Write-LogError "Requete Interbase desactivee" Write-Output "" Return } Set-Content -Path "C:\temp\isql.txt" -Value @( 'Show version;' ) $Command = "& '$InterbaseClient' -i C:\temp\isql.txt -q 2`>`&1" Write-LogDebug ("iSQL COMMAND {0}" -f $Command) $Version = [string] (Invoke-Expression "$Command") $Output = $Version -replace "ISQL Version: ", "" Write-Output $Output }