Voici 2 petits scripts qui vous permettront de retrouver sur quelles machines de l’Active Directory est installé un logiciel spécifique.
Ces 2 scripts produisent un fichier csv et un fichier log en sortie.
- Source du script 1
Retrouver un programme d’après sont répertoire d’installation (ici recherche de 7ZIP)
####################################################################################################
#
# Script Name: ScrollWKS1.ps1
#
# Author: EHX
# Version: 1.0
# Date: 15/12/2015
#
# Description: Balaye l'ensemble des postes de l'AD et teste la présence d'un pgm dans un dossier
#
####################################################################################################
Param(
[Parameter(Mandatory=$false)]
[String]$param1
)
Process{
Cls
#Region "Functions"
####################################################################################################
# Get-Script-Directory
####################################################################################################
Function Get-Script-Directory
{
$scriptInvocation = (Get-Variable MyInvocation -Scope 1).Value
return Split-Path $scriptInvocation.MyCommand.Path
}
####################################################################################################
# Add To Log
####################################################################################################
Function Log([String]$LogtoAdd)
{
Add-Content -Path $LogFilePath -Value $LogtoAdd
If ($LogtoAdd.Contains('ERROR')) { Write-Host $LogtoAdd -ForegroundColor Red } Else { Write-Host $LogtoAdd }
}
####################################################################################################
# End Log
####################################################################################################
Function EndLog
{
# Stop Timer
$Watch.Stop()
$ts = $Watch.Elapsed
[String]$Time = [system.String]::Format("{0:00}h:{1:00}m:{2:00}s.{3:00}ms", $ts.Hours, $ts.Minutes, $ts.Seconds, $ts.Milliseconds / 10)
Log
Log ("****************************************************************************")
Log
Log ("Traitement terminé à: " + [datetime]::Now + " - Temps de Traitement: " + $Time)
Log
Log ("****************************************************************************")
Log
Log
Log
}
####################################################################################################
# Exit Script
####################################################################################################
Function ExitScript
{
EndLog
Exit
}
####################################################################################################
# Check Error With Exit
####################################################################################################
Function CheckErrorWithExit
{
If ($error -ne $null) {
Log (" $error")
ExitScript
}
}
####################################################################################################
# Check Error With No Exit
####################################################################################################
Function CheckErrorWithNoExit
{
If ($error -ne $null) {
Log (" ERROR: $error")
}
}
####################################################################################################
# Connexion à l'AD
#################################################################################################
Function ConnectToAD
{
Import-Module ActiveDirectory
#Get a reference to the RootDSE of the current domain
$rootdse = Get-ADRootDSE
#Get a reference to the current domain
$domain = Get-ADDomain
log ("Domaine $domain")
}
#EndRegion
####################################################################################################
# Main Process
####################################################################################################
#Region "Main Process"
#---------------------------------------Variables Definition
$PathScript = Get-Script-Directory
$LogFileName = [System.IO.Path]::GetFileNameWithoutExtension($MyInvocation.MyCommand.Name)
$LogFilePath = $PathScript + "\" + $LogFileName + '.log'
$ResultFilePath = $PathScript + "\" + $LogFileName + '.csv'
$Computername = gc env:computername
$Watch = New-Object system.Diagnostics.Stopwatch #Timer
$PathYear = Get-Date -format yyyy
$PathMonth = Get-Date -format MM
$PathDay = Get-Date -format dd
$PathHour = Get-Date -format HH
$PathMin = Get-Date -format mm
$PathSec = Get-Date -format mm
$rootdse = ""
$domain = ""
$Count = 2
$connect = 0
$noconnect = 0
$install = 0
$obj = @()
$InstallRep = "C$\Program Files\7-Zip"
$InstallProg= "7z.exe"
#---------------------------------------Main Process
#Create Log File
If ((Test-Path $LogFilePath) -eq $False) {
$LogFile = [System.IO.File]::CreateText($LogFilePath)
$LogFile.Close()
}
#Write Eventlog if log file cannot be created
If ((Test-Path $LogFilePath) -eq $False) {
Write-Eventlog -LogName "Windows PowerShell" -Source PowerShell -EntryType Error -Eventid 100 -Message "Log file $LogFilePath cannot be created for script $LogFileName.ps1"
Exit
}
#Start Logging
Log ("****************************************************************************")
Log ("Processus démarré le : " + [datetime]::Now + " sur le poste: """ + $Computername + """")
Log ("Fichier Log : $LogFilePath")
log ("Fichier de résultats : $ResultFilePath")
Log ("****************************************************************************")
#Start Timer
$Watch.Start()
ConnectToAD
# Configure $ErrorActionPreference
$ErrorActionPreference = "SilentlyContinue"
# Recherche des machines dans l'AD
$Machines = Get-ADComputer -Filter * -Properties Name
# Traitement de chaque machine
foreach ($Machine in $Machines){
$Computer = $Machine.name
$textline = $Computer
# Machine introuvable (non pingable)
if (-not (test-connection $Computer -Quiet -Count $Count)){
$textline = $textline + ";non connecté"
$noconnect += 1
log ($textline)
continue
}
# Machine connectée
$textline = $textline + ";connecté"
$connect += 1
$rep = "\\$Computer\$Installrep\"
# Répertoire non trouvé
if (-not(test-path $rep)){
$textline = $textline + ";Répertoire inexistant"
log ($textline)
continue
}
# Répertoire trouvé
$install += 1
$textline = $textline + ";$InstallRep"
$file= Get-Item "\\$Computer\$InstallRep\$InstallProg"
$textline = $textline + ";$InstallProg;Version: "+ $file.VersionInfo.FileVersion
log ($textline)
$obj += New-Object -TypeName psObject -Property @{'Computer'=$Computer;'Folder'=$InstallRep;'File'=$InstallProg;'FileVersion'=$file.VersionInfo|Select FileVersion;'LastAccessTime'=$file.LastWriteTime}
}
#Fin de script
log ("----------------------------------")
log ("Machines non connectées $noconnect")
log ("Machines connectées $connect")
log ("Machines installées $install")
# Ecriture fichier csv
$obj | select computer, Folder, File, FileVersion, lastaccesstime | Export-Csv -Path "$ResultFilePath" -NoTypeInformation
Exitscript
#EndRegion
}
- Source du script 2
Retrouver un programme d’après une clé de la base de registre (ici recherche de 7ZIP)
####################################################################################################
#
# Script Name: ScrollWKS2.ps1
#
# Author: EHX
# Version: 1.0
# Date: 15/12/2015
#
# Description: Balaye l'ensemble des postes de l'AD et teste la présence d'un pgm dans la BDR
#
####################################################################################################
Param(
[Parameter(Mandatory=$false)]
[String]$param1
)
Process{
Cls
#Region "Functions"
####################################################################################################
# Get-Script-Directory
####################################################################################################
Function Get-Script-Directory
{
$scriptInvocation = (Get-Variable MyInvocation -Scope 1).Value
return Split-Path $scriptInvocation.MyCommand.Path
}
####################################################################################################
# Add To Log
####################################################################################################
Function Log([String]$LogtoAdd)
{
Add-Content -Path $LogFilePath -Value $LogtoAdd
If ($LogtoAdd.Contains('ERROR')) { Write-Host $LogtoAdd -ForegroundColor Red } Else { Write-Host $LogtoAdd }
}
####################################################################################################
# End Log
####################################################################################################
Function EndLog
{
# Stop Timer
$Watch.Stop()
$ts = $Watch.Elapsed
[String]$Time = [system.String]::Format("{0:00}h:{1:00}m:{2:00}s.{3:00}ms", $ts.Hours, $ts.Minutes, $ts.Seconds, $ts.Milliseconds / 10)
Log
Log ("****************************************************************************")
Log
Log ("Traitement terminé à: " + [datetime]::Now + " - Temps de Traitement: " + $Time)
Log
Log ("****************************************************************************")
Log
Log
Log
}
####################################################################################################
# Exit Script
####################################################################################################
Function ExitScript
{
EndLog
Exit
}
####################################################################################################
# Check Error With Exit
####################################################################################################
Function CheckErrorWithExit
{
If ($error -ne $null) {
Log (" $error")
ExitScript
}
}
####################################################################################################
# Check Error With No Exit
####################################################################################################
Function CheckErrorWithNoExit
{
If ($error -ne $null) {
Log (" ERROR: $error")
}
}
####################################################################################################
# Connexion à l'AD
#################################################################################################
Function ConnectToAD
{
Import-Module ActiveDirectory
#Get a reference to the RootDSE of the current domain
$rootdse = Get-ADRootDSE
#Get a reference to the current domain
$domain = Get-ADDomain
log ("Domaine $domain")
}
#EndRegion
####################################################################################################
# Main Process
####################################################################################################
#Region "Main Process"
#---------------------------------------Variables Definition
$PathScript = Get-Script-Directory
$LogFileName = [System.IO.Path]::GetFileNameWithoutExtension($MyInvocation.MyCommand.Name)
$LogFilePath = $PathScript + "\" + $LogFileName + '.log'
$ResultFilePath = $PathScript + "\" + $LogFileName + '.csv'
$Computername = gc env:computername
$Watch = New-Object system.Diagnostics.Stopwatch #Timer
$PathYear = Get-Date -format yyyy
$PathMonth = Get-Date -format MM
$PathDay = Get-Date -format dd
$PathHour = Get-Date -format HH
$PathMin = Get-Date -format mm
$PathSec = Get-Date -format mm
$rootdse = ""
$domain = ""
$Count = 2
$connect = 0
$noconnect = 0
$install = 0
$obj = @()
$Key = "LocalMachine"
$Subkey = "SOFTWARE\7-Zip"
$Value = "Path"
#---------------------------------------Main Process
#Create Log File
If ((Test-Path $LogFilePath) -eq $False) {
$LogFile = [System.IO.File]::CreateText($LogFilePath)
$LogFile.Close()
}
#Write Eventlog if log file cannot be created
If ((Test-Path $LogFilePath) -eq $False) {
Write-Eventlog -LogName "Windows PowerShell" -Source PowerShell -EntryType Error -Eventid 100 -Message "Log file $LogFilePath cannot be created for script $LogFileName.ps1"
Exit
}
#Start Logging
Log ("****************************************************************************")
Log ("Processus démarré le : " + [datetime]::Now + " sur le poste: """ + $Computername + """")
Log ("Fichier Log : $LogFilePath")
log ("Fichier de résultats : $ResultFilePath")
Log ("****************************************************************************")
#Start Timer
$Watch.Start()
ConnectToAD
# Configure $ErrorActionPreference
$ErrorActionPreference = "SilentlyContinue"
# Lit toutes les machines de l'AD
$Machines = Get-ADComputer -Filter * -Properties Name
# Traite chaque machine
foreach ($Machine in $Machines){
$Computer = $Machine.name
$textline = $Computer
# Machine non connectée (non pingable)
if (-not (test-connection $Computer -Quiet -Count $Count)){
$textline = $textline + ";non connecté"
$noconnect += 1
log ($textline)
continue
}
# Machine connectée
$textline = $textline + ";connecté"
$connect += 1
# Recherche de la clé
$version = ""
$Reg = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey($Key, $computer)
$RegKey = $Reg.OpenSubKey($SubKey)
$Version = $RegKey.GetValue($Value)
# clé trouvée
if ($Version){
$obj += New-Object -TypeName psObject -Property @{'Computer'=$Computer;'Key'=$Key;'SubKey'=$SubKey;'Version'=$Version}
$install += 1
$textline = $textline + " - Clé trouvée: $key\$subkey - Version: $version"
}
# clé non trouvée
else {
$textline = $textline + " - Clé non trouvée"
}
log ($textline)
}
#Fin de script
log ("----------------------------------")
log ("Machines non connectées $noconnect")
log ("Machines connectées $connect")
log ("Machines installées $install")
#Ecriture fichier résultat
$obj | select computer, Key, SubKey, Version | Export-Csv -Path "$ResultFilePath" -NoTypeInformation
Exitscript
#EndRegion
}