├── .gitattributes ├── APP-Deploy └── CITRIX-Receiver-14.6.0.12010-Install.bat ├── ActiveDirectory ├── Add-ContactToAD.ps1 ├── Create-ContactsOnAD.ps1 ├── Create-ContactsOnAD.ps1--template.csv ├── Export-ADGroupMemberToCSV │ └── Export-ADGroupMemberToCSV.ps1 ├── Export-GPOSettings.ps1 ├── ListADObjectsOnSelectedOU.ps1 └── ListADObjectsOnSelectedOU │ ├── ListADObjectsOnSelectedOU.ps1 │ ├── bufferCommand.txt │ ├── logging │ └── Logging.ps1 │ └── utilities │ ├── ADDS.ps1 │ └── Utils.ps1 ├── ActiveDirectoryCertificateServices ├── Get-ADCS_Report.ps1 └── PS PKI v3.1.0.exe ├── Bitlocker └── Backup-BitlockerRecoveryKeyToAD.ps1 ├── DHCP └── Backup-DHCPLeases.ps1 ├── Domoticz └── functions.ps1 ├── Exchange └── EnableOnlineArchive.ps1 ├── FSRM └── New-FSRMQuota.ps1 ├── Hyper-V ├── Create-HyperV_VM.ps1 └── Delete-HyperV_VM.ps1 ├── LICENSE ├── LocalUsersAndGroups ├── Create-LocalAdminAccount.ps1 └── Replace-LocalAdminPassword.ps1 ├── Miscellaneous ├── Create-Shortcut.ps1 ├── DecodeFileFromBase64 │ └── DecodeFileFromBase64.ps1 ├── EncodeFileToBase64 │ └── EncodeFileToBase64.ps1 ├── Get-MicrosoftLicenceStatus.ps1 ├── Mount-NetworkDrive ├── New-IsoFile.ps1 ├── SearchAndListObject-WithRegularExpression │ └── SearchAndListObject-WithRegularExpression.ps1 ├── Show-BalloonNotificationThenStartProcessOnUserClick.ps1 ├── Start-MSRA.ps1 └── Store-SecurestringToFile.ps1 ├── Network Policy Server └── Check_NPS_WorkStation_Prerequisites.ps1 ├── Network ├── Ping-Host.ps1 ├── Test-Port.ps1 └── TestServerPortConnectivity.ps1 ├── Office-365 ├── Add-DelegationRights--template.csv ├── Add-DelegationRights.ps1 ├── Add-LDAPAddressBook │ ├── LdapABManager_ABConfiguration.xml │ ├── LdapABManager_x64.exe │ ├── LdapABManager_x86.exe │ ├── Office-x64.bat │ └── Office-x86.bat ├── Add-UserToSharedMailbox │ ├── Add-UserToSharedMailbox.csv │ └── Add-UserToSharedMailbox.ps1 ├── Check-Office2016Activation.ps1 ├── Get-CopyOnSharedboxForSendAsAndSendOnBehalfMessage.ps1 ├── Get-MailboxUsage.ps1 ├── Set-DefaultUserAsRoomsCalenderReviewer.ps1 ├── Set-Office365Signature.ps1 └── Update-UPNandLicence.ps1 ├── Office └── Get-OfficeInstalledVersion.ps1 ├── Outlook ├── Create-Rule_PopupWhenMessageWithAttachment.ps1 ├── Import-PST.ps1 ├── List-AllMailboxAndPST.ps1 └── Replace-MailSuffixOnADUserObject.ps1 ├── PrepareServer ├── 1-AddAdPrereqs.ps1 ├── bufferCommand.txt ├── logging │ └── Logging.ps1 └── utilities │ ├── ADDS.ps1 │ └── Utils.ps1 ├── Printing └── Declare-PrintDrivers.ps1 ├── README.md ├── ScheduledTasks └── Set-ScheduledTaskCredential.ps1 ├── Security └── Submit-SuspiciousFilesToMalwrCOM │ └── Submit-SuspiciousFilesToMalwrCOM.ps1 ├── VMware Workstation └── Start-VMwareWorkstationServices.ps1 └── WSUS └── Get-ComputersToRebootAfterUpdate.ps1 /.gitattributes: -------------------------------------------------------------------------------- 1 | # Auto detect text files and perform LF normalization 2 | * text=auto 3 | 4 | # Custom for Visual Studio 5 | *.cs diff=csharp 6 | 7 | # Standard to msysgit 8 | *.doc diff=astextplain 9 | *.DOC diff=astextplain 10 | *.docx diff=astextplain 11 | *.DOCX diff=astextplain 12 | *.dot diff=astextplain 13 | *.DOT diff=astextplain 14 | *.pdf diff=astextplain 15 | *.PDF diff=astextplain 16 | *.rtf diff=astextplain 17 | *.RTF diff=astextplain 18 | -------------------------------------------------------------------------------- /APP-Deploy/CITRIX-Receiver-14.6.0.12010-Install.bat: -------------------------------------------------------------------------------- 1 | REM 2 | REM DATE: Feb 20, 2017 3 | REM VERSION: 0.4 4 | REM INPUTS: (1) Current version of Citrix package 5 | REM (2) Current Version of Citrix WebHelper module 6 | REM (3) Package Location/Deployment Directory 7 | REM (4) Script Logging Directory 8 | REM (5) Package Installer Command Line Options 9 | REM 10 | REM CHANGELOG: v0.1 - 25.01.2017 - Initial write 11 | REM v0.2 - 10.02.2017 - Add ',DesktopViewer' to (4) 12 | REM v0.3 - 16.02.2017 - Add a verification on WebHelper version (new (2) parameter) 13 | REM Redefine parameters 14 | REM Add version of Citrix package and Citrix DesktopViewer module version on log 15 | REM v0.4 - 20.02.2017 - Add few steps to verify Citrix presence, then DesktopViewer version 16 | REM If Citrix present, then check DesktopViewer version 17 | REM If DesktopViewer not present/ with bad version, then uninstall and reinstall Citrix with DesktopViewer 18 | REM 19 | REM 20 | REM (1) Current version of Citrix package 21 | Set DesiredVersion=14.6.0.12010 22 | REM 23 | REM (2) Current version of Citrix WebHelper module 24 | Set DesiredDesktopViewerVersion=14.6.0.12010 25 | REM 26 | REM (3) Package Location/Deployment Directory 27 | Set DeployDirectory=\\contorso.dom\SYSVOL\contorso.dom\scripts\Citrix\ 28 | REM 29 | REM (4) SCRIPT LOGGING DIRECTORY 30 | Set logshare=\\contorso.dom\SYSVOL\contorso.dom\scripts\Citrix\logs\ 31 | REM 32 | REM (5) PACKAGE INSTALLER COMMAND LINE OPTIONS 33 | Set CommandLineOptions=/noreboot /silent /EnableTracing=true /rcu /EnableCEIP=false /ALLOWADDSTORE=N ADDLOCAL=ICA_Client,WebHelper,DesktopViewer 34 | REM 35 | REM Start 36 | echo %date% %time% %ComputerName% [INFO] The %0 script is running >> %logshare%global.log 37 | REM Check if the machine is 64bit 38 | IF NOT "%ProgramFiles(x86)%"=="" SET WOW6432NODE=WOW6432NODE\ 39 | REM 40 | REM Check if Citrix is installed 41 | REM 42 | IF EXIST "C:\Program Files (x86)\Citrix\ICA Client\redirector.exe" (goto CheckPackagePresence) else (goto CitrixNotFound) 43 | REM Check if the Desired plug-in is installed 44 | REM 45 | :CheckPackagePresence 46 | reg query "HKEY_LOCAL_MACHINE\SOFTWARE\%WOW6432NODE%Citrix\PluginPackages\XenAppSuite\DesktopViewer" | findstr %DesiredDesktopViewerVersion% 47 | if %errorlevel%==1 (goto PackageNotFound) else (goto End) 48 | REM 49 | :CitrixNotFound 50 | echo %date% %time% %ComputerName% [WARNING] Citrix not detected, Begin Deployment >> %logshare%global.log 51 | start /wait %DeployDirectory%\CitrixReceiver%DesiredVersion%.exe DONOTSTARTCC=1 %CommandLineOptions% 52 | if %errorlevel% neq 0 (goto BadInstall) else (goto End) 53 | 54 | :PackageNotFound 55 | echo %date% %time% %ComputerName% [WARNING] DesktopViewer package not detected, Begin Deployment >> %logshare%global.log 56 | start /wait %DeployDirectory%\CitrixReceiver%DesiredVersion%.exe /uninstall /noreboot /silent 57 | start /wait %DeployDirectory%\CitrixReceiver%DesiredVersion%.exe DONOTSTARTCC=1 %CommandLineOptions% 58 | if %errorlevel% neq 0 (goto BadInstall) else (goto End) 59 | 60 | :BadInstall 61 | echo %date% %time% %ComputerName% [ERROR] %DesiredVersion% %DesiredDesktopViewerVersion% Deployment ended with error code %errorlevel%. >>%logshare%global.log 62 | 63 | :End 64 | echo %date% %time% %ComputerName% [INFO] %DesiredVersion% %DesiredDesktopViewerVersion% Deployment ended with error code %errorlevel%. >>%logshare%global.log 65 | exit 0 66 | -------------------------------------------------------------------------------- /ActiveDirectory/Add-ContactToAD.ps1: -------------------------------------------------------------------------------- 1 | Add-Type -AssemblyName System.Windows.Forms 2 | 3 | $PathDesktop = 'C:' + $env:HOMEPATH + '\Desktop' 4 | $ContactOU = 'OU=Contacts,OU=Users,DC=domain,DC=dom' 5 | 6 | function Select-FileDialog 7 | { 8 | [CmdletBinding()] 9 | param ([string]$Title, 10 | [string]$Filter = 'All files *.*|*.*') 11 | Add-Type -AssemblyName System.Windows.Forms | Out-Null 12 | $fileDialogBox = New-Object -TypeName Windows.Forms.OpenFileDialog 13 | $fileDialogBox.ShowHelp = $false 14 | $fileDialogBox.initialDirectory = $PathDesktop 15 | $fileDialogBox.filter = $Filter 16 | $fileDialogBox.Title = $Title 17 | $Show = $fileDialogBox.ShowDialog() 18 | 19 | if ($Show -eq 'OK') 20 | { 21 | Return $fileDialogBox.FileName 22 | } 23 | Else 24 | { 25 | Write-Error -Message 'Opération annulée' 26 | [Windows.Forms.MessageBox]::Show("Le script n'est pas en mesure de continuer. Opération stoppée.", 'Opération stoppée', 0, [Windows.Forms.MessageBoxIcon]::Error) 27 | Stop-TranscriptOnLog 28 | Exit 29 | } 30 | } 31 | 32 | # Disclaimer 33 | $Disclaimer = [Windows.Forms.MessageBox]::Show( 34 | " 35 | Ce script a pour but de rajouter des contacts dans l'Active Directory. 36 | Pour cela, il injecte des données venant d'un fichier .csv. 37 | 38 | 39 | /!\ Attention /!\ 40 | 41 | Si vous n'êtes pas sûr des actions à mener ou de l'impact, quitter ce script dès à présent. 42 | 43 | Souhaitez-vous continuer ? 44 | 45 | 46 | ", "Active Directory - Ajout de contact", 1, [Windows.Forms.MessageBoxIcon]::Question) 47 | If ($Disclaimer -eq "OK") 48 | { 49 | Write-Host 'Patientez, traitement en cours ...' 50 | } 51 | Else 52 | { 53 | Write-Error -Message 'Opération annulée' 54 | [Windows.Forms.MessageBox]::Show("Le script n'est pas en mesure de continuer. Opération stoppée.", 'Opération stoppée', 0, [Windows.Forms.MessageBoxIcon]::Error) 55 | Stop-TranscriptOnLog 56 | Exit 57 | } 58 | 59 | Import-Module ActiveDirectory 60 | 61 | ##region Import information coming from input .CSV file 62 | # Import CSV file 63 | [Windows.Forms.MessageBox]::Show( 64 | " 65 | Sélectionner dans cette fenêtre le fichier contenant : 66 | - Le 'Prénom' du contact à créer 67 | - Le 'Nom' du contact à créer () 68 | - L'adresse e-mail du contact à créer 69 | 70 | 71 | Le fichier doit être de la forme suivante : 72 | 73 | Prenom NOM Mail Mobile Titre Service Bureau Societe Adresse Ville CP TelSociete FaxSociete 74 | John Doe john.doe@dom.com 0601234567 Admin Sys IT 1 Microsoft 123 Rue des lilas Paris 75001 0401234567 0401234444 75 | Jane Roe jane.roe@dom.com 0701234567 DevOps Developpment 2 Apple 456 Allée des roses Lyon 69001 0489012345 0489104444 76 | 77 | ", "Office 365 - Ajout de contact", 0, [Windows.Forms.MessageBoxIcon]::Question) 78 | 79 | # Import list of users and related sharedmailbox and rights 80 | $CSVInputFile = Select-FileDialog -Title 'Select CSV file' -Filter 'Fichier CSV (*.csv) |*.csv' 81 | $csvValues = Import-Csv $CSVInputFile -Delimiter ';' 82 | #endregion Import information coming from input .CSV file 83 | 84 | #region Apply modification 85 | foreach ($line in $csvValues) 86 | { 87 | $UserFirstName = $line.'Prenom' 88 | $UserLASTNAME = $line.'Nom'.ToUpper() 89 | $UserName = $UserFirstName + ' ' + $UserLASTNAME 90 | $UserMailAddress = $line.Mail 91 | $UserMobile = $line.'Mobile' 92 | $UserTitle = $line.'Titre' 93 | $UserDepartment = $line.'Service' 94 | $UserCompanyOffice = $line.'Bureau' 95 | $UserCompanyName = $line.'Societe' 96 | $UserCompanyAddress = $line.'Adresse' 97 | $UserCompanyCity = $line.'Ville' 98 | $UserCompanyPostalCode = $line.CP 99 | $UserCompanyPhoneLine = $line.'TelSociete' 100 | $UserCompanyFax = $line.'FaxSociete' 101 | 102 | Write-Host 'Création du contact' $UserName $UserMailAddress $UserMobile $UserTitle $UserDepartment $UserCompanyOffice $UserCompanyName $UserCompanyAddress $UserCompanyCity $UserCompanyPostalCode $UserCompanyPhoneLine $UserCompanyFax 103 | New-ADObject -Type Contact -Name $UserName -Path $ContactOU -OtherAttributes @{ 'displayName' = $UserName; 'mail' = $UserMailAddress; 'proxyAddresses' = $UserMailAddress; 'givenName' = $UserFirstName; 'sn' = $UserLASTNAME; 'physicalDeliveryOfficeName' = $UserCompanyOffice; 'telephoneNumber' = $UserCompanyPhoneLine; 'mobile' = $UserMobile; 'facsimileTelephoneNumber' = $UserCompanyFax; 'streetAddress' = $UserCompanyAddress; 'l' = $UserCompanyCity; 'postalCode' = $UserCompanyPostalCode; 'c' = 'FR'; 'Title' = $UserTitle; 'department' = $UserDepartment; 'company' = $UserCompanyName } 104 | } 105 | #endregion Apply modification 106 | 107 | #region Show MessageBox to confirm action 108 | [Windows.Forms.MessageBox]::Show( 109 | "Action menée avec succès 110 | ", "ActiveDirectory - Ajout de contact", 0, [Windows.Forms.MessageBoxIcon]::Information) 111 | #endregion Show MessageBox to confirm action 112 | -------------------------------------------------------------------------------- /ActiveDirectory/Create-ContactsOnAD.ps1: -------------------------------------------------------------------------------- 1 | Add-Type -AssemblyName System.Windows.Forms 2 | 3 | $PathDesktop = 'C:' + $env:HOMEPATH + '\Desktop' 4 | $ContactOU = 'OU=Contacts,OU=Utilisateurs,DC=contoso,DC=local' 5 | $DomainController = 'DomainController1' 6 | 7 | function Select-FileDialog 8 | { 9 | [CmdletBinding()] 10 | param ([string]$Title, 11 | [string]$Filter = 'All files *.*|*.*') 12 | Add-Type -AssemblyName System.Windows.Forms | Out-Null 13 | $fileDialogBox = New-Object -TypeName Windows.Forms.OpenFileDialog 14 | $fileDialogBox.ShowHelp = $false 15 | $fileDialogBox.initialDirectory = $PathDesktop 16 | $fileDialogBox.filter = $Filter 17 | $fileDialogBox.Title = $Title 18 | $Show = $fileDialogBox.ShowDialog() 19 | 20 | if ($Show -eq 'OK') 21 | { 22 | Return $fileDialogBox.FileName 23 | } 24 | Else 25 | { 26 | Write-Error -Message 'Opération annulée' 27 | [Windows.Forms.MessageBox]::Show("Le script n'est pas en mesure de continuer. Opération stoppée.", 'Opération stoppée', 0, [Windows.Forms.MessageBoxIcon]::Error) 28 | Stop-TranscriptOnLog 29 | Exit 30 | } 31 | } 32 | 33 | # Disclaimer 34 | $Disclaimer = [Windows.Forms.MessageBox]::Show( 35 | " 36 | Ce script a pour but de rajouter des contacts dans l'Active Directory. 37 | Pour cela, il injecte des données venant d'un fichier .csv. 38 | 39 | 40 | /!\ Attention /!\ 41 | 42 | Si vous n'êtes pas sûr des actions à mener ou de l'impact, quitter ce script dès à présent. 43 | 44 | Souhaitez-vous continuer ? 45 | 46 | 47 | ", "Active Directory - Ajout de contact", 1, [Windows.Forms.MessageBoxIcon]::Question) 48 | If ($Disclaimer -eq "OK") 49 | { 50 | Write-Host 'Patientez, traitement en cours ...' 51 | } 52 | Else 53 | { 54 | Write-Error -Message 'Opération annulée' 55 | [Windows.Forms.MessageBox]::Show("Le script n'est pas en mesure de continuer. Opération stoppée.", 'Opération stoppée', 0, [Windows.Forms.MessageBoxIcon]::Error) 56 | Stop-TranscriptOnLog 57 | Exit 58 | } 59 | 60 | Import-Module ActiveDirectory 61 | 62 | ##region Import information coming from input .CSV file 63 | # Import CSV file 64 | [Windows.Forms.MessageBox]::Show( 65 | " 66 | Sélectionner dans cette fenêtre le fichier contenant : 67 | - Le 'Prénom' du contact à créer 68 | - Le 'Nom' du contact à créer () 69 | - L'adresse e-mail du contact à créer 70 | 71 | 72 | Le fichier doit être de la forme suivante : 73 | 74 | Prénom NOM Mail 75 | John DOE john.doe@dom.com 76 | Jane ROE jane.roe@dom.com 77 | 78 | ", "Office 365 - Ajout de contact", 0, [Windows.Forms.MessageBoxIcon]::Question) 79 | 80 | # Import list of users and related sharedmailbox and rights 81 | $CSVInputFile = Select-FileDialog -Title 'Select CSV file' -Filter 'Fichier CSV (*.csv) |*.csv' 82 | $csvValues = Import-Csv $CSVInputFile -Delimiter ';' 83 | #endregion Import information coming from input .CSV file 84 | 85 | #region Apply modification 86 | foreach ($line in $csvValues) 87 | { 88 | $UserFirstName = $line.'Prenom' 89 | $UserLASTNAME = $line.'Nom'.ToUpper() 90 | $UserName = $UserFirstName + ' ' + $UserLASTNAME 91 | $UserDescription = $line.'Description' 92 | $UserMailAddress = $line.'Mail' 93 | $UserMobile = $line.'Mobile' 94 | $UserTitle = $line.'Titre' 95 | $UserDepartment = $line.'Service' 96 | $UserCompanyOffice = $line.'Bureau' 97 | $UserCompanyName = $line.'Societe' 98 | $UserCompanyAddress = $line.'Adresse' 99 | $UserCompanyCity = $line.'Ville' 100 | $UserCompanyPostalCode = $line.'CP' 101 | $UserCompanyPhoneLine = $line.'TelSociete' 102 | $UserCompanyFax = $line.'FaxSociete' 103 | 104 | Write-Host 'Création du contact' $UserName $UserMailAddress $UserMobile $UserTitle $UserDepartment $UserCompanyOffice $UserCompanyName $UserCompanyAddress $UserCompanyCity $UserCompanyPostalCode $UserCompanyPhoneLine $UserCompanyFax 105 | New-ADObject -Type Contact -Server $DomainController -Name $UserName -Path $ContactOU -OtherAttributes @{ 'displayName' = $UserName; 'description' = $UserDescription; 'mail' = $UserMailAddress; 'proxyAddresses' = $UserMailAddress; 'givenName' = $UserFirstName; 'sn' = $UserLASTNAME; 'physicalDeliveryOfficeName' = $UserCompanyOffice; 'telephoneNumber' = $UserCompanyPhoneLine; 'mobile' = $UserMobile; 'facsimileTelephoneNumber' = $UserCompanyFax; 'streetAddress' = $UserCompanyAddress; 'l' = $UserCompanyCity; 'postalCode' = $UserCompanyPostalCode; 'c' = 'FR'; 'Title' = $UserTitle; 'department' = $UserDepartment; 'company' = $UserCompanyName } 106 | } 107 | #endregion Apply modification 108 | 109 | #region Show MessageBox to confirm action 110 | [Windows.Forms.MessageBox]::Show( 111 | "Action menée avec succès. 112 | ", "ActiveDirectory - Ajout de contact", 0, [Windows.Forms.MessageBoxIcon]::Information) 113 | #endregion Show MessageBox to confirm action 114 | -------------------------------------------------------------------------------- /ActiveDirectory/Create-ContactsOnAD.ps1--template.csv: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wikijm/PowerShell-AdminScripts/0f52701924d72a72b74f718cf7a4ce45ff27dbca/ActiveDirectory/Create-ContactsOnAD.ps1--template.csv -------------------------------------------------------------------------------- /ActiveDirectory/Export-ADGroupMemberToCSV/Export-ADGroupMemberToCSV.ps1: -------------------------------------------------------------------------------- 1 | #requires -version 2 2 | <# 3 | .SYNOPSIS 4 | This script get list of users on an AD Group and export it to CSV file 5 | .DESCRIPTION 6 | This script get list of users on an AD Group and export it to CSV file with name, objectClass and SamAccountName 7 | .INPUTS 8 | AD Group name 9 | .OUTPUTS 10 | CSV file widefined with $CSVExport 11 | .NOTES 12 | Version: 1.0 13 | Author: ALBERT Jean-Marc 14 | Creation Date: 05/02/2016 15 | Purpose/Change: 1.0 - 2016.02.05 - ALBERT Jean-Marc - Initial script development 16 | .EXAMPLE 17 | N/A 18 | #> 19 | #---------------------------------------------------------[Initialisations]-------------------------------------------------------- 20 | #Set Error Action to Silently Continue 21 | Add-Type -AssemblyName System.Windows.Forms 22 | $ErrorActionPreference = "SilentlyContinue" 23 | 24 | #----------------------------------------------------------[Declarations]---------------------------------------------------------- 25 | #Script Version 26 | $sScriptVersion = "1.0" 27 | 28 | $ADGroupName = "" 29 | $CSVExport = "" 30 | 31 | #-----------------------------------------------------------[Functions]------------------------------------------------------------ 32 | <# 33 | Empty 34 | #> 35 | 36 | #------------------------------------------------------------[Actions]------------------------------------------------------------- 37 | 38 | Get-ADGroupMember -Identity $ADGroupName | Select-Object name,objectClass,SamAccountName | Export-CSV $CSVExport -Encoding UTF8 -NoType -Force 39 | 40 | # Show an information message 41 | [System.Windows.Forms.MessageBox]::Show("All .pst from $PSTfolder were imported to Outlook" , "Information" , 0, [Windows.Forms.MessageBoxIcon]::Information) 42 | 43 | # End Script 44 | -------------------------------------------------------------------------------- /ActiveDirectory/Export-GPOSettings.ps1: -------------------------------------------------------------------------------- 1 | $GPOSettingsFolderPath = "D:\Scripts\AD-ExportGPOSettings\" 2 | $GPOSettingsResultFolderPath = $GPOSettingsFolderPath + "\Results\" 3 | 4 | cd $GPOSettingsFolderPath 5 | 6 | Get-GPO -All | % {$_.GenerateReport('html') | Out-File "$($_.DisplayName).htm"} 7 | Get-GPO -All | % {$_.GenerateReport('xml') | Out-File "$($_.DisplayName).xml"} 8 | 9 | Get-ChildItem *.xml | ForEach-Object { $NewName = $_.BaseName + "_" + $_.LastWriteTime.toString("yyyy.MM.dd.HH.mm") + ".xml" ; Rename-Item -Path $_.FullName -newname $NewName } 10 | Get-ChildItem *.htm | ForEach-Object { $NewName = $_.BaseName + "_" + $_.LastWriteTime.toString("yyyy.MM.dd.HH.mm") + ".htm" ; Rename-Item -Path $_.FullName -newname $NewName } 11 | 12 | If (!(Test-Path -Path $GPOSettingsResultFolderPath)) { 13 | New-Item -ItemType "Directory" -Path $GPOSettingsResultFolderPath -Force 14 | } 15 | 16 | Get-ChildItem *.xml -Recurse | Move-Item -Destination $GPOSettingsResultFolderPath 17 | Get-ChildItem *.htm -Recurse | Move-Item -Destination $GPOSettingsResultFolderPath 18 | -------------------------------------------------------------------------------- /ActiveDirectory/ListADObjectsOnSelectedOU/ListADObjectsOnSelectedOU.ps1: -------------------------------------------------------------------------------- 1 | #requires -version 2 2 | <# 3 | .SYNOPSIS 4 | List all AD Objects on a selected OU, and export results into a CSV 5 | 6 | .DESCRIPTION 7 | List all AD objects on a graphically selected OU, and export results into a CSV (CommonName and Description) 8 | 9 | .INPUTS 10 | User Interface 11 | 12 | .OUTPUTS 13 | Create transcript log file similar to $ScriptDir\[SCRIPTNAME]_[YYYY_MM_DD]_[HHhMMmSSs].log 14 | Create a list of AD Objects, similar to $ScriptDir\[SCRIPTNAME]_FoundADObjects_[YYYY_MM_DD]_[HHhMMmSSs].csv 15 | 16 | 17 | .NOTES 18 | Version: 1.1 19 | Author: ALBERT Jean-Marc 20 | Creation Date: 15/07/2015 21 | Purpose/Change: 1.0 - 2015.07.15 - ALBERT Jean-Marc - Initial script development 22 | 1.1 - 2015.07.16 - ALBERT Jean-Marc - Optimize code (minification) 23 | 1.2 - 2015.07.17 - ALBERT Jean-Marc - Add sAMAccountName and homedirectory to "Get-ADObject parameters" 24 | 1.3 - 2015.09.12 - ALBERT Jean-Marc - Use functions defined on external .ps1 files 25 | 1.4 - 2016.10.31 - ALBERT Jean-Marc - Add missing .NET Assembly and replace $global:streamWriter per $script:streamWriter 26 | 27 | 28 | .SOURCES 29 | 30 | 31 | .EXAMPLE 32 | 33 | #> 34 | 35 | #---------------------------------------------------------[Initialisations]-------------------------------------------------------- 36 | Add-Type -AssemblyName System.Windows.Forms 37 | Set-StrictMode -version Latest 38 | 39 | $scriptPath = split-path -parent $MyInvocation.MyCommand.Definition 40 | $scriptFile = $MyInvocation.MyCommand.Definition 41 | $launchDate = get-date -f "yyyy.MM.dd-HHhmmmss" 42 | $logDirectoryPath = $scriptPath + "\" + $launchDate 43 | $buffer = "$scriptPath\bufferCommand.txt" 44 | $fullScriptPath = (Resolve-Path -Path $buffer).Path 45 | 46 | $loggingFunctions = "$scriptPath\logging\Logging.ps1" 47 | $utilsFunctions = "$scriptPath\utilities\Utils.ps1" 48 | $addsFunctions = "$scriptPath\utilities\ADDS.ps1" 49 | 50 | 51 | #----------------------------------------------------------[Declarations]---------------------------------------------------------- 52 | 53 | $scriptName = [System.IO.Path]::GetFileName($scriptFile) 54 | $scriptVersion = "1.4" 55 | 56 | if(!(Test-Path $logDirectoryPath)) { 57 | New-Item $logDirectoryPath -type directory | Out-Null 58 | } 59 | 60 | $logFileName = "Log_" + $launchDate + ".log" 61 | $logPathName = "$logDirectoryPath\$logFileName" 62 | 63 | $script:streamWriter = New-Object System.IO.StreamWriter $logPathName 64 | 65 | #Define CSV file export of AD Group objects 66 | $CSVExportADObjects = "$ScriptPath\$scriptFile" + "_" + "FoundADObjects" + "_" + $launchDate + ".csv" 67 | 68 | 69 | #-----------------------------------------------------------[Functions]------------------------------------------------------------ 70 | 71 | . $loggingFunctions 72 | . $utilsFunctions 73 | . $addsFunctions 74 | 75 | 76 | #----------------------------------------------------------[Execution]---------------------------------------------------------- 77 | 78 | Start-Log -scriptName $scriptName -scriptVersion $scriptVersion -streamWriter $script:streamWriter 79 | Clear-Host 80 | Write-Host "================================================================================================" 81 | 82 | # Prerequisites 83 | if($adminFlag -eq $false){ 84 | Write-Host "You have to launch this script with " -nonewline; Write-Host "local Administrator rights!" -f Red 85 | $scriptPath = Split-Path $MyInvocation.InvocationName 86 | $RWMC = $scriptPath + "\$scriptName.ps1" 87 | $ArgumentList = 'Start-Process -FilePath powershell.exe -ArgumentList \"-ExecutionPolicy Bypass -File "{0}"\" -Verb Runas' -f $RWMC; 88 | Start-Process -FilePath powershell.exe -ArgumentList $ArgumentList -Wait -NoNewWindow; 89 | Stop-Script 90 | } 91 | 92 | Write-Host "================================================================================================" 93 | 94 | # Execute action with a progressbar 95 | Write-Progress -Activity "Starting GUI to select OU" -status "Running..." -id 1 96 | # Call OnApplicationLoad to initialize 97 | If((OnApplicationLoad) -eq $true) { 98 | #Call the form 99 | Call-AD_OU_select_pff | Out-Null 100 | #Perform cleanup 101 | OnApplicationExit 102 | } 103 | 104 | # Show selected OU on a messagebox 105 | [System.Windows.Forms.MessageBox]::Show("Selected OU: $objSelectedOU" , "Information" , 0, [Windows.Forms.MessageBoxIcon]::Information) 106 | 107 | 108 | # Writing informations in the log file 109 | Write-Progress -Activity "Write informations in the log file" -status "Running..." -id 1 110 | 111 | End-Log -streamWriter $script:streamWriter 112 | Stop-ScriptMessageBox 113 | notepad $logPathName 114 | Clear-Host 115 | -------------------------------------------------------------------------------- /ActiveDirectory/ListADObjectsOnSelectedOU/bufferCommand.txt: -------------------------------------------------------------------------------- 1 | dw 0000000000000000 -------------------------------------------------------------------------------- /ActiveDirectory/ListADObjectsOnSelectedOU/logging/Logging.ps1: -------------------------------------------------------------------------------- 1 | Function Start-Log { 2 | [CmdletBinding()] 3 | Param ([Parameter(Mandatory=$true)][string]$scriptName, [Parameter(Mandatory=$true)][string]$scriptVersion, 4 | [Parameter(Mandatory=$true)][string]$streamWriter) 5 | Process{ 6 | $global:streamWriter.WriteLine("================================================================================================") 7 | $global:streamWriter.WriteLine("[$ScriptName] version [$ScriptVersion] started at $([DateTime]::Now)") 8 | $global:streamWriter.WriteLine("================================================================================================`n") 9 | } 10 | } 11 | 12 | Function Write-Log { 13 | [CmdletBinding()] 14 | Param ([Parameter(Mandatory=$true)][string]$streamWriter, [Parameter(Mandatory=$true)][string]$infoToLog) 15 | Process{ 16 | $global:streamWriter.WriteLine("$infoToLog") 17 | } 18 | } 19 | 20 | Function Write-Error { 21 | [CmdletBinding()] 22 | Param ([Parameter(Mandatory=$true)][string]$streamWriter, [Parameter(Mandatory=$true)][string]$errorCaught, [Parameter(Mandatory=$true)][boolean]$forceExit) 23 | Process{ 24 | $global:streamWriter.WriteLine("Error: [$errorCaught]") 25 | if ($forceExit -eq $true){ 26 | End-Log -streamWriter $global:streamWriter 27 | break; 28 | } 29 | } 30 | } 31 | 32 | Function End-Log { 33 | [CmdletBinding()] 34 | Param ([Parameter(Mandatory=$true)][string]$streamWriter) 35 | Process{ 36 | $global:streamWriter.WriteLine("`n================================================================================================") 37 | $global:streamWriter.WriteLine("Script ended at $([DateTime]::Now)") 38 | $global:streamWriter.WriteLine("================================================================================================") 39 | 40 | $global:streamWriter.Close() 41 | } 42 | } -------------------------------------------------------------------------------- /ActiveDirectory/ListADObjectsOnSelectedOU/utilities/Utils.ps1: -------------------------------------------------------------------------------- 1 | function OnApplicationLoad { 2 | return $true #return true for success or false for failure 3 | } 4 | function OnApplicationExit { 5 | $script:ExitCode = 0 #Set the exit code for the Packager 6 | } 7 | 8 | function Set-RegistryKey($computername, $parentKey, $nameRegistryKey, $valueRegistryKey) { 9 | try{ 10 | $remoteBaseKeyObject = [microsoft.win32.registrykey]::OpenRemoteBaseKey('LocalMachine',$computername) 11 | $regKey = $remoteBaseKeyObject.OpenSubKey($parentKey,$true) 12 | $regKey.Setvalue("$nameRegistryKey", "$valueRegistryKey", [Microsoft.Win32.RegistryValueKind]::DWORD) 13 | $remoteBaseKeyObject.close() 14 | } 15 | catch { 16 | $_.Exception 17 | } 18 | } 19 | 20 | function Disable-UAC($computername) { 21 | $parentKey = "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Policies\\System" 22 | $nameRegistryKey = "LocalAccountTokenFilterPolicy" 23 | $valueRegistryKey = "1" 24 | 25 | $objReg = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey('LocalMachine', $computername) 26 | $objRegKey= $objReg.OpenSubKey($parentKey) 27 | $test = $objRegkey.GetValue($nameRegistryKey) 28 | if($test -eq $null){ 29 | Set-RegistryKey $computername $parentKey $nameRegistryKey $valueRegistryKey 30 | Write-Host "Registry key setted, you have to reboot the remote computer" -foregroundcolor "magenta" 31 | Stop-Script 32 | } 33 | else { 34 | if($test -ne 1){ 35 | Set-RegistryKey $computername $parentKey $nameRegistryKey $valueRegistryKey 36 | Write-Host "Registry key setted, you have to reboot the remote computer" -foregroundcolor "magenta" 37 | Stop-Script 38 | } 39 | } 40 | } 41 | 42 | function CreateDirectoryIfNeeded ( [string] $directory ) { 43 | if (!(Test-Path -Path $directory -type "Container")) { 44 | New-Item -type directory -Path $directory > $null 45 | } 46 | } 47 | 48 | function Run-WmiRemoteProcess { 49 | Param( 50 | [string]$computername=$env:COMPUTERNAME, 51 | [string]$cmd=$(Throw "You must enter the full path to the command which will create the process."), 52 | [int]$timeout = 0 53 | ) 54 | 55 | Write-Host "Process to create on $computername is $cmd" 56 | [wmiclass]$wmi="\\$computername\root\cimv2:win32_process" 57 | # Exit if the object didn't get created 58 | if (!$wmi) {return} 59 | 60 | try{ 61 | $remote=$wmi.Create($cmd) 62 | } 63 | catch{ 64 | $_.Exception 65 | } 66 | $test =$remote.returnvalue 67 | if ($remote.returnvalue -eq 0) { 68 | Write-Host ("Successfully launched $cmd on $computername with a process id of " + $remote.processid) 69 | } else { 70 | Write-Host ("Failed to launch $cmd on $computername. ReturnValue is " + $remote.ReturnValue) 71 | } 72 | return 73 | } 74 | 75 | function Stop-Script () { 76 | Begin{ 77 | Write-Log -streamWriter $global:streamWriter -infoToLog "--- Script terminating ---" 78 | } 79 | Process{ 80 | "Script terminating..." 81 | Write-Host "================================================================================================" 82 | End-Log -streamWriter $global:streamWriter 83 | Exit 84 | } 85 | } 86 | 87 | Function Stop-ScriptMessageBox () { 88 | # MessageBox who inform of the end of the process 89 | [System.Windows.Forms.MessageBox]::Show( 90 | "Process done. 91 | The log file will be opened when click on 'OK' button. 92 | Please, check the log file for further informations. 93 | " , "End of process" , 0, [Windows.Forms.MessageBoxIcon]::Information) 94 | } 95 | 96 | function Test-InternetConnection { 97 | if(![Activator]::CreateInstance([Type]::GetTypeFromCLSID([Guid]'{DCB00C01-570F-4A9B-8D69-199FDBA5723B}')).IsConnectedToInternet){ 98 | Write-Host "The script need an Internet Connection to run" -f Red 99 | Stop-Script 100 | } 101 | } 102 | 103 | function Test-LocalAdminRights { 104 | $myComputer = Get-WMIObject Win32_ComputerSystem | Select-Object -ExpandProperty name 105 | $myUser = [System.Security.Principal.WindowsIdentity]::GetCurrent() 106 | $amIAdmin = ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()) 107 | $adminFlag = $amIAdmin.IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator") 108 | if($adminFlag -eq $true){ 109 | $adminMessage = " with administrator rights on " 110 | } 111 | else { 112 | $adminMessage = " without administrator rights on " 113 | } 114 | 115 | Write-Host "RWMC runs with user " -nonewline; Write-Host $myUser.Name -f Red -nonewline; Write-Host $adminMessage -nonewline; Write-Host $myComputer -f Red -nonewline; Write-Host " computer" 116 | return $adminFlag 117 | } -------------------------------------------------------------------------------- /ActiveDirectoryCertificateServices/Get-ADCS_Report.ps1: -------------------------------------------------------------------------------- 1 | #requires -version 2 2 | <# 3 | .SYNOPSIS 4 | Collect ADCS information, export results into a HTML report and send it by mail 5 | 6 | .DESCRIPTION 7 | Collect ADCS information locally, and export results into a HTML report (failed and pending requests, plus expired certificates) and send it by mail 8 | 9 | .INPUTS 10 | 11 | 12 | .OUTPUTS 13 | Create HTML report, similar to $ScriptDir\[SCRIPTNAME]_[YYYY_MM_DD]_[HHhMMmSSs].html 14 | 15 | 16 | .NOTES 17 | Version: 1.1 18 | Author: ALBERT Jean-Marc 19 | Creation Date: 01/09/2015 20 | Purpose/Change: 1.0 - 2015.09.01 - ALBERT Jean-Marc - Initial script development 21 | 1.1 - 2016.10.31 - ALBERT Jean-Marc - Replace alias used instead of command name, and " per ', and multiple enhancement 22 | 23 | 24 | 25 | .SOURCES 26 | https://www.shellandco.net/monitor-certificate-expiration/ 27 | http://pspki.codeplex.com/ 28 | http://stackoverflow.com/questions/16542729/send-multiple-outputs-to-the-same-html-file-in-powershell 29 | 30 | 31 | .EXAMPLE 32 | 33 | #> 34 | 35 | 36 | #---------------------------------------------------------[Initialisations]-------------------------------------------------------- 37 | 38 | #Get input strings 39 | [CmdletBinding()] 40 | param( 41 | [string] $computername = "$ENV:COMPUTERNAME", 42 | [string] $reportfile = "$ScriptDir\$([System.IO.Path]::GetFileNameWithoutExtension($MyInvocation.MyCommand.Definition))" + '_' + $SystemDate + '_' + $SystemTime + '.html', 43 | [string] $cert_path = "$env:windir\System32\certsrv\CertEnroll", 44 | [string] $crl_root_filename = 'domain.crl', 45 | [string] $crl_sub_filename = 'domain-sub.crl', 46 | [string] $monthQtyFail = '6', 47 | [string] $monthQtyPend = '1', 48 | [string] $monthQtyExpir = '3' 49 | ) 50 | 51 | 52 | 53 | #----------------------------------------------------------[Declarations]---------------------------------------------------------- 54 | 55 | #Script Version 56 | $sScriptVersion = '1.1' 57 | 58 | #Write script directory path on "ScriptDir" variable 59 | $ScriptDir = Split-Path -Path $MyInvocation.MyCommand.Definition -Parent 60 | $Script 61 | $SystemTime = Get-Date -uformat %Hh%Mm%Ss 62 | $SystemDate = Get-Date -uformat %Y.%m.%d 63 | 64 | 65 | 66 | #-----------------------------------------------------------[Functions]------------------------------------------------------------ 67 | 68 | #Send mail function 69 | Function script:send_mail { 70 | 71 | [CmdletBinding()] 72 | param 73 | ( 74 | [string] 75 | $message, 76 | 77 | [string] 78 | $subject 79 | ) 80 | $emailFrom = 'supervision@domain.local' 81 | $emailCC = 'jean-marc.albert@domain.com' 82 | $emailTo = 'jean-marc.albert@domain.com' 83 | $smtpServer = 'smtp.domain.com' 84 | Send-MailMessage -SmtpServer $smtpServer -To $emailTo -Cc $emailCC -From $emailFrom -Subject $subject -Body $message -BodyAsHtml -Priority High 85 | } 86 | 87 | 88 | 89 | #------------------------------------------------------------[Actions]------------------------------------------------------------- 90 | 91 | #Start stopwatch 92 | $totalTime = New-Object -TypeName System.Diagnostics.Stopwatch 93 | $totalTime.Start() 94 | 95 | #Credits 96 | Write-Host 97 | Write-Host 'ADCS Certificate Expiration Report Tool ' -ForegroundColor 'Yellow' 98 | Write-Host 99 | if(Get-Module -ListAvailable -Name PSPKI | Where-Object { $_.name -eq 'PSPKI' }) 100 | { 101 | #Import PSPKI PowerShell module 102 | if(Get-Module -Name PSPKI | Where-Object { $_.name -eq 'PSPKI' }) 103 | { 104 | Write-Host 'PSPKI PowerShell module already imported…' -ForegroundColor 'Yellow' 105 | } 106 | else 107 | { 108 | Write-Host 'Importing PSPKI PowerShell module…' -ForegroundColor 'Yellow' 109 | Import-Module -Name PSPKI 110 | } 111 | Write-Host 112 | 113 | 114 | #Set variables 115 | Write-Host 'Setting variables…' -ForegroundColor 'Yellow' 116 | Write-Host 117 | $caname = $computername.ToLower() 118 | $domaindns = $ENV:USERDNSDOMAIN.ToLower() 119 | $todaysdate = Get-Date 120 | $findaldate = $todaysdate.AddMonths(2) 121 | $monthQtyFailMinus = "-$monthQtyFail" 122 | $htmlpre = " 123 |

Generated by user: $ENV:USERNAME

124 |

Root CA CRL expiration date : $((Get-CRL $cert_path\$crl_root_filename ).NextUpdate) (MM/DD/YYYY) 125 |
126 | Subordinate CA CRL expiration date : $((Get-CRL $cert_path\$crl_sub_filename).NextUpdate) (MM/DD/YYYY) 127 | " 128 | $htmlpost = " 129 |
130 |
131 |

-------------------------------------------------------------------------------------------------

132 |

---- Certificate informations retrived from $caname.$domaindns ----

133 |

-------------------------------------------------------------------------------------------------

134 | " 135 | $htmllinebreak = '
' 136 | $htmltitle = "Certificate information from $caname.$domaindns" 137 | $htmlpreadcsfailed ="

The following list represent failed requests during last $monthQtyFail months

" 138 | $adcsfailed = Get-CertificationAuthority "$caname.$domaindns" | Get-FailedRequest -Filter "Request.SubmittedWhen -gt $(($todaysdate).AddMonths($monthQtyFailMinus))" | ConvertTo-HTML -Fragment -Property RequestID,Request.RequesterName,Request.SubmittedWhen,Request.CommonName 139 | $htmlpreadcspending ="

The following list represent pending requests

" 140 | $adcspending = Get-CertificationAuthority "$caname.$domaindns" | Get-PendingRequest | ConvertTo-HTML -Fragment -Property RequestID,Request.RequesterName,Request.SubmittedWhen,Request.CommonName 141 | $htmlpreadcsexpired = "

The following certificates expire before $findaldate (MM/DD/YYYY)

" 142 | $adcsexpired = Get-CertificationAuthority "$caname.$domaindns" | Get-IssuedRequest -Filter "NotAfter -ge $($todaysdate)", "NotAfter -le $(($todaysdate).AddMonths($monthQtyExpir))" | where-object {$_.CertificateTemplate -notmatch 'User|EFS|Client-Server-DA-Authentication'} | ConvertTo-HTML -Property RequestID,RequesterName,CommonName,CertificateTemplate,NotBefore,NotAfter -Fragment 143 | 144 | #Generate report 145 | $a = " 146 | 152 | " 153 | 154 | Write-Host 'Generating report…' -ForegroundColor 'Yellow' 155 | Write-Host 156 | 157 | ConvertTo-Html -Body "$htmlpre $htmlpreadcsfailed $adcsfailed $htmlpreadcspending $adcspending $htmllinebreak $htmlpreadcsexpired $adcsexpired $htmlpost" -head $a | Out-File -FilePath $reportfile 158 | $message = gc $reportfile 159 | 160 | #Send report by email 161 | send_mail $message "Certificate expiration report $todaysdate (MM/DD/YYYY) ($caname)" 162 | 163 | #Open report 164 | Write-Host 'Opening report…' -ForegroundColor 'Yellow' 165 | Write-Host 166 | #Invoke-Item $reportfile 167 | 168 | #Warning if PSPKI is not installed 169 | } 170 | else 171 | { 172 | Write-Host 'PSPKI is not installed. Please install it from http://pspki.codeplex.com/ ' -ForegroundColor 'Yellow' 173 | Write-Host 174 | } 175 | 176 | #Stop stopwatch 177 | $totalTime.Stop() 178 | $ts = $totalTime.Elapsed 179 | $totalTime = [system.String]::Format('{0:00}:{1:00}:{2:00}',$ts.Hours, $ts.Minutes, $ts.Seconds) 180 | Write-Host "Process total time: $totalTime" -ForegroundColor Yellow 181 | Write-Host 182 | 183 | Invoke-Item $reportfile 184 | -------------------------------------------------------------------------------- /ActiveDirectoryCertificateServices/PS PKI v3.1.0.exe: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wikijm/PowerShell-AdminScripts/0f52701924d72a72b74f718cf7a4ce45ff27dbca/ActiveDirectoryCertificateServices/PS PKI v3.1.0.exe -------------------------------------------------------------------------------- /Bitlocker/Backup-BitlockerRecoveryKeyToAD.ps1: -------------------------------------------------------------------------------- 1 | $BitLockerDrives = Get-BitLockerVolume {$_.KeyProtector {$_.KeyProtectorType -eq 'RecoveryPassword'}} 2 | Foreach ($BitLockerDrive in $BitLockerDrives) { 3 | $BitlockerDriveKey = $BitLockerDrive select -exp KeyProtector {$_.KeyProtectorType -eq 'RecoveryPassword'} 4 | Backup-BitLockerKeyProtector $BitlockerDrive.MountPoint $BitlockerDriveKey.KeyProtectorId 5 | Write-Host -ForegroundColor Green Backing up drive $BitlockerDrive ($($BitLockerDrive.VolumeType)), key $($BitlockerDriveKey.KeyProtectorId), password $($BitlockerDriveKey.RecoveryPassword) 6 | } 7 | -------------------------------------------------------------------------------- /DHCP/Backup-DHCPLeases.ps1: -------------------------------------------------------------------------------- 1 | #requires -version 2 -RunAsAdministrator 2 | <# 3 | .SYNOPSIS 4 | List all DHCP lease Objects coming from a targeted DHCP server, and export results into a CSV 5 | 6 | .DESCRIPTION 7 | List all DHCP lease Objects coming from a targeted DHCP server, and export results into a CSV 8 | 9 | .INPUTS 10 | DHCP server name as an argument 11 | 12 | .OUTPUTS 13 | Create transcript log file similar to $ScriptDir\[SCRIPTNAME]_[YYYY_MM_DD]_[HHhMMmSSs].log 14 | Create a list of DHCP lease Objects, similar to $ScriptDir\[SCRIPTNAME]_DHCPServer_Reservations_[YYYY_MM_DD]_[HHhMMmSSs].csv 15 | 16 | 17 | .NOTES 18 | Version: 1.0 19 | Author: ALBERT Jean-Marc 20 | Creation Date: 13/02/2019 21 | Purpose/Change: 1.0 - 2019.02.13 - ALBERT Jean-Marc - Initial script development 22 | 23 | 24 | .SOURCES 25 | https://blogs.technet.microsoft.com/leesteve/2017/06/09/ps-without-bs-extracting-dhcp-reservations-to-a-csv/ 26 | 27 | .EXAMPLE 28 | 29 | #> 30 | 31 | #---------------------------------------------------------[Initialisations]-------------------------------------------------------- 32 | 33 | #Set Error Action to Silently Continue 34 | $ErrorActionPreference = "SilentlyContinue" 35 | 36 | # Powershell DHCPServer module importation 37 | Import-Module DHCPServer 38 | 39 | #----------------------------------------------------------[Declarations]---------------------------------------------------------- 40 | 41 | #Script Version 42 | $sScriptVersion = "1.0" 43 | 44 | #Write script directory path on "ScriptDir" variable 45 | $ScriptDir = Split-Path -Path $MyInvocation.MyCommand.Definition -Parent 46 | 47 | #Log file creation, similar to $ScriptDir\[SCRIPTNAME]_[YYYY_MM_DD].log 48 | $SystemTime = Get-Date -uformat %Hh%Mm%Ss 49 | $SystemDate = Get-Date -uformat %Y_%m_%d 50 | $ScriptLogFile = "$ScriptDir\$([System.IO.Path]::GetFileNameWithoutExtension($MyInvocation.MyCommand.Definition))" + "_" + $DHCPServer + "_" + $SystemDate + "_" + $SystemTime + ".log" 51 | 52 | #Define CSV file export of DHCP leases objects 53 | $CSVExport = "$ScriptDir\$([System.IO.Path]::GetFileNameWithoutExtension($MyInvocation.MyCommand.Definition))" + "_" + $DHCPServer + "_" + "Reservations" + "_" + $SystemDate + "_" + $SystemTime + ".csv" 54 | 55 | 56 | #-----------------------------------------------------------[Functions]------------------------------------------------------------ 57 | 58 | Function Stop-TranscriptOnLog { 59 | Stop-Transcript 60 | # We put in the transcript the line breaks necessary for Notepad 61 | [string]::Join("`r`n",(Get-Content $ScriptLogFile)) | Out-File $ScriptLogFile 62 | } 63 | 64 | #------------------------------------------------------------[Actions]------------------------------------------------------------- 65 | 66 | # Start of log completion 67 | Start-Transcript $ScriptLogFile | Out-Null 68 | 69 | 70 | # Catch DHCP Server name 71 | $DHCPServer = $env:COMPUTERNAME 72 | <# 73 | param ([string]$DHCPServer = $args[0]) 74 | 75 | If ($DHCPServer -eq $null) { 76 | $DHCPServer = $env:COMPUTERNAME 77 | }#> 78 | 79 | # Get DHCP scope list on targeted server(s) 80 | $DHCPServerScope = Get-DHCPServerV4Scope -ComputerName $DHCPServer 81 | 82 | # For each scope, list and export every leases to a .CSV file 83 | $DHCPServerScope | ForEach { 84 | Get-DHCPServerv4Lease -ScopeID $_.ScopeID | where {$_.AddressState -like '*Reservation'} 85 | } | Select-Object ScopeId,IPAddress,HostName,ClientID,AddressState | Export-Csv $CSVExport -Delimiter ";" -NoTypeInformation 86 | 87 | # MessageBox who inform of the end of the process 88 | Write-Information "Process done" 89 | 90 | # Stop the log transcript 91 | Stop-TranscriptOnLog 92 | 93 | # Open the log file | Debug purpose only, you may leave it as a comment 94 | #Invoke-Item $ScriptLogFile 95 | -------------------------------------------------------------------------------- /Domoticz/functions.ps1: -------------------------------------------------------------------------------- 1 | $DomoticzApiProtocol = 'http' 2 | $DomoticzApiIP = '192.168.0.XX' 3 | $DomoticzApiPort = '8080' 4 | $DomoticzDeviceID = 'X' 5 | 6 | function Get-LightSwitchStatus { 7 | Param([Parameter(Mandatory=$true)][string]$DomoticzDeviceID) 8 | $DomoticzRequestURL = $DomoticzApiProtocol + '://' + $DomoticzApiIP + ':' + $DomoticzApiPort + '/json.htm?type=devices&rid=' + $DomoticzDeviceID 9 | $DomoticzRequestResult = Invoke-WebRequest $DomoticzRequestURL | ConvertFrom-Json 10 | 11 | Write-Host $DomoticzRequestResult.result.HardwareName 12 | Write-Host $DomoticzRequestResult.result.Type 13 | Write-Host $DomoticzRequestResult.result.Status 14 | Write-Host $DomoticzRequestResult.result.LastUpdate 15 | } 16 | 17 | Get-LightSwitchStatus X 18 | -------------------------------------------------------------------------------- /Exchange/EnableOnlineArchive.ps1: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wikijm/PowerShell-AdminScripts/0f52701924d72a72b74f718cf7a4ce45ff27dbca/Exchange/EnableOnlineArchive.ps1 -------------------------------------------------------------------------------- /FSRM/New-FSRMQuota.ps1: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wikijm/PowerShell-AdminScripts/0f52701924d72a72b74f718cf7a4ce45ff27dbca/FSRM/New-FSRMQuota.ps1 -------------------------------------------------------------------------------- /Hyper-V/Create-HyperV_VM.ps1: -------------------------------------------------------------------------------- 1 | #requires -version 2 2 | <# 3 | .SYNOPSIS 4 | Create Hyper-V VM with an input .CSV file 5 | 6 | .DESCRIPTION 7 | Create Hyper-V Virtual Machines with an input .CSV file (contains Name;DiskCapacityInGB;Generation;CPUNb;StartupRAMinMB;MinimumRAMinMB;SwitchName) 8 | 9 | .INPUTS 10 | .CSV file selected by user during the script 11 | 12 | .OUTPUTS 13 | Create transcript log file similar to $ScriptDir\[SCRIPTNAME]_[YYYY_MM_DD]_[HHhMMmSSs].log 14 | 15 | .NOTES 16 | Version: 1.0 17 | Author: ALBERT Jean-Marc 18 | Creation Date: 26/08/2015 19 | Purpose/Change: 2015.08.24 - ALBERT Jean-Marc - Initial script development 20 | 2015.08.26 - ALBERT Jean-Marc - Replace .CSV fixed name per file dialog selection 21 | 22 | 23 | .EXAMPLE 24 | 25 | #> 26 | 27 | #---------------------------------------------------------[Initialisations]-------------------------------------------------------- 28 | 29 | #Set Error Action to Silently Continue 30 | $ErrorActionPreference = "SilentlyContinue" 31 | 32 | #----------------------------------------------------------[Declarations]---------------------------------------------------------- 33 | 34 | #Script Version 35 | $sScriptVersion = "2.0" 36 | 37 | #Write script directory path on "ScriptDir" variable 38 | $ScriptDir = Split-Path -Path $MyInvocation.MyCommand.Definition -Parent 39 | 40 | # Log file creation, similar to $ScriptDir\[SCRIPTNAME]_[YYYY_MM_DD].log 41 | $ActualDate = Get-Date -uformat %Y_%m_%d 42 | $ScriptLogFile = "$ScriptDir\$([System.IO.Path]::GetFileNameWithoutExtension($MyInvocation.MyCommand.Definition))" + "_" + $ActualDate + ".log" 43 | 44 | # Declare Environment and Hyper-V parameters 45 | $VMLoc = "E:\Hyper-V\" 46 | $NetworkSwitch1 = "Externe" 47 | $NetworkSwitch1Type = "Public" 48 | $NetworkSwitch2 = "LAN 192.168.1.0" 49 | $NetworkSwitch2Type = "Private" 50 | 51 | #-----------------------------------------------------------[Functions]------------------------------------------------------------ 52 | function Stop-TranscriptOnLog 53 | { 54 | Stop-Transcript 55 | # Add EOL required for Notepad.exe application usage 56 | [string]::Join("`r`n", (Get-Content $ScriptLogFile)) | Out-File $ScriptLogFile 57 | } 58 | 59 | function Select-FileDialog 60 | { 61 | param ([string]$Title, [string]$Filter = "All files *.*|*.*") 62 | [System.Reflection.Assembly]::LoadWithPartialName('System.Windows.Forms') | Out-Null 63 | $fileDialogBox = New-Object Windows.Forms.OpenFileDialog 64 | $fileDialogBox.ShowHelp = $false 65 | $fileDialogBox.initialDirectory = $ScriptDir 66 | $fileDialogBox.filter = $Filter 67 | $fileDialogBox.Title = $Title 68 | $Show = $fileDialogBox.ShowDialog() 69 | 70 | If ($Show -eq "OK") 71 | { 72 | Return $fileDialogBox.FileName 73 | } 74 | Else 75 | { 76 | Write-Error "Canceled operation" 77 | [System.Windows.Forms.MessageBox]::Show("Script is not able to continue. Operation stopped.", "Operation canceled", 0, [Windows.Forms.MessageBoxIcon]::Error) 78 | Stop-TranscriptOnLog 79 | Exit 80 | } 81 | 82 | } 83 | 84 | #------------------------------------------------------------[Actions]------------------------------------------------------------- 85 | # Start of log completion 86 | Start-Transcript $ScriptLogFile | Out-Null 87 | 88 | # Import CSV file 89 | [System.Windows.Forms.MessageBox]::Show( 90 | " 91 | Select on this window the CSV file who contains VM parameters. 92 | Its content must be similar to: 93 | 94 | Name;DiskCapacityInGB;Generation;CPUNb;StartupRAMinMB;MinimumRAMinMB;SwitchName (Required line) 95 | VM01;200;2;2;1024;512;LAN 192.168.1.0 96 | VM02;200;2;2;1024;512;LAN 192.168.1.0 97 | VM03;200;2;2;1024;512;LAN 192.168.1.0 98 | ", "VM parameters list", 0, [Windows.Forms.MessageBoxIcon]::Question) 99 | 100 | $CSVInputFile = Select-FileDialog -Title "Select CSV file" -Filter "CSV File (*.csv) |*.csv" 101 | 102 | # Import VM parameters list 103 | $csvValues = Import-Csv $CSVInputFile -Delimiter ';' 104 | 105 | 106 | # Loop to handle Virtual Machine generation & launch 107 | foreach ($line in $csvValues) 108 | { 109 | $VMName = $VMList.Name 110 | $DiskCapacityinGB = $VMList.DiskCapacityInGB 111 | [int64]$DiskCapacity = 1GB*$DiskCapacityinGB 112 | $Generation = $VMList.Generation 113 | $CPU = $VMList.CPUNb 114 | $MemoryStartupBytes = $VMList.StartupRAMinMB 115 | $MemoryMinimumBytes = $VMList.MinimumRAMinMB 116 | [int64]$startupmem = 1MB*$MemoryStartupBytes 117 | [int64]$minimummem = 1MB*$MemoryMinimumBytes 118 | $SwitchName = $VMList.SwitchName 119 | 120 | # Create Virtual Machines & VHDX 121 | New-VHD -Path "$VMLoc\$VMName\Virtual Hard Disks\$VMName.vhdx" -SizeBytes $DiskCapacity -Dynamic 122 | New-VM -Path $VMLoc -Name $VMName -Generation $Generation -MemoryStartupBytes $startupmem -VHDPath "$VMLoc\$VMName\Virtual Hard Disks\$VMName.vhdx" -SwitchName $SwitchName 123 | Set-VMProcessor –VMName $VMName –count $CPU 124 | Set-VMMemory -VMName $VMName -DynamicMemoryEnabled $true -StartupBytes $startupmem -MinimumBytes $minimummem 125 | } 126 | 127 | $OUTPUT = [System.Windows.Forms.MessageBox]::Show("VM were create well. Would you like to launch them?", "Ended VM creation", 4, [Windows.Forms.MessageBoxIcon]::Question) 128 | if ($OUTPUT -eq "YES") 129 | { 130 | # Import CSV file 131 | $VMList = Import-Csv $CSVVMConfigFile -delimiter ';' 132 | # Start all created VM 133 | foreach ($VMList in $VMList) 134 | { 135 | $VMName = $VMList.Name 136 | Start-VM $VMName 137 | } 138 | } 139 | else 140 | { 141 | [System.Windows.Forms.MessageBox]::Show("Created VM were not started.", "Ended VM creation", 0, [Windows.Forms.MessageBoxIcon]::Information) 142 | } 143 | 144 | # Get VM 145 | Get-VM | Sort-Object Name | Select Name, State, CPUUsage, MemoryAssigned | Export-CliXML $ScriptDir\Get-VM.xml 146 | Import-CliXML $ScriptDir\Get-VM.xml | Out-GridView -Title Get-VM -PassThru 147 | 148 | # Stop the log transcript 149 | Stop-TranscriptOnLog -------------------------------------------------------------------------------- /Hyper-V/Delete-HyperV_VM.ps1: -------------------------------------------------------------------------------- 1 | #requires -version 2 2 | <# 3 | .SYNOPSIS 4 | Delete Hyper-V VM with an input .CSV file 5 | 6 | .DESCRIPTION 7 | Delete Hyper-V Virtual Machines listed on an input .CSV file (contains Name) 8 | 9 | .INPUTS 10 | .CSV file selected by user during the script 11 | 12 | .OUTPUTS 13 | Create transcript log file similar to $ScriptDir\[SCRIPTNAME]_[YYYY_MM_DD]_[HHhMMmSSs].log 14 | 15 | .NOTES 16 | Version: 1.0 17 | Author: ALBERT Jean-Marc 18 | Creation Date: 26/08/2015 19 | Purpose/Change: 2015.08.26 - ALBERT Jean-Marc - Initial script development 20 | 21 | 22 | .EXAMPLE 23 | 24 | #> 25 | 26 | #---------------------------------------------------------[Initialisations]-------------------------------------------------------- 27 | 28 | #Set Error Action to Silently Continue 29 | $ErrorActionPreference = "SilentlyContinue" 30 | 31 | #----------------------------------------------------------[Declarations]---------------------------------------------------------- 32 | 33 | #Script Version 34 | $sScriptVersion = "1.0" 35 | 36 | #Write script directory path on "ScriptDir" variable 37 | $ScriptDir = Split-Path -Path $MyInvocation.MyCommand.Definition -Parent 38 | 39 | # Log file creation, similar to $ScriptDir\[SCRIPTNAME]_[YYYY_MM_DD].log 40 | $ActualDate = Get-Date -uformat %Y_%m_%d 41 | $ScriptLogFile = "$ScriptDir\$([System.IO.Path]::GetFileNameWithoutExtension($MyInvocation.MyCommand.Definition))" + "_" + $ActualDate + ".log" 42 | 43 | # Declare Environment and Hyper-V parameters 44 | $VMLoc = "E:\Hyper-V\" 45 | 46 | #-----------------------------------------------------------[Functions]------------------------------------------------------------ 47 | function Stop-TranscriptOnLog 48 | { 49 | Stop-Transcript 50 | # Add EOL required for Notepad.exe application usage 51 | [string]::Join("`r`n", (Get-Content $ScriptLogFile)) | Out-File $ScriptLogFile 52 | } 53 | 54 | function Select-FileDialog 55 | { 56 | param ([string]$Title, [string]$Filter = "All files *.*|*.*") 57 | [System.Reflection.Assembly]::LoadWithPartialName('System.Windows.Forms') | Out-Null 58 | $fileDialogBox = New-Object Windows.Forms.OpenFileDialog 59 | $fileDialogBox.ShowHelp = $false 60 | $fileDialogBox.initialDirectory = $ScriptDir 61 | $fileDialogBox.filter = $Filter 62 | $fileDialogBox.Title = $Title 63 | $Show = $fileDialogBox.ShowDialog() 64 | 65 | If ($Show -eq "OK") 66 | { 67 | Return $fileDialogBox.FileName 68 | } 69 | Else 70 | { 71 | Write-Error "Canceled operation" 72 | [System.Windows.Forms.MessageBox]::Show("Script is not able to continue. Operation stopped.", "Operation canceled", 0, [Windows.Forms.MessageBoxIcon]::Error) 73 | Stop-TranscriptOnLog 74 | Exit 75 | } 76 | 77 | } 78 | 79 | #------------------------------------------------------------[Actions]------------------------------------------------------------- 80 | # Start of log completion 81 | Start-Transcript $ScriptLogFile | Out-Null 82 | 83 | # Import CSV file 84 | [System.Windows.Forms.MessageBox]::Show( 85 | " 86 | Select on this window the CSV file who contains VM names. 87 | Its content must be similar to: 88 | 89 | Name (Required line) 90 | VM01 91 | VM02 92 | VM03 93 | ", "VM list", 0, [Windows.Forms.MessageBoxIcon]::Question) 94 | 95 | $CSVInputFile = Select-FileDialog -Title "Select CSV file" -Filter "CSV File (*.csv) |*.csv" 96 | 97 | # Import VM parameters list 98 | $csvValues = Import-Csv $CSVInputFile -Delimiter ';' 99 | 100 | # Delete Virtual Machines 101 | foreach ($VMList in $VMList) 102 | { 103 | $VMName = $VMList.Name 104 | # Stop, Delete VM & VHDX 105 | Get-VM $VMName | %{ Stop-VM -VM $_ -Force; Remove-VM -VM $_ -Force; Remove-Item -Path $_.Path -Recurse -Force } 106 | } 107 | 108 | # Get VM 109 | Get-VM | Sort-Object Name | Select Name, State, CPUUsage, MemoryAssigned | Export-CliXML $ScriptDir\Get-VM.xml 110 | Import-CliXML $ScriptDir\Get-VM.xml | Out-GridView -Title Get-VM -PassThru 111 | 112 | # Stop the log transcript 113 | Stop-TranscriptOnLog -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2022 wikijm 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /LocalUsersAndGroups/Create-LocalAdminAccount.ps1: -------------------------------------------------------------------------------- 1 | #requires -version 2 2 | <# 3 | .SYNOPSIS 4 | Create a local admin user, with local admin group adaptation 5 | 6 | .DESCRIPTION 7 | Create a local admin user, with local admin group adaptation 8 | 9 | .INPUTS 10 | 11 | 12 | .OUTPUTS 13 | 14 | 15 | 16 | .NOTES 17 | Version: 0.1 18 | Author: ALBERT Jean-Marc 19 | Creation Date: 08/04/2016 (DD/MM/YYYY) 20 | Purpose/Change: 1.0 - 2016.04.08 - ALBERT Jean-Marc - Initial script development 21 | 22 | 23 | .SOURCES 24 | 25 | 26 | 27 | .EXAMPLE 28 | 29 | 30 | #> 31 | 32 | #---------------------------------------------------------[Initialisations]-------------------------------------------------------- 33 | Set-StrictMode -version Latest 34 | 35 | #Set Error Action to Silently Continue 36 | $ErrorActionPreference = "SilentlyContinue" 37 | 38 | #----------------------------------------------------------[Declarations]---------------------------------------------------------- 39 | 40 | $scriptVersion = "0.1" 41 | 42 | $userName = "test" 43 | $password = "P@ssw0rd!!" 44 | $description = 'TYPE_A_DESCRIPTION' 45 | 46 | $computer = $Env:COMPUTERNAME 47 | 48 | #-----------------------------------------------------------[Functions]------------------------------------------------------------ 49 | 50 | function LocalGroupExist ($groupName) { 51 | return [ADSI]::Exists("WinNT://$Env:COMPUTERNAME/$groupName,group") 52 | } 53 | 54 | function LocalUserExist ($userName) { 55 | # Local user account creation: 56 | $colUsers = ($Computer.psbase.children | Where-Object {$_.psBase.schemaClassName -eq "User"} | Select-Object -expand Name) 57 | $userFound = $colUsers -contains $userName 58 | return $userFound 59 | } 60 | 61 | function CreateLocalUser ($userName,$password) { 62 | $userExist = LocalUserExist($userName) 63 | 64 | if($userExist -eq $false) 65 | { 66 | $User = $Computer.Create("User", $userName) 67 | $User.SetPassword($password) 68 | $User.SetInfo() 69 | $User.FullName = $userName 70 | $User.SetInfo() 71 | $user.description = $description 72 | $user.SetInfo() 73 | $User.UserFlags = 64 + 65536 # ADS_UF_PASSWD_CANT_CHANGE + ADS_UF_DONT_EXPIRE_PASSWD 74 | $User.SetInfo() 75 | } 76 | else { 77 | "User : $userName already exist." 78 | } 79 | } 80 | 81 | function AddUserToGroup ($groupName, $userName) { 82 | $group = [ADSI]"WinNT://$Env:COMPUTERNAME/$groupName" 83 | $user = [ADSI]"WinNT://$Env:COMPUTERNAME/$userName" 84 | $memberExist = CheckGroupMember $groupName $userName 85 | if($memberExist -eq $false) 86 | { 87 | $group = [ADSI]"WinNT://$Env:COMPUTERNAME/$groupName" 88 | $user = [ADSI]"WinNT://$Env:COMPUTERNAME/$userName" 89 | $group.Add($user.Path) 90 | } 91 | } 92 | 93 | #----------------------------------------------------------[Execution]---------------------------------------------------------- 94 | 95 | #Get local admin group 96 | $LocalAdminGroup = (get-wmiobject win32_group | Where-Object {$_.Name -Like "Administr*"}).Name 97 | 98 | #Create $userName local account 99 | CreateLocalUser $userName $password 100 | 101 | #Check $userName local account creation 102 | $IsAccountExist = LocalUserExist($userName) 103 | if($IsAccountExist -eq $true) 104 | { 105 | "$userName now exist" 106 | } 107 | else 108 | { 109 | "/!\ Error: $userName don't exist /!\" 110 | } 111 | 112 | 113 | #Add $userName local account to local admin group 114 | AddUserToGroup $LocalAdminGroup -------------------------------------------------------------------------------- /LocalUsersAndGroups/Replace-LocalAdminPassword.ps1: -------------------------------------------------------------------------------- 1 | #requires -version 2 2 | <# 3 | .SYNOPSIS 4 | Replace password of local admin account 5 | 6 | .DESCRIPTION 7 | Get local account (user object) with $childObjectSID ends with "-500" (Admin account) then replace password 8 | 9 | .INPUTS 10 | 11 | 12 | .OUTPUTS 13 | 14 | 15 | 16 | .NOTES 17 | Version: 0.1 18 | Author: ALBERT Jean-Marc 19 | Creation Date: 29/04/2016 (DD/MM/YYYY) 20 | Purpose/Change: 1.0 - 2016.04.29 - ALBERT Jean-Marc - Initial script development 21 | 22 | 23 | .SOURCES 24 | 25 | 26 | 27 | .EXAMPLE 28 | 29 | 30 | #> 31 | 32 | #---------------------------------------------------------[Initialisations]-------------------------------------------------------- 33 | Set-StrictMode -version Latest 34 | 35 | #Set Error Action to Silently Continue 36 | $ErrorActionPreference = "SilentlyContinue" 37 | 38 | #----------------------------------------------------------[Declarations]---------------------------------------------------------- 39 | 40 | $scriptName = [System.IO.Path]::GetFileName($scriptFile) 41 | $scriptVersion = "0.1" 42 | 43 | $ComputerName = $env:COMPUTERNAME 44 | $Computer = [ADSI] "WinNT://$ComputerName,Computer" 45 | $DecodedPassword = "Str0n6P@ssw0rd!!" 46 | 47 | #-----------------------------------------------------------[Execution]------------------------------------------------------------ 48 | Write-Host "=======================================================" 49 | Write-Host {}{}{}{}{}{}{}{}{}{}{}{}"$scriptName" 50 | Write-Host "=======================================================" 51 | 52 | 53 | #Get local admin account name 54 | Write-Progress -Activity "Get local admin account name" -status "Running..." -id 1 55 | foreach ( $childObject in $Computer.Children ) { 56 | # Skip objects that are not users. 57 | if ( $childObject.Class -ne "User" ) { 58 | continue 59 | } 60 | $type = "System.Security.Principal.SecurityIdentifier" 61 | # BEGIN CALLOUT A 62 | $childObjectSID = new-object $type($childObject.objectSid[0],0) 63 | # END CALLOUT A 64 | if ( $childObjectSID.Value.EndsWith("-500") ) { 65 | $LocalAdminAccount = $($childObject.Name[0]) 66 | break 67 | } 68 | } 69 | 70 | #Show local Admin account 71 | Write-Progress -Activity "Show local Admin account" -status "Running..." -id 1 72 | Write-Host -ForegroundColor Green "Local user account: $LocalAdminAccount" 73 | 74 | #Define new password to local Admin account 75 | Write-Progress -Activity "Define new password to local Admin account" -status "Running..." -id 1 76 | $Computer 77 | $User = [adsi]"WinNT://$ComputerName/$LocalAdminAccount,user" 78 | $User.SetPassword($DecodedPassword) 79 | $User.SetInfo() 80 | Write-Host -ForegroundColor Green "Password changed successfully" -------------------------------------------------------------------------------- /Miscellaneous/Create-Shortcut.ps1: -------------------------------------------------------------------------------- 1 | Function CreateShortcut 2 | { 3 | [CmdletBinding()] 4 | param ( 5 | [parameter(Mandatory=$true)] 6 | [ValidateScript( {[IO.File]::Exists($_)} )] 7 | [System.IO.FileInfo] $Target, 8 | 9 | [ValidateScript( {[IO.Directory]::Exists($_)} )] 10 | [System.IO.DirectoryInfo] $OutputDirectory, 11 | 12 | [string] $Name, 13 | [string] $Description, 14 | 15 | [string] $Arguments, 16 | [System.IO.DirectoryInfo] $WorkingDirectory, 17 | 18 | [string] $HotKey, 19 | [int] $WindowStyle = 1, 20 | [string] $IconLocation, 21 | [switch] $Elevated 22 | ) 23 | 24 | try { 25 | #region Create Shortcut 26 | if ($Name) { 27 | [System.IO.FileInfo] $LinkFileName = [System.IO.Path]::ChangeExtension($Name, "lnk") 28 | } else { 29 | [System.IO.FileInfo] $LinkFileName = [System.IO.Path]::ChangeExtension($Target.Name, "lnk") 30 | } 31 | 32 | if ($OutputDirectory) { 33 | [System.IO.FileInfo] $LinkFile = [IO.Path]::Combine($OutputDirectory, $LinkFileName) 34 | } else { 35 | [System.IO.FileInfo] $LinkFile = [IO.Path]::Combine($Target.Directory, $LinkFileName) 36 | } 37 | 38 | 39 | $wshshell = New-Object -ComObject WScript.Shell 40 | $shortCut = $wshShell.CreateShortCut($LinkFile) 41 | $shortCut.TargetPath = $Target 42 | $shortCut.WindowStyle = $WindowStyle 43 | $shortCut.Description = $Description 44 | $shortCut.WorkingDirectory = $WorkingDirectory 45 | $shortCut.HotKey = $HotKey 46 | $shortCut.Arguments = $Arguments 47 | if ($IconLocation) { 48 | $shortCut.IconLocation = $IconLocation 49 | } 50 | $shortCut.Save() 51 | #endregion 52 | 53 | #region Elevation Flag 54 | if ($Elevated) { 55 | $tempFileName = [IO.Path]::GetRandomFileName() 56 | $tempFile = [IO.FileInfo][IO.Path]::Combine($LinkFile.Directory, $tempFileName) 57 | 58 | $writer = new-object System.IO.FileStream $tempFile, ([System.IO.FileMode]::Create) 59 | $reader = $LinkFile.OpenRead() 60 | 61 | while ($reader.Position -lt $reader.Length) 62 | { 63 | $byte = $reader.ReadByte() 64 | if ($reader.Position -eq 22) { 65 | $byte = 34 66 | } 67 | $writer.WriteByte($byte) 68 | } 69 | 70 | $reader.Close() 71 | $writer.Close() 72 | 73 | $LinkFile.Delete() 74 | 75 | Rename-Item -Path $tempFile -NewName $LinkFile.Name 76 | } 77 | #endregion 78 | } catch { 79 | Write-Error "Failed to create shortcut. The error was '$_'." 80 | return $null 81 | } 82 | return $LinkFile 83 | } 84 | 85 | CreateShortcut -name "Notepad++ Admin" -Target "${env:ProgramFiles(x86)}\Notepad++\notepad++.exe" -OutputDirectory "C:\Users\Public\Desktop" -Elevated True 86 | -------------------------------------------------------------------------------- /Miscellaneous/DecodeFileFromBase64/DecodeFileFromBase64.ps1: -------------------------------------------------------------------------------- 1 | #requires -version 2 2 | <# 3 | .SYNOPSIS 4 | Decode selected file from Base64, and export result to original (decoded) file 5 | 6 | .DESCRIPTION 7 | Decode selected file (with dialog) from Base64, and export result to original (decoded) file (without "-encoded.txt" suffix) 8 | 9 | .INPUTS 10 | File selected by user with "Select file" dialog 11 | 12 | .OUTPUTS 13 | File selected by user with "Select file" dialog without "-encoded.txt" suffix 14 | 15 | .NOTES 16 | Version: 0.1 17 | Author: ALBERT Jean-Marc 18 | Creation Date: 17/03/2016 (DD/MM/YYYY) 19 | Purpose/Change: 1.0 - 2016.03.17 - ALBERT Jean-Marc - Initial script development 20 | 21 | 22 | .SOURCES 23 | 24 | 25 | 26 | .EXAMPLE 27 | 28 | 29 | #> 30 | 31 | #---------------------------------------------------------[Initialisations]-------------------------------------------------------- 32 | Set-StrictMode -version Latest 33 | 34 | #Set Error Action to Silently Continue 35 | $ErrorActionPreference = "SilentlyContinue" 36 | $scriptFile = $MyInvocation.MyCommand.Definition 37 | 38 | 39 | #----------------------------------------------------------[Declarations]---------------------------------------------------------- 40 | 41 | $scriptName = [System.IO.Path]::GetFileName($scriptFile) 42 | $scriptVersion = "0.1" 43 | 44 | 45 | #-----------------------------------------------------------[Functions]------------------------------------------------------------ 46 | 47 | function Select-FileDialog 48 | { 49 | param([string]$Title,[string]$Filter="All files *.*|*.*") 50 | [System.Reflection.Assembly]::LoadWithPartialName( 'System.Windows.Forms' ) | Out-Null 51 | $fileDialogBox = New-Object Windows.Forms.OpenFileDialog 52 | $fileDialogBox.ShowHelp = $false 53 | $fileDialogBox.initialDirectory = $ScriptDir 54 | $fileDialogBox.filter = $Filter 55 | $fileDialogBox.Title = $Title 56 | $Show = $fileDialogBox.ShowDialog( ) 57 | 58 | If ($Show -eq "OK") 59 | { 60 | Return $fileDialogBox.FileName 61 | } 62 | Else 63 | { 64 | Write-Error "Canceled operation" 65 | [System.Windows.Forms.MessageBox]::Show("Script is not able to continue. Operation stopped." , "Operation canceled" , 0, [Windows.Forms.MessageBoxIcon]::Error) 66 | Stop-TranscriptOnLog 67 | Exit 68 | } 69 | 70 | } 71 | 72 | 73 | #----------------------------------------------------------[Execution]---------------------------------------------------------- 74 | 75 | cls 76 | 77 | # Import file to decode 78 | [System.Windows.Forms.MessageBox]::Show( 79 | " 80 | Select on this window the file that you want to decode from Base64 81 | ", "Select file", 0, [Windows.Forms.MessageBoxIcon]::Question) 82 | 83 | $FileToDecode = Select-FileDialog -Title "Select file" 84 | $Content = [System.Convert]::FromBase64String($Base64) 85 | $DecodedFile = $FileToDecode.Replace("-encoded.txt","") 86 | Set-Content -Path $DecodedFile -Value $Content -Encoding Byte 87 | 88 | # Inform user to the end of the process, and let the possibility to open the output 89 | $OUTPUT = [System.Windows.Forms.MessageBox]::Show("Decoded version was create well. Would you like to open it?", "Ended Base64 decoding", 4, [Windows.Forms.MessageBoxIcon]::Question) 90 | if ($OUTPUT -eq "YES") 91 | { 92 | notepad $DecodedFile 93 | } 94 | 95 | else 96 | { 97 | [System.Windows.Forms.MessageBox]::Show("End of the script.", "Ended Base64 decoding process", 0, [Windows.Forms.MessageBoxIcon]::Information) 98 | } -------------------------------------------------------------------------------- /Miscellaneous/EncodeFileToBase64/EncodeFileToBase64.ps1: -------------------------------------------------------------------------------- 1 | #requires -version 2 2 | <# 3 | .SYNOPSIS 4 | Encode selected file to Base64, and export result to "SELECTEDFILE-encoded.txt" 5 | 6 | .DESCRIPTION 7 | Encode selected file (with dialog) to Base64, and export the result to "SELECTEDFILE-encoded.txt" 8 | 9 | .INPUTS 10 | File selected by user with "Select file" dialog 11 | 12 | .OUTPUTS 13 | File selected by user with "Select file" dialog + "-encoded.txt" suffix 14 | 15 | .NOTES 16 | Version: 0.1 17 | Author: ALBERT Jean-Marc 18 | Creation Date: 17/03/2016 (DD/MM/YYYY) 19 | Purpose/Change: 1.0 - 2016.03.17 - ALBERT Jean-Marc - Initial script development 20 | 21 | 22 | .SOURCES 23 | 24 | 25 | 26 | .EXAMPLE 27 | 28 | 29 | #> 30 | 31 | #---------------------------------------------------------[Initialisations]-------------------------------------------------------- 32 | Set-StrictMode -version Latest 33 | 34 | #Set Error Action to Silently Continue 35 | $ErrorActionPreference = "SilentlyContinue" 36 | $scriptFile = $MyInvocation.MyCommand.Definition 37 | 38 | 39 | #----------------------------------------------------------[Declarations]---------------------------------------------------------- 40 | 41 | $scriptName = [System.IO.Path]::GetFileName($scriptFile) 42 | $scriptVersion = "0.1" 43 | 44 | 45 | #-----------------------------------------------------------[Functions]------------------------------------------------------------ 46 | 47 | function Select-FileDialog 48 | { 49 | param([string]$Title,[string]$Filter="All files *.*|*.*") 50 | [System.Reflection.Assembly]::LoadWithPartialName( 'System.Windows.Forms' ) | Out-Null 51 | $fileDialogBox = New-Object Windows.Forms.OpenFileDialog 52 | $fileDialogBox.ShowHelp = $false 53 | $fileDialogBox.initialDirectory = $ScriptDir 54 | $fileDialogBox.filter = $Filter 55 | $fileDialogBox.Title = $Title 56 | $Show = $fileDialogBox.ShowDialog( ) 57 | 58 | If ($Show -eq "OK") 59 | { 60 | Return $fileDialogBox.FileName 61 | } 62 | Else 63 | { 64 | Write-Error "Canceled operation" 65 | [System.Windows.Forms.MessageBox]::Show("Script is not able to continue. Operation stopped." , "Operation canceled" , 0, [Windows.Forms.MessageBoxIcon]::Error) 66 | Stop-TranscriptOnLog 67 | Exit 68 | } 69 | 70 | } 71 | 72 | 73 | #----------------------------------------------------------[Execution]---------------------------------------------------------- 74 | 75 | cls 76 | 77 | # Import file to encode 78 | [System.Windows.Forms.MessageBox]::Show( 79 | " 80 | Select on this window the file that you want to encode to Base64 81 | ", "Select file", 0, [Windows.Forms.MessageBoxIcon]::Question) 82 | 83 | $FileToEncode = Select-FileDialog -Title "Select file" 84 | $Content = Get-Content -Path $FileToEncode -Encoding Byte 85 | $Base64 = [System.Convert]::ToBase64String($Content) 86 | $EncodedOutput = $FileToEncode + "-encoded.txt" 87 | $Base64 | Out-File $EncodedOutput 88 | 89 | # Inform user to the end of the process, and let the possibility to open the output 90 | $OUTPUT = [System.Windows.Forms.MessageBox]::Show("Encoded version was create well. Would you like to open it?", "Ended Base64 encoding", 4, [Windows.Forms.MessageBoxIcon]::Question) 91 | if ($OUTPUT -eq "YES") 92 | { 93 | notepad $EncodedOutput 94 | } 95 | 96 | else 97 | { 98 | [System.Windows.Forms.MessageBox]::Show("End of the script.", "Ended Base64 encoding process", 0, [Windows.Forms.MessageBoxIcon]::Information) 99 | } -------------------------------------------------------------------------------- /Miscellaneous/Get-MicrosoftLicenceStatus.ps1: -------------------------------------------------------------------------------- 1 | <# 2 | #USAGE 3 | PS C:\temp\> ./Get-MicrosoftLicenceStatus.ps1 4 | 5 | # RESULT 6 | Name ApplicationId LicenseStatus 7 | ---- ------------- ------------- 8 | Windows(R), Professional edition 55c92734-d682-4d71-983e-d6ec3f16059f Licensed 9 | Office 16, Office16ProPlusVL_KMS_Client edition 0ff1ce15-a989-479d-af46-f275c6370663 Licensed 10 | #> 11 | 12 | $lstat = DATA { 13 | ConvertFrom-StringData -StringData @' 14 | 0 = Unlicensed 15 | 1 = Licensed 16 | 2 = OOB Grace 17 | 3 = OOT Grace 18 | 4 = Non-Genuine Grace 19 | 5 = Notification 20 | 6 = Extended Grace 21 | '@} 22 | 23 | function Get-MicrosoftLicenseStatus { 24 | param ( 25 | [parameter(ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)] 26 | [string]$computername="$env:COMPUTERNAME" 27 | ) 28 | 29 | PROCESS { 30 | Get-WmiObject SoftwareLicensingProduct -ComputerName $computername | 31 | where {$_.PartialProductKey} | select Name, ApplicationId,@{N="LicenseStatus"; E={$lstat["$($_.LicenseStatus)"]} } 32 | } 33 | } 34 | 35 | Get-MicrosoftLicenseStatus 36 | -------------------------------------------------------------------------------- /Miscellaneous/Mount-NetworkDrive: -------------------------------------------------------------------------------- 1 | #requires -version 2 2 | <# 3 | .SYNOPSIS 4 | 5 | 6 | .DESCRIPTION 7 | 8 | 9 | .INPUTS 10 | 11 | 12 | .OUTPUTS 13 | Fill a log file similar to $ScriptDir\[SCRIPTNAME]_[YYYY_MM_DD]_[HHhMMmSSs].log 14 | 15 | 16 | 17 | .NOTES 18 | Version: 0.1 19 | Author: ALBERT Jean-Marc 20 | Creation Date: 22/05/2017 (DD/MM/YYYY) 21 | Purpose/Change: 0.1 - 2017.05.22 - ALBERT Jean-Marc - Initial script development 22 | 0.2 - 2017.05.23 - ALBERT Jean-Marc - Add GUI auto-close when clicking on principal button 23 | 24 | 25 | .SOURCES 26 | 27 | 28 | 29 | .EXAMPLE 30 | 31 | 32 | #> 33 | 34 | #region ---------------------------------------------------------[Initialisations]-------------------------------------------------------- 35 | Set-StrictMode -version Latest 36 | 37 | #Set Error Action to Silently Continue 38 | $ErrorActionPreference = "SilentlyContinue" 39 | 40 | $launchDate = get-date -f "dd/MM/yyyy" 41 | $launchHour = get-date -f "HH:mm:ss" 42 | 43 | Add-Type -AssemblyName System.Windows.Forms 44 | 45 | #endregion 46 | 47 | #region ----------------------------------------------------------[Declarations]---------------------------------------------------------- 48 | 49 | $scriptName = [System.IO.Path]::GetFileName($scriptFile) 50 | $scriptVersion = "0.2" 51 | 52 | $scriptPath = split-path -parent $MyInvocation.MyCommand.Definition 53 | $logPathName = "$SourceFolderPath\$logFileName" 54 | 55 | $NetworkDriveLetter = 'A:' 56 | $NetworkDriveLabel = 'Network drive label' 57 | $NetworkDrivePath = '\\domain.com\folder' 58 | $NetworkDriveAccountDomain = 'DOMAIN' 59 | 60 | #endregion 61 | 62 | #region -----------------------------------------------------------[Functions]------------------------------------------------------------ 63 | 64 | $Script:showWindowAsync = Add-Type -MemberDefinition @" 65 | [DllImport("user32.dll")] 66 | public static extern bool ShowWindowAsync(IntPtr hWnd, int nCmdShow); 67 | "@ -Name "Win32ShowWindowAsync" -Namespace Win32Functions -PassThru 68 | Function Show-Powershell() 69 | {$null = $showWindowAsync::ShowWindowAsync((Get-Process -Id $pid).MainWindowHandle, 10)} 70 | Function Hide-Powershell() 71 | {$null = $showWindowAsync::ShowWindowAsync((Get-Process -Id $pid).MainWindowHandle, 2)} 72 | 73 | #endregion 74 | 75 | #region -----------------------------------------------------------[Execution]---------------------------------------------------------- 76 | 77 | #region Mount 78 | 79 | #Hide Powershell console 80 | Hide-Powershell 81 | 82 | If (!(Test-Path $NetworkDriveLetter)) 83 | { 84 | #region Generate & show form 85 | $Form = New-Object system.Windows.Forms.Form 86 | $Form.Text = "COMPANYNAME - Network share '$NetworkDriveLabel'" 87 | $form.FormBorderStyle = [System.Windows.Forms.FormBorderStyle]::FixedDialog 88 | $form.StartPosition = "CenterScreen" 89 | $form.MaximizeBox = $false 90 | $form.MinimizeBox = $false 91 | $Form.TopMost = $true 92 | $Form.Width = 460 93 | $Form.Height = 240 94 | 95 | $labelDescription = New-Object system.windows.Forms.Label 96 | $labelDescription.Text = "Please fill information below in order to access on network share 97 | '$NetworkDriveLabel' ($NetworkDriveLetter) and make it available in 'Computer'. 98 | 99 | All field are mandatory." 100 | $labelDescription.AutoSize = $true 101 | $labelDescription.Width = 25 102 | $labelDescription.Height = 10 103 | $labelDescription.location = new-object system.drawing.point(10,20) 104 | $labelDescription.Font = "Microsoft Sans Serif,10" 105 | $Form.controls.Add($labelDescription) 106 | 107 | 108 | $LabelUser = New-Object system.windows.Forms.Label 109 | $LabelUser.Text = "User:" 110 | $LabelUser.AutoSize = $true 111 | $LabelUser.Width = 25 112 | $LabelUser.Height = 10 113 | $LabelUser.location = new-object system.drawing.point(24,135) 114 | $LabelUser.Font = "Microsoft Sans Serif,10" 115 | $Form.controls.Add($LabelUser) 116 | $textBoxUser = New-Object system.windows.Forms.TextBox 117 | $textBoxUser.Text = 'xxxxx' 118 | $textBoxUser.Enabled = $true 119 | $textBoxUser.Width = 100 120 | $textBoxUser.Height = 20 121 | $textBoxUser.location = new-object system.drawing.point(130,135) 122 | $textBoxUser.Font = "Microsoft Sans Serif,10" 123 | $Form.controls.Add($textBoxUser) 124 | 125 | $LabelPassword = New-Object system.windows.Forms.Label 126 | $LabelPassword.Text = "Password:" 127 | $LabelPassword.AutoSize = $true 128 | $LabelPassword.Width = 25 129 | $LabelPassword.Height = 10 130 | $LabelPassword.location = new-object system.drawing.point(24,160) 131 | $LabelPassword.Font = "Microsoft Sans Serif,10" 132 | $Form.Controls.Add($LabelPassword) 133 | $textBoxPassword = New-Object system.windows.Forms.MaskedTextBox 134 | $textBoxPassword.PasswordChar = '*' 135 | $textBoxPassword.Enabled = $true 136 | $textBoxPassword.Width = 100 137 | $textBoxPassword.Height = 20 138 | $textBoxPassword.location = new-object system.drawing.point(130,160) 139 | $textBoxPassword.Font = "Microsoft Sans Serif,10" 140 | $Form.controls.Add($textBoxPassword) 141 | 142 | 143 | $buttonStartMount = New-Object system.windows.Forms.Button 144 | $buttonStartMount.Text = "Access to '$NetworkDriveLabel'" 145 | $buttonStartMount.Width = 190 146 | $buttonStartMount.Height = 50 147 | $buttonStartMount.Add_MouseClick({ 148 | #Mount network share 149 | $NetworkDriveAccount = $NetworkDriveAccountDomain + '\' + $textBoxUser.Text 150 | (New-Object -ComObject WScript.Network).MapNetworkDrive($NetworkDriveLetter,$NetworkDrivePath,$true,$NetworkDriveAccount,$textBoxPassword.Text) 151 | #Rename it 152 | (New-Object -ComObject Shell.Application).NameSpace($NetworkDriveLetter).Self.Name=$NetworkDriveLabel 153 | #Open it on a new explorer windows 154 | Invoke-Item $NetworkDrivePath 155 | $Form.Close() 156 | 157 | }) 158 | $buttonStartMount.location = new-object system.drawing.point(248,133) 159 | $buttonStartMount.Font = "Microsoft Sans Serif,10" 160 | $Form.controls.Add($buttonStartMount) 161 | 162 | [void]$Form.ShowDialog() 163 | $Form.Dispose() 164 | #endregion 165 | 166 | } 167 | else { 168 | Write-Error -Message "$NetworkDriveLabel ($NetworkDriveLetter) already connected." 169 | [Windows.Forms.MessageBox]::Show("$NetworkDriveLabel ($NetworkDriveLetter) already connected.", 'Operation stopped', 0, [Windows.Forms.MessageBoxIcon]::Information) 170 | } 171 | -------------------------------------------------------------------------------- /Miscellaneous/New-IsoFile.ps1: -------------------------------------------------------------------------------- 1 | function New-IsoFile 2 | { 3 | <# 4 | .Synopsis 5 | Creates a new .iso file 6 | .Description 7 | The New-IsoFile cmdlet creates a new .iso file containing content from chosen folders 8 | .Example 9 | New-IsoFile "c:\tools","c:Downloads\utils" 10 | This command creates a .iso file in $env:temp folder (default location) that contains c:\tools and c:\downloads\utils folders. The folders themselves are included at the root of the .iso image. 11 | .Example 12 | New-IsoFile -FromClipboard -Verbose 13 | Before running this command, select and copy (Ctrl-C) files/folders in Explorer first. 14 | .Example 15 | dir c:\WinPE | New-IsoFile -Path c:\temp\WinPE.iso -BootFile "${env:ProgramFiles(x86)}\Windows Kits\10\Assessment and Deployment Kit\Deployment Tools\amd64\Oscdimg\efisys.bin" -Media DVDPLUSR -Title "WinPE" 16 | This command creates a bootable .iso file containing the content from c:\WinPE folder, but the folder itself isn't included. Boot file etfsboot.com can be found in Windows ADK. Refer to IMAPI_MEDIA_PHYSICAL_TYPE enumeration for possible media types: http://msdn.microsoft.com/en-us/library/windows/desktop/aa366217(v=vs.85).aspx 17 | .Notes 18 | NAME: New-IsoFile 19 | AUTHOR: Chris Wu 20 | LASTEDIT: 03/23/2016 14:46:50 21 | #> 22 | 23 | [CmdletBinding(DefaultParameterSetName='Source')]Param( 24 | [parameter(Position=1,Mandatory=$true,ValueFromPipeline=$true, ParameterSetName='Source')]$Source, 25 | [parameter(Position=2)][string]$Path = "$env:temp\$((Get-Date).ToString('yyyyMMdd-HHmmss.ffff')).iso", 26 | [ValidateScript({Test-Path -LiteralPath $_ -PathType Leaf})][string]$BootFile = $null, 27 | [ValidateSet('CDR','CDRW','DVDRAM','DVDPLUSR','DVDPLUSRW','DVDPLUSR_DUALLAYER','DVDDASHR','DVDDASHRW','DVDDASHR_DUALLAYER','DISK','DVDPLUSRW_DUALLAYER','BDR','BDRE')][string] $Media = 'DVDPLUSRW_DUALLAYER', 28 | [string]$Title = (Get-Date).ToString("yyyyMMdd-HHmmss.ffff"), 29 | [switch]$Force, 30 | [parameter(ParameterSetName='Clipboard')][switch]$FromClipboard 31 | ) 32 | 33 | Begin { 34 | ($cp = new-object System.CodeDom.Compiler.CompilerParameters).CompilerOptions = '/unsafe' 35 | if (!('ISOFile' -as [type])) { 36 | Add-Type -CompilerParameters $cp -TypeDefinition @' 37 | public class ISOFile 38 | { 39 | public unsafe static void Create(string Path, object Stream, int BlockSize, int TotalBlocks) 40 | { 41 | int bytes = 0; 42 | byte[] buf = new byte[BlockSize]; 43 | var ptr = (System.IntPtr)(&bytes); 44 | var o = System.IO.File.OpenWrite(Path); 45 | var i = Stream as System.Runtime.InteropServices.ComTypes.IStream; 46 | 47 | if (o != null) { 48 | while (TotalBlocks-- > 0) { 49 | i.Read(buf, BlockSize, ptr); o.Write(buf, 0, bytes); 50 | } 51 | o.Flush(); o.Close(); 52 | } 53 | } 54 | } 55 | '@ 56 | } 57 | 58 | if ($BootFile) { 59 | if('BDR','BDRE' -contains $Media) { Write-Warning "Bootable image doesn't seem to work with media type $Media" } 60 | ($Stream = New-Object -ComObject ADODB.Stream -Property @{Type=1}).Open() # adFileTypeBinary 61 | $Stream.LoadFromFile((Get-Item -LiteralPath $BootFile).Fullname) 62 | ($Boot = New-Object -ComObject IMAPI2FS.BootOptions).AssignBootImage($Stream) 63 | } 64 | 65 | $MediaType = @('UNKNOWN','CDROM','CDR','CDRW','DVDROM','DVDRAM','DVDPLUSR','DVDPLUSRW','DVDPLUSR_DUALLAYER','DVDDASHR','DVDDASHRW','DVDDASHR_DUALLAYER','DISK','DVDPLUSRW_DUALLAYER','HDDVDROM','HDDVDR','HDDVDRAM','BDROM','BDR','BDRE') 66 | 67 | Write-Verbose -Message "Selected media type is $Media with value $($MediaType.IndexOf($Media))" 68 | ($Image = New-Object -com IMAPI2FS.MsftFileSystemImage -Property @{VolumeName=$Title}).ChooseImageDefaultsForMediaType($MediaType.IndexOf($Media)) 69 | 70 | if (!($Target = New-Item -Path $Path -ItemType File -Force:$Force -ErrorAction SilentlyContinue)) { Write-Error -Message "Cannot create file $Path. Use -Force parameter to overwrite if the target file already exists."; break } 71 | } 72 | 73 | Process { 74 | if($FromClipboard) { 75 | if($PSVersionTable.PSVersion.Major -lt 5) { Write-Error -Message 'The -FromClipboard parameter is only supported on PowerShell v5 or higher'; break } 76 | $Source = Get-Clipboard -Format FileDropList 77 | } 78 | 79 | foreach($item in $Source) { 80 | if($item -isnot [System.IO.FileInfo] -and $item -isnot [System.IO.DirectoryInfo]) { 81 | $item = Get-Item -LiteralPath $item 82 | } 83 | 84 | if($item) { 85 | Write-Verbose -Message "Adding item to the target image: $($item.FullName)" 86 | try { $Image.Root.AddTree($item.FullName, $true) } catch { Write-Error -Message ($_.Exception.Message.Trim() + ' Try a different media type.') } 87 | } 88 | } 89 | } 90 | 91 | End { 92 | if ($Boot) { $Image.BootImageOptions=$Boot } 93 | $Result = $Image.CreateResultImage() 94 | [ISOFile]::Create($Target.FullName,$Result.ImageStream,$Result.BlockSize,$Result.TotalBlocks) 95 | Write-Verbose -Message "Target image ($($Target.FullName)) has been created" 96 | $Target 97 | } 98 | } 99 | -------------------------------------------------------------------------------- /Miscellaneous/SearchAndListObject-WithRegularExpression/SearchAndListObject-WithRegularExpression.ps1: -------------------------------------------------------------------------------- 1 | SearchAndListObject-WithRegularExpression 2 | #requires -version 2 3 | <# 4 | .SYNOPSIS 5 | 6 | 7 | .DESCRIPTION 8 | 9 | 10 | .INPUTS 11 | 12 | 13 | .OUTPUTS 14 | Create transcript log file similar to $ScriptDir\[SCRIPTNAME]_[YYYY_MM_DD]_[HHhMMmSSs].log 15 | Create a list of SUBJECT, similar to $ScriptDir\[SCRIPTNAME]_SUBJECT_[YYYY_MM_DD]_[HHhMMmSSs].csv 16 | 17 | .NOTES 18 | Version: 0.1 19 | Author: ALBERT Jean-Marc 20 | Creation Date: 19/03/2016 (DD/MM/YYYY) 21 | Purpose/Change: 1.0 - 2016.03.19 - ALBERT Jean-Marc - Initial script development 22 | 23 | 24 | .SOURCES 25 | 26 | 27 | 28 | .EXAMPLE 29 | 30 | 31 | #> 32 | 33 | #---------------------------------------------------------[Initialisations]-------------------------------------------------------- 34 | Set-StrictMode -version Latest 35 | 36 | #Set Error Action to Silently Continue 37 | $ErrorActionPreference = "SilentlyContinue" 38 | $scriptFile = $MyInvocation.MyCommand.Definition 39 | 40 | 41 | #----------------------------------------------------------[Declarations]---------------------------------------------------------- 42 | 43 | $scriptName = [System.IO.Path]::GetFileName($scriptFile) 44 | $scriptVersion = "0.1" 45 | 46 | 47 | #-----------------------------------------------------------[Functions]------------------------------------------------------------ 48 | 49 | function Select-FileDialog 50 | { 51 | param([string]$Title,[string]$Filter="All files *.*|*.*") 52 | [System.Reflection.Assembly]::LoadWithPartialName( 'System.Windows.Forms' ) | Out-Null 53 | $fileDialogBox = New-Object Windows.Forms.OpenFileDialog 54 | $fileDialogBox.ShowHelp = $false 55 | $fileDialogBox.initialDirectory = $ScriptDir 56 | $fileDialogBox.filter = $Filter 57 | $fileDialogBox.Title = $Title 58 | $Show = $fileDialogBox.ShowDialog( ) 59 | 60 | If ($Show -eq "OK") 61 | { 62 | Return $fileDialogBox.FileName 63 | } 64 | Else 65 | { 66 | Write-Error "Canceled operation" 67 | [System.Windows.Forms.MessageBox]::Show("Script is not able to continue. Operation stopped." , "Operation canceled" , 0, [Windows.Forms.MessageBoxIcon]::Error) 68 | Stop-TranscriptOnLog 69 | Exit 70 | } 71 | 72 | } 73 | 74 | 75 | #----------------------------------------------------------[Execution]---------------------------------------------------------- 76 | 77 | cls 78 | 79 | # Import file to encode 80 | [System.Windows.Forms.MessageBox]::Show( 81 | " 82 | Select on this window the file that you want to encode to Base64 83 | ", "Select file", 0, [Windows.Forms.MessageBoxIcon]::Question) 84 | 85 | $FileToEncode = Select-FileDialog -Title "Select file" 86 | $Content = Get-Content -Path $FileToEncode -Encoding Byte 87 | $Base64 = [System.Convert]::ToBase64String($Content) 88 | $EncodedOutput = $FileToEncode + "-encoded.txt" 89 | $Base64 | Out-File $EncodedOutput 90 | 91 | # Inform user to the end of the process, and let the possibility to open the output 92 | $OUTPUT = [System.Windows.Forms.MessageBox]::Show("Encoded version was create well. Would you like to open it?", "Ended Base64 encoding", 4, [Windows.Forms.MessageBoxIcon]::Question) 93 | if ($OUTPUT -eq "YES") 94 | { 95 | notepad $EncodedOutput 96 | } 97 | 98 | else 99 | { 100 | [System.Windows.Forms.MessageBox]::Show("End of the script.", "Ended Base64 encoding process", 0, [Windows.Forms.MessageBoxIcon]::Information) 101 | } -------------------------------------------------------------------------------- /Miscellaneous/Show-BalloonNotificationThenStartProcessOnUserClick.ps1: -------------------------------------------------------------------------------- 1 | #Load the required assemblies 2 | [void] [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms") 3 | #Remove any registered events related to notifications 4 | Remove-Event BalloonClicked_event -ea SilentlyContinue 5 | Unregister-Event -SourceIdentifier BalloonClicked_event -ea silentlycontinue 6 | Remove-Event BalloonClosed_event -ea SilentlyContinue 7 | Unregister-Event -SourceIdentifier BalloonClosed_event -ea silentlycontinue 8 | Remove-Event Disposed -ea SilentlyContinue 9 | Unregister-Event -SourceIdentifier Disposed -ea silentlycontinue 10 | 11 | #Get domain 12 | $MachineDomain = (Get-WmiObject Win32_ComputerSystem).Domain 13 | 14 | 15 | #Create the notification object 16 | $notification = New-Object System.Windows.Forms.NotifyIcon 17 | #Define various parts of the notification 18 | $notification.Icon = [System.Drawing.SystemIcons]::Error 19 | $notification.BalloonTipTitle = "Connection error on $MachineDomain" 20 | $notification.BalloonTipIcon = "Error" 21 | $title = "Credentials have expired, please reauthenticate by clicking on this message" 22 | $notification.BalloonTipText = $title 23 | 24 | #Make balloon tip visible when called 25 | $notification.Visible = $True 26 | 27 | ## Register a click event with action to take based on event 28 | #Balloon message clicked 29 | register-objectevent $notification BalloonTipClicked BalloonClicked_event -Action { 30 | Start-Process 'iexplore.exe' -ArgumentList 'http://www.google.com' -WindowStyle Maximized -Verb Open 31 | #Get rid of the icon after action is taken 32 | $notification.Dispose() 33 | } | Out-Null 34 | 35 | #Balloon message closed 36 | register-objectevent $notification BalloonTipClosed BalloonClosed_event -Action {$notification.Dispose()} | Out-Null 37 | 38 | #Call the balloon notification 39 | $notification.ShowBalloonTip(1000) 40 | 41 | #Add a Sleep to avoid end of PowerShell process before user click on balloon 42 | Sleep(1) 43 | -------------------------------------------------------------------------------- /Miscellaneous/Start-MSRA.ps1: -------------------------------------------------------------------------------- 1 | #requires -version 2 2 | <# 3 | .SYNOPSIS 4 | 5 | 6 | .DESCRIPTION 7 | 8 | 9 | .INPUTS 10 | 11 | 12 | .OUTPUTS 13 | Fill a log file similar to $ScriptDir\[SCRIPTNAME]_[YYYY_MM_DD]_[HHhMMmSSs].log 14 | 15 | 16 | 17 | .NOTES 18 | Version: 1.2 19 | Author: ALBERT Jean-Marc 20 | Creation Date: 22/02/2017 (DD/MM/YYYY) 21 | Purpose/Change: 1.0 - 2017.02.22 - ALBERT Jean-Marc - Initial script development 22 | 1.1 - 2017.02.27 - ALBERT Jean-Marc - Add combobox for Computer and User, thanks to request on Active Directory objects 23 | Modify logged information thanks to modification somewhat above 24 | Move buttons 25 | Apply templace to this script 26 | 1.2 - 2017.02.27 - ALBERT Jean-Marc - Verify log's first line 27 | Add #region to [Execution] region 28 | 29 | .SOURCES 30 | 31 | 32 | 33 | .EXAMPLE 34 | 35 | 36 | #> 37 | 38 | #region ---------------------------------------------------------[Initialisations]-------------------------------------------------------- 39 | Set-StrictMode -version Latest 40 | 41 | #Set Error Action to Silently Continue 42 | $ErrorActionPreference = "SilentlyContinue" 43 | 44 | $launchDate = get-date -f "dd/MM/yyyy" 45 | $launchHour = get-date -f "HH:mm:ss" 46 | 47 | Import-Module ActiveDirectory 48 | Add-Type -AssemblyName System.Windows.Forms 49 | 50 | #endregion 51 | 52 | #region ----------------------------------------------------------[Declarations]---------------------------------------------------------- 53 | 54 | $scriptName = [System.IO.Path]::GetFileName($scriptFile) 55 | $scriptVersion = "1.2" 56 | 57 | $scriptPath = split-path -parent $MyInvocation.MyCommand.Definition 58 | $logFileName = "pmad.log" 59 | $logPathName = "C:\temp\$logFileName" 60 | $logFileFirstLine = "Date,Heure,PosteAdmin,Admin,Utilisateur,PosteUser,Ticket" 61 | 62 | $domain = [System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain() 63 | 64 | $LDAPUserArray = Get-ADuser -SearchBase "OU=Users,DC=contorso,DC=dom" -Filter * | Select Name,SamAccountName | Sort Name 65 | $LDAPComputerArray = Get-ADComputer -SearchBase "OU=Computers,DC=contorso,DC=dom" -Filter * | Select Name | Sort Name 66 | 67 | #endregion 68 | 69 | #region -----------------------------------------------------------[Functions]------------------------------------------------------------ 70 | function Set-FirstLine { 71 | param ( 72 | [string]$Path, 73 | [string]$Value 74 | ) 75 | $oldcontent = Get-Content $Path 76 | Set-Content -Path $Path -Value $Value 77 | Add-Content -Path $Path -Value $oldcontent 78 | } 79 | #endregion 80 | 81 | #region -----------------------------------------------------------[Execution]---------------------------------------------------------- 82 | 83 | #region Verify log's first line 84 | $logFileFirstLineContent = Get-content $logPathName -First 1 85 | if($logFileFirstLineContent -ne $logFileFirstLine){ 86 | Set-FirstLine -Path $logPathName -Value $logFileFirstLine 87 | } 88 | #endregion 89 | 90 | #region Generate & show form 91 | $Form = New-Object system.Windows.Forms.Form 92 | $Form.Text = "Contrôle à distance" 93 | $form.FormBorderStyle = [System.Windows.Forms.FormBorderStyle]::FixedDialog 94 | $form.StartPosition = "CenterScreen" 95 | $form.MaximizeBox = $false 96 | $form.MinimizeBox = $false 97 | $Form.TopMost = $false 98 | $Form.Width = 460 99 | $Form.Height = 305 100 | 101 | $labelDescription = New-Object system.windows.Forms.Label 102 | $labelDescription.Text = "Merci de remplir les champs ci-dessous afin de prendre la main 103 | sur un poste CONTORSO. 104 | 105 | Tous sont obligatoires." 106 | $labelDescription.AutoSize = $true 107 | $labelDescription.Width = 25 108 | $labelDescription.Height = 10 109 | $labelDescription.location = new-object system.drawing.point(10,20) 110 | $labelDescription.Font = "Microsoft Sans Serif,10" 111 | $Form.controls.Add($labelDescription) 112 | 113 | $LabelProd = New-Object system.windows.Forms.Label 114 | $LabelProd.Text = "Administrateur" 115 | $LabelProd.AutoSize = $true 116 | $LabelProd.Width = 25 117 | $LabelProd.Height = 10 118 | $LabelProd.location = new-object system.drawing.point(24,101) 119 | $LabelProd.Font = "Microsoft Sans Serif,10" 120 | $Form.controls.Add($LabelProd) 121 | $textBoxProd = New-Object system.windows.Forms.TextBox 122 | $textBoxProd.Text = $env:USERNAME 123 | $textBoxProd.Enabled = $false 124 | $textBoxProd.Width = 100 125 | $textBoxProd.Height = 20 126 | $textBoxProd.location = new-object system.drawing.point(125,101) 127 | $textBoxProd.Font = "Microsoft Sans Serif,10" 128 | $Form.controls.Add($textBoxProd) 129 | $textBoxProdComputer = New-Object system.windows.Forms.TextBox 130 | $textBoxProdComputer.Text = $env:COMPUTERNAME 131 | $textBoxProdComputer.Enabled = $false 132 | $textBoxProdComputer.Width = 100 133 | $textBoxProdComputer.Height = 20 134 | $textBoxProdComputer.location = new-object system.drawing.point(265,101) 135 | $textBoxProdComputer.Font = "Microsoft Sans Serif,10" 136 | $Form.controls.Add($textBoxProdComputer) 137 | 138 | $LabelUtilisateur = New-Object system.windows.Forms.Label 139 | $LabelUtilisateur.Text = "Utilisateur" 140 | $LabelUtilisateur.AutoSize = $true 141 | $LabelUtilisateur.Width = 25 142 | $LabelUtilisateur.Height = 10 143 | $LabelUtilisateur.location = new-object system.drawing.point(24,151) 144 | $LabelUtilisateur.Font = "Microsoft Sans Serif,10" 145 | $Form.controls.Add($LabelUtilisateur) 146 | $comboBoxUtilisateur = New-Object system.windows.Forms.ComboBox 147 | $comboBoxUtilisateur.Text = "xxxN" 148 | $comboBoxUtilisateur.Width = 220 149 | $comboBoxUtilisateur.Height = 20 150 | $comboBoxUtilisateur.location = new-object system.drawing.point(125,151) 151 | $comboBoxUtilisateur.Font = "Microsoft Sans Serif,10" 152 | $Form.controls.Add($comboBoxUtilisateur) 153 | foreach ($LDAPUser in $LDAPUserArray) { 154 | $LDAPUserResult = "{0} ({1})" -f $LDAPUser.Name, $LDAPUser.SamAccountName 155 | [void] $comboBoxUtilisateur.Items.Add($LDAPUserResult) 156 | } 157 | 158 | $LabelComputerName = New-Object system.windows.Forms.Label 159 | $LabelComputerName.Text = "Poste" 160 | $LabelComputerName.AutoSize = $true 161 | $LabelComputerName.Width = 25 162 | $LabelComputerName.Height = 10 163 | $LabelComputerName.location = new-object system.drawing.point(23,188) 164 | $LabelComputerName.Font = "Microsoft Sans Serif,10" 165 | $Form.controls.Add($LabelComputerName) 166 | $comboBoxComputerName = New-Object system.windows.Forms.ComboBox 167 | $comboBoxComputerName.Text = "Uxnnnnnnnnn" 168 | $comboBoxComputerName.Width = 110 169 | $comboBoxComputerName.Height = 20 170 | $comboBoxComputerName.location = new-object system.drawing.point(125,189) 171 | $comboBoxComputerName.Font = "Microsoft Sans Serif,10" 172 | $Form.controls.Add($comboBoxComputerName) 173 | foreach ($LDAPComputer in $LDAPComputerArray) { 174 | [void] $comboBoxComputerName.Items.Add($LDAPComputer.Name) 175 | } 176 | 177 | $labelTicket = New-Object system.windows.Forms.Label 178 | $labelTicket.Text = "Ticket" 179 | $labelTicket.AutoSize = $true 180 | $labelTicket.Width = 25 181 | $labelTicket.Height = 10 182 | $labelTicket.location = new-object system.drawing.point(22,230) 183 | $labelTicket.Font = "Microsoft Sans Serif,10" 184 | $Form.controls.Add($labelTicket) 185 | $textBoxTicket = New-Object system.windows.Forms.TextBox 186 | $textBoxTicket.Text = "xxxxx" 187 | $textBoxTicket.Width = 110 188 | $textBoxTicket.Height = 20 189 | $textBoxTicket.location = new-object system.drawing.point(125,230) 190 | $textBoxTicket.Font = "Microsoft Sans Serif,10" 191 | $Form.controls.Add($textBoxTicket) 192 | 193 | $buttonStartRC = New-Object system.windows.Forms.Button 194 | $buttonStartRC.Text = "Lancer contrôle à distance" 195 | $buttonStartRC.Width = 140 196 | $buttonStartRC.Height = 50 197 | $buttonStartRC.Add_MouseClick({ 198 | $Result = "$env:COMPUTERNAME,$env:USERNAME,$($comboBoxUtilisateur.Text),$($textBoxComputerName.Text),$($textBoxTicket.Text)" 199 | $launchDate + ',' + $launchHour + ',' +$env:COMPUTERNAME + ',' + $env:USERNAME + ',' + $comboBoxUtilisateur.Text + ',' + $comboBoxComputerName.Text + ',' + $textBoxTicket.Text | Out-File -filepath $logPathName -Append -Encoding UTF8 200 | msra.exe /offerRA $comboBoxComputerName.Text 201 | }) 202 | $buttonStartRC.location = new-object system.drawing.point(240,195) 203 | $buttonStartRC.Font = "Microsoft Sans Serif,10" 204 | $Form.controls.Add($buttonStartRC) 205 | 206 | $buttonLog = New-Object system.windows.Forms.Button 207 | $buttonLog.Text = "Log" 208 | $buttonLog.Width = 60 209 | $buttonLog.Height = 30 210 | $buttonLog.location = new-object system.drawing.point(385,205) 211 | $buttonLog.Font = "Microsoft Sans Serif,10" 212 | $Form.controls.Add($buttonLog) 213 | $buttonLog.Add_MouseClick({ 214 | Invoke-Item $logPathName 215 | }) 216 | 217 | 218 | [void]$Form.ShowDialog() 219 | $Form.Dispose() 220 | #endregion 221 | 222 | #endregion 223 | 224 | #endregion 225 | -------------------------------------------------------------------------------- /Miscellaneous/Store-SecurestringToFile.ps1: -------------------------------------------------------------------------------- 1 | param( 2 | [Parameter(Mandatory=$true)] 3 | [string]$Path, 4 | [Parameter(Mandatory=$true)] 5 | [string]$password 6 | ) 7 | 8 | # Convert the password to a secure string 9 | $SecurePassword = $password | ConvertTo-SecureString -AsPlainText -Force 10 | 11 | # Store the credential in the path 12 | $SecurePassword | ConvertFrom-SecureString | Out-File $Path 13 | 14 | # Write What we did 15 | Write-Host "Wrote password to $path" 16 | 17 | <# 18 | .SYNOPSIS 19 | Stores a password in a file on the local computer for retrevial by scripts. 20 | 21 | .DESCRIPTION 22 | Used for securely storing a password on a machine for use with automated scripts. 23 | 24 | Takes a password and encrypts it using the local account, then stores that password in a file you specify. 25 | Only the account that creates the output file can decrypt the password stored in the file. 26 | 27 | .PARAMETER Path 28 | Path and file name for the password file that will be created. 29 | 30 | .PARAMETER Password 31 | Plain text version of password. 32 | 33 | .OUTPUTS 34 | File Specified in Path variable will contain an encrypted version of the password. 35 | 36 | .EXAMPLE 37 | .\Store-SecurestringToFile.ps1 -Path c:\scripts\scriptname.key -Password "Password123" 38 | 39 | Puts the encrypted version of Password123 into the c:\scripts\scriptname.key file 40 | #> 41 | -------------------------------------------------------------------------------- /Network Policy Server/Check_NPS_WorkStation_Prerequisites.ps1: -------------------------------------------------------------------------------- 1 | #requires -version 2 2 | <# 3 | .SYNOPSIS 4 | Check NPS prerequisites on Workstation 5 | 6 | .DESCRIPTION 7 | Check NPS prerequisites on Workstation, like AD membership, certificates presence and Wifi config 8 | 9 | .INPUTS 10 | 11 | 12 | .OUTPUTS 13 | 14 | 15 | .NOTES 16 | Version: 0.1 17 | Author: ALBERT Jean-Marc 18 | Creation Date: 03/11/2017 (DD/MM/YYYY) 19 | Purpose/Change: 1.0 - 2017.11.03 - ALBERT Jean-Marc - Initial script development 20 | 21 | .SOURCES 22 | 23 | 24 | .EXAMPLE 25 | 26 | 27 | #> 28 | 29 | #region ---------------------------------------------------------[Initialisations]-------------------------------------------------------- 30 | Set-StrictMode -version Latest 31 | 32 | #Set Error Action to Silently Continue 33 | $ErrorActionPreference = "SilentlyContinue" 34 | 35 | #Modify Window width 36 | Clear-Host 37 | $h = Get-Host 38 | $win = $h.ui.rawui.windowsize 39 | $win.Width = 68 40 | $h.ui.rawui.set_windowsize($win) 41 | #endregion 42 | 43 | #region ----------------------------------------------------------[Declarations]---------------------------------------------------------- 44 | $ComputerName = $env:COMPUTERNAME 45 | $DomainName = 'contoso.com' 46 | $DomainMembership = Test-Domain $ComputerName | Select-String Domain 47 | $TrustedRootCertificationAuthorityCertName = 'CN=contoso-rootCA, DC=contoso, DC=com' 48 | $TargetedADGroup = "Computer Wifi" 49 | $WifiCorrectAccessPointName = "*AccessPoint Name*" 50 | $WifiActiveConnection = netsh wlan show interfaces 51 | $WifiActiveConnectionSSID = $WifiActiveConnection | Select-String \sSSID 52 | #endregion 53 | 54 | #region -----------------------------------------------------------[Functions]------------------------------------------------------------ 55 | function Test-Domain { 56 | [CmdletBinding()] 57 | param ( 58 | [parameter(Position=0, 59 | Mandatory=$true, 60 | ValueFromPipeline=$true, 61 | ValueFromPipelineByPropertyName=$true)] 62 | [string]$computerName=$env:COMPUTERNAME 63 | ) 64 | BEGIN{} 65 | PROCESS{Get-WmiObject -Class Win32_ComputerSystem -ComputerName $ComputerName | Select Domain 66 | } 67 | END{} 68 | } 69 | function Get-ComputerADGroupMembership { 70 | Get-ADComputer $ComputerName -Properties MemberOf 71 | } 72 | #endregion 73 | 74 | #region -----------------------------------------------------------[Execution]------------------------------------------------------------ 75 | #Load PowerShell AD module before execution 76 | $ImportModuleADid = (Import-Module ActiveDirectory).id 77 | Wait-Process -Id $ImportModuleADid -Timeout 10 78 | 79 | 80 | Write-Host "------------------------------------------------------------------`n 81 | - Show actual computer name: -`n 82 | Computer: $ComputerName" 83 | Write-Host "------------------------------------------------------------------` 84 | - Check domain membership status: -" 85 | If ($DomainMembership -like "*$DomainName*" ) { 86 | Write-Host ' AD Group membership (need AD PowerShell module): OK' -ForegroundColor Green 87 | } 88 | 89 | Else { 90 | Write-Host ' AD Group membership (need AD PowerShell module): KO' -ForegroundColor Red 91 | } 92 | Write-Host "------------------------------------------------------------------` 93 | - Check authorized computer membership status: -" 94 | If (Get-ComputerADGroupMembership | Where {$_.MemberOf -like "*$TargetedADGroup*"} ) { 95 | Write-Host ' Domain membership: OK' -ForegroundColor Green 96 | } 97 | 98 | Else { 99 | Write-Host ' Domain membership: KO' -ForegroundColor Red 100 | } 101 | #Get-ComputerADGroupMembership | %{if ($_.MemberOf -like "*$TargetedADGroup*") {Write-Host "found"} 102 | 103 | 104 | Write-Host "------------------------------------------------------------------` 105 | - Check workstation certificate status: -" 106 | If (Get-ChildItem cert:\LocalMachine\My | Where Subject -like *$ComputerName* ) { 107 | Write-Host ' Computer Certificate: Present' -ForegroundColor Green 108 | 109 | } 110 | 111 | Else { 112 | Write-Host ' Computer Certificate: Missing' -ForegroundColor Red 113 | } 114 | 115 | Write-Host "------------------------------------------------------------------` 116 | - Check trusted root certification authority certificate status: -" 117 | 118 | If (Get-ChildItem cert:\LocalMachine\CA | Where Subject -eq $TrustedRootCertificationAuthorityCertName ) { 119 | Write-Host ' Trusted Root Certification Authority certificate: Present' -ForegroundColor Green 120 | 121 | } 122 | 123 | Else { 124 | Write-Host ' Trusted Root Certification Authority certificate:: Missing'-ForegroundColor Red 125 | } 126 | 127 | 128 | Write-Host "------------------------------------------------------------------` 129 | - Show actual Wifi connection: -" 130 | $WifiActiveConnection | Select-String SSID,Authentification,Chiffrement,'Mode de connexion',Signal 131 | If (!$WifiActiveConnection) { 132 | Write-Host 'No Wifi connection is active!' -ForegroundColor Red 133 | 134 | } 135 | 136 | If ($WifiActiveConnectionSSID -like $WifiCorrectAccessPointName) { 137 | Write-Host 'You are on the right AccessPoint' -ForegroundColor Green 138 | If (($WifiActiveConnection | Select-String 'Mode de connexion') -like "*Profil*") { 139 | Write-Host 'You received the right GPO' -ForegroundColor Green 140 | } 141 | Else { 142 | Write-Host '' 143 | Write-Host 'You have not received the right GPO!' -ForegroundColor Red 144 | } 145 | } 146 | Else { 147 | Write-Host '' 148 | Write-Host 'You are not on the right AccessPoint!' -ForegroundColor Red 149 | } 150 | 151 | Write-Host "------------------------------------------------------------------" 152 | Pause 153 | #endregion 154 | -------------------------------------------------------------------------------- /Network/Ping-Host.ps1: -------------------------------------------------------------------------------- 1 | <# 2 | .SYNOPSIS 3 | Ping one or multiple hosts then get a very informative and pleasant-looking result 4 | 5 | .DESCRIPTION 6 | 7 | Tweak the Test-Connection cmdlet available in powershell and make it Presentable with extended functionalities such as Colors, Host Status, Success and Failure Percentage, Number of ICMP Attempts. 8 | 9 | .PARAMETER Hosts 10 | A description of the Hosts parameter. 11 | 12 | .PARAMETER ToCsv 13 | A description of the ToCsv parameter. 14 | 15 | .EXAMPLE 16 | Ping Multiple Hostnames at a time 17 | PS C:\> Ping-Host '127.0.0.1','localhost','192.168.0.14','192.168.0.16','192.168.0.50','192.168.0.60' 18 | 19 | Ping Range of IP address at a time 20 | PS C:\> Ping-Host (100..150|%{"10.0.50.$_"}) 21 | 22 | Ping a list of Hostname in one go 23 | PS C:\> Ping-Host -Hosts (gc C:\list.txt) 24 | 25 | Ping Hostnames queried from ActiveDirectory 26 | PS C:\> Ping-Host -Hosts ((Get-ADComputer -Filter {name -like 'LSP*-DSP*'}).name}) 27 | 28 | .NOTES 29 | Additional information about the function. 30 | 31 | .LINK 32 | https://geekeefy.wordpress.com/2015/07/16/powershell-fancy-test-connection/ 33 | #> 34 | function Ping-Host 35 | { 36 | [CmdletBinding(HelpUri = ' https://geekeefy.wordpress.com/2015/07/16/powershell-fancy-test-connection/')] 37 | [OutputType([string])] 38 | param 39 | ( 40 | [Parameter(Position = 0)] 41 | $Hosts, 42 | [Parameter]$ToCsv 43 | ) 44 | 45 | #Parameter Definition 46 | 47 | #Funtion to make space so that formatting looks good 48 | Function Make-Space($l, $Maximum) 49 | { 50 | $space = "" 51 | $s = [int]($Maximum - $l) + 1 52 | 1 .. $s | %{ $space += " " } 53 | 54 | return [String]$space 55 | } 56 | #Array Variable to store length of all hostnames 57 | $LengthArray = @() 58 | $Hosts | %{ $LengthArray += $_.length } 59 | 60 | #Find Maximum length of hostname to adjust column witdth accordingly 61 | $Maximum = ($LengthArray | Measure-object -Maximum).maximum 62 | $Count = $hosts.Count 63 | 64 | #Initializing Array objects 65 | $Success = New-Object int[] $Count 66 | $Failure = New-Object int[] $Count 67 | $Total = New-Object int[] $Count 68 | cls 69 | #Running a never ending loop 70 | while ($true) 71 | { 72 | 73 | $i = 0 #Index number of the host stored in the array 74 | $out = "| HOST$(Make-Space 4 $Maximum)| STATUS | SUCCESS | FAILURE | ATTEMPTS |" 75 | $Firstline = "" 76 | 1 .. $out.length | %{ $firstline += "_" } 77 | 78 | #output the Header Row on the screen 79 | Write-Host $Firstline 80 | Write-host $out -ForegroundColor White -BackgroundColor Black 81 | 82 | $Hosts | %{ 83 | $total[$i]++ 84 | If (Test-Connection $_ -Count 1 -Quiet -ErrorAction SilentlyContinue) 85 | { 86 | $success[$i] += 1 87 | #Percent calclated on basis of number of attempts made 88 | $SuccessPercent = $("{0:N2}" -f (($success[$i]/$total[$i]) * 100)) 89 | $FailurePercent = $("{0:N2}" -f (($Failure[$i]/$total[$i]) * 100)) 90 | 91 | #Print status UP in GREEN if above condition is met 92 | Write-Host "| $_$(Make-Space $_.Length $Maximum)| UP$(Make-Space 2 4) | $SuccessPercent`%$(Make-Space ([string]$SuccessPercent).length 6) | $FailurePercent`%$(Make-Space ([string]$FailurePercent).length 6) | $($Total[$i])$(Make-Space ([string]$Total[$i]).length 9)|" -BackgroundColor Green 93 | } 94 | else 95 | { 96 | $Failure[$i] += 1 97 | 98 | #Percent calclated on basis of number of attempts made 99 | $SuccessPercent = $("{0:N2}" -f (($success[$i]/$total[$i]) * 100)) 100 | $FailurePercent = $("{0:N2}" -f (($Failure[$i]/$total[$i]) * 100)) 101 | 102 | #Print status DOWN in RED if above condition is met 103 | Write-Host "| $_$(Make-Space $_.Length $Maximum)| DOWN$(Make-Space 4 4) | $SuccessPercent`%$(Make-Space ([string]$SuccessPercent).length 6) | $FailurePercent`%$(Make-Space ([string]$FailurePercent).length 6) | $($Total[$i])$(Make-Space ([string]$Total[$i]).length 9)|" -BackgroundColor Red 104 | } 105 | $i++ 106 | 107 | } 108 | 109 | #Pause the loop for few seconds so that output 110 | #stays on screen for a while and doesn't refreshes 111 | 112 | Start-Sleep -Seconds 4 113 | cls 114 | } 115 | } 116 | -------------------------------------------------------------------------------- /Network/Test-Port.ps1: -------------------------------------------------------------------------------- 1 | function Test-Port{ 2 | <# 3 | .SYNOPSIS 4 | Tests port on computer. 5 | 6 | .DESCRIPTION 7 | Tests port on computer. 8 | 9 | .PARAMETER computer 10 | Name of server to test the port connection on. 11 | 12 | .PARAMETER port 13 | Port to test 14 | 15 | .PARAMETER tcp 16 | Use tcp port 17 | 18 | .PARAMETER udp 19 | Use udp port 20 | 21 | .PARAMETER UDPTimeOut 22 | Sets a timeout for UDP port query. (In milliseconds, Default is 1000) 23 | 24 | .PARAMETER TCPTimeOut 25 | Sets a timeout for TCP port query. (In milliseconds, Default is 1000) 26 | 27 | .NOTES 28 | Name: Test-Port.ps1 29 | Author: Boe Prox 30 | DateCreated: 18Aug2010 31 | List of Ports: http://www.iana.org/assignments/port-numbers 32 | 33 | To Do: 34 | Add capability to run background jobs for each host to shorten the time to scan. 35 | .LINK 36 | https://boeprox.wordpress.org 37 | 38 | .EXAMPLE 39 | Test-Port -computer 'server' -port 80 40 | Checks port 80 on server 'server' to see if it is listening 41 | 42 | .EXAMPLE 43 | 'server' | Test-Port -port 80 44 | Checks port 80 on server 'server' to see if it is listening 45 | 46 | .EXAMPLE 47 | Test-Port -computer @("server1","server2") -port 80 48 | Checks port 80 on server1 and server2 to see if it is listening 49 | 50 | .EXAMPLE 51 | Test-Port -comp dc1 -port 17 -udp -UDPtimeout 10000 52 | 53 | Server : dc1 54 | Port : 17 55 | TypePort : UDP 56 | Open : True 57 | Notes : "My spelling is Wobbly. It's good spelling but it Wobbles, and the letters 58 | get in the wrong places." A. A. Milne (1882-1958) 59 | 60 | Description 61 | ----------- 62 | Queries port 17 (qotd) on the UDP port and returns whether port is open or not 63 | 64 | .EXAMPLE 65 | @("server1","server2") | Test-Port -port 80 66 | Checks port 80 on server1 and server2 to see if it is listening 67 | 68 | .EXAMPLE 69 | (Get-Content hosts.txt) | Test-Port -port 80 70 | Checks port 80 on servers in host file to see if it is listening 71 | 72 | .EXAMPLE 73 | Test-Port -computer (Get-Content hosts.txt) -port 80 74 | Checks port 80 on servers in host file to see if it is listening 75 | 76 | .EXAMPLE 77 | Test-Port -computer (Get-Content hosts.txt) -port @(1..59) 78 | Checks a range of ports from 1-59 on all servers in the hosts.txt file 79 | 80 | #> 81 | [cmdletbinding( 82 | DefaultParameterSetName = '', 83 | ConfirmImpact = 'low' 84 | )] 85 | Param( 86 | [Parameter( 87 | Mandatory = $True, 88 | Position = 0, 89 | ParameterSetName = '', 90 | ValueFromPipeline = $True)] 91 | [array]$computer, 92 | [Parameter( 93 | Position = 1, 94 | Mandatory = $True, 95 | ParameterSetName = '')] 96 | [array]$port, 97 | [Parameter( 98 | Mandatory = $False, 99 | ParameterSetName = '')] 100 | [int]$TCPtimeout=1000, 101 | [Parameter( 102 | Mandatory = $False, 103 | ParameterSetName = '')] 104 | [int]$UDPtimeout=1000, 105 | [Parameter( 106 | Mandatory = $False, 107 | ParameterSetName = '')] 108 | [switch]$TCP, 109 | [Parameter( 110 | Mandatory = $False, 111 | ParameterSetName = '')] 112 | [switch]$UDP 113 | ) 114 | Begin { 115 | If (!$tcp -AND !$udp) {$tcp = $True} 116 | #Typically you never do this, but in this case I felt it was for the benefit of the function 117 | #as any errors will be noted in the output of the report 118 | $ErrorActionPreference = "SilentlyContinue" 119 | $report = @() 120 | } 121 | Process { 122 | ForEach ($c in $computer) { 123 | ForEach ($p in $port) { 124 | If ($tcp) { 125 | #Create temporary holder 126 | $temp = "" | Select Server, Port, TypePort, Open, Notes 127 | #Create object for connecting to port on computer 128 | $tcpobject = new-Object system.Net.Sockets.TcpClient 129 | #Connect to remote machine's port 130 | $connect = $tcpobject.BeginConnect($c,$p,$null,$null) 131 | #Configure a timeout before quitting 132 | $wait = $connect.AsyncWaitHandle.WaitOne($TCPtimeout,$false) 133 | #If timeout 134 | If(!$wait) { 135 | #Close connection 136 | $tcpobject.Close() 137 | Write-Verbose "Connection Timeout" 138 | #Build report 139 | $temp.Server = $c 140 | $temp.Port = $p 141 | $temp.TypePort = "TCP" 142 | $temp.Open = $False 143 | $temp.Notes = "Connection to Port Timed Out" 144 | } Else { 145 | $error.Clear() 146 | $tcpobject.EndConnect($connect) | out-Null 147 | #If error 148 | If($error[0]){ 149 | #Begin making error more readable in report 150 | [string]$string = ($error[0].exception).message 151 | $message = (($string.split(":")[1]).replace('"',"")).TrimStart() 152 | $failed = $true 153 | } 154 | #Close connection 155 | $tcpobject.Close() 156 | #If unable to query port to due failure 157 | If($failed){ 158 | #Build report 159 | $temp.Server = $c 160 | $temp.Port = $p 161 | $temp.TypePort = "TCP" 162 | $temp.Open = $False 163 | $temp.Notes = "$message" 164 | } Else{ 165 | #Build report 166 | $temp.Server = $c 167 | $temp.Port = $p 168 | $temp.TypePort = "TCP" 169 | $temp.Open = $True 170 | $temp.Notes = "" 171 | } 172 | } 173 | #Reset failed value 174 | $failed = $Null 175 | #Merge temp array with report 176 | $report += $temp 177 | } 178 | If ($udp) { 179 | #Create temporary holder 180 | $temp = "" | Select Server, Port, TypePort, Open, Notes 181 | #Create object for connecting to port on computer 182 | $udpobject = new-Object system.Net.Sockets.Udpclient 183 | #Set a timeout on receiving message 184 | $udpobject.client.ReceiveTimeout = $UDPTimeout 185 | #Connect to remote machine's port 186 | Write-Verbose "Making UDP connection to remote server" 187 | $udpobject.Connect("$c",$p) 188 | #Sends a message to the host to which you have connected. 189 | Write-Verbose "Sending message to remote host" 190 | $a = new-object system.text.asciiencoding 191 | $byte = $a.GetBytes("$(Get-Date)") 192 | [void]$udpobject.Send($byte,$byte.length) 193 | #IPEndPoint object will allow us to read datagrams sent from any source. 194 | Write-Verbose "Creating remote endpoint" 195 | $remoteendpoint = New-Object system.net.ipendpoint([system.net.ipaddress]::Any,0) 196 | Try { 197 | #Blocks until a message returns on this socket from a remote host. 198 | Write-Verbose "Waiting for message return" 199 | $receivebytes = $udpobject.Receive([ref]$remoteendpoint) 200 | [string]$returndata = $a.GetString($receivebytes) 201 | If ($returndata) { 202 | Write-Verbose "Connection Successful" 203 | #Build report 204 | $temp.Server = $c 205 | $temp.Port = $p 206 | $temp.TypePort = "UDP" 207 | $temp.Open = $True 208 | $temp.Notes = $returndata 209 | $udpobject.close() 210 | } 211 | } Catch { 212 | If ($Error[0].ToString() -match "\bRespond after a period of time\b") { 213 | #Close connection 214 | $udpobject.Close() 215 | #Make sure that the host is online and not a false positive that it is open 216 | If (Test-Connection -comp $c -count 1 -quiet) { 217 | Write-Verbose "Connection Open" 218 | #Build report 219 | $temp.Server = $c 220 | $temp.Port = $p 221 | $temp.TypePort = "UDP" 222 | $temp.Open = $True 223 | $temp.Notes = "" 224 | } Else { 225 | <# 226 | It is possible that the host is not online or that the host is online, 227 | but ICMP is blocked by a firewall and this port is actually open. 228 | #> 229 | Write-Verbose "Host maybe unavailable" 230 | #Build report 231 | $temp.Server = $c 232 | $temp.Port = $p 233 | $temp.TypePort = "UDP" 234 | $temp.Open = $False 235 | $temp.Notes = "Unable to verify if port is open or if host is unavailable." 236 | } 237 | } ElseIf ($Error[0].ToString() -match "forcibly closed by the remote host" ) { 238 | #Close connection 239 | $udpobject.Close() 240 | Write-Verbose "Connection Timeout" 241 | #Build report 242 | $temp.Server = $c 243 | $temp.Port = $p 244 | $temp.TypePort = "UDP" 245 | $temp.Open = $False 246 | $temp.Notes = "Connection to Port Timed Out" 247 | } Else { 248 | $udpobject.close() 249 | } 250 | } 251 | #Merge temp array with report 252 | $report += $temp 253 | } 254 | } 255 | } 256 | } 257 | End { 258 | #Generate Report 259 | $report 260 | } 261 | } 262 | 263 | 264 | (Get-Content hosts.txt) | Test-Port -port 80 | Select Server,Port,Open,Notes | ft 265 | -------------------------------------------------------------------------------- /Network/TestServerPortConnectivity.ps1: -------------------------------------------------------------------------------- 1 | 2 | # test server-port reachability 3 | test-netconnection -port 4 | 5 | # test server-port reachability on continuous bases 6 | 7 | while ($true) {test-netconnection -port | Format-Table @{n='Timestamp';e={Get-DAte}},tcptestsucceeded} 8 | -------------------------------------------------------------------------------- /Office-365/Add-DelegationRights--template.csv: -------------------------------------------------------------------------------- 1 | UserEmailAddress;SharedboxName;SendAs;Automapping 2 | john.doe@dom.com;Production;Yes;No 3 | jane.roe@dom.com;Production;No;Yes 4 | -------------------------------------------------------------------------------- /Office-365/Add-DelegationRights.ps1: -------------------------------------------------------------------------------- 1 | # Work in progress for this script, be careful with it! 2 | 3 | Add-Type -AssemblyName System.Windows.Forms 4 | 5 | $PathDesktop = 'C:' + $env:HOMEPATH + '\Desktop' 6 | 7 | function Connect-EXOnline 8 | { 9 | #Define URL to contact Office 365 10 | $Office365URL = "https://ps.outlook.com/powershell" 11 | 12 | #Imports the installed Azure Active Directory module. 13 | Import-Module MSOnline 14 | 15 | #Capture administrative credential for future connections. 16 | $Office365Credentials = Get-Credential -Message "Enter your Office 365 admin credentials" 17 | 18 | #Establishes Online Services connection to Office 365 Management Layer. 19 | Connect-MsolService -Credential $Office365Credentials 20 | 21 | #Creates an Exchange Online session using defined credential. 22 | $EXOSession = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri $Office365URL -Credential $Office365Credentials -Authentication Basic -AllowRedirection -Name "Exchange Online" 23 | 24 | #This imports the Office 365 session into your active Shell. 25 | Import-PSSession $EXOSession 26 | } 27 | 28 | function Disconnect-EXOnline 29 | { 30 | Remove-PSSession -Name "Exchange Online" 31 | } 32 | 33 | function Select-FileDialog 34 | { 35 | [CmdletBinding()] 36 | param ([string]$Title, 37 | [string]$Filter = 'All files *.*|*.*') 38 | Add-Type -AssemblyName System.Windows.Forms | Out-Null 39 | $fileDialogBox = New-Object -TypeName Windows.Forms.OpenFileDialog 40 | $fileDialogBox.ShowHelp = $false 41 | $fileDialogBox.initialDirectory = $PathDesktop 42 | $fileDialogBox.filter = $Filter 43 | $fileDialogBox.Title = $Title 44 | $Show = $fileDialogBox.ShowDialog() 45 | 46 | if ($Show -eq 'OK') 47 | { 48 | Return $fileDialogBox.FileName 49 | } 50 | Else 51 | { 52 | Write-Error -Message 'Opération annulée' 53 | [Windows.Forms.MessageBox]::Show("Le script n'est pas en mesure de continuer. Opération stoppée.", 'Opération stoppée', 0, [Windows.Forms.MessageBoxIcon]::Error) 54 | Stop-TranscriptOnLog 55 | Exit 56 | } 57 | } 58 | 59 | # Disclaimer 60 | $Disclaimer = [Windows.Forms.MessageBox]::Show( 61 | " 62 | Ce script a pour but de déléguer des droits sur une boîte partagée. 63 | Pour cela, il injecte des données venant d'un fichier .csv directement sur Office 365. 64 | 65 | 66 | /!\ Attention /!\ 67 | 68 | Si vous n'êtes pas sûr des actions à mener, ou de l'impact sur la messagerie, quitter ce script dès à présent. 69 | 70 | Souhaitez-vous continuer ? 71 | 72 | 73 | ", 'Boîte partagée', 1, [Windows.Forms.MessageBoxIcon]::Question) 74 | If ($Disclaimer -eq "OK") 75 | { 76 | Write-Information 'Patientez, traitement en cours ...' 77 | } 78 | Else 79 | { 80 | Write-Error -Message 'Opération annulée' 81 | [Windows.Forms.MessageBox]::Show("Le script n'est pas en mesure de continuer. Opération stoppée.", 'Opération stoppée', 0, [Windows.Forms.MessageBoxIcon]::Error) 82 | Stop-TranscriptOnLog 83 | Exit 84 | } 85 | 86 | 87 | 88 | # Start a connection to Office 365 89 | Connect-EXOnline 90 | 91 | # Import CSV file 92 | [Windows.Forms.MessageBox]::Show( 93 | " 94 | Sélectionner dans cette fenêtre le fichier contenant : 95 | - L'adresse e-mail du nom de l'utilisateur à attacher à une boîte partagée 96 | - Le nom de la boîte partagée concernée 97 | - Si la boîte partagée doit s'automonter (mapping) 98 | - Si l'utilisateur a tous les droits sur la boîte partagée 99 | - Si l'utilisateur est en mesure d'envoyer des messages 'de la part de' 100 | 101 | 102 | Le fichier doit être de la forme suivante : 103 | 104 | UserEmailAddress SharedboxName SendAs Automapping 105 | john.doe@dom.com Production Yes No 106 | jane.roe@dom.com Production No Yes 107 | 108 | ", 'Shared mailbox', 0, [Windows.Forms.MessageBoxIcon]::Question) 109 | 110 | # Import list of users and related sharedmailbox and rights 111 | $CSVInputFile = Select-FileDialog -Title 'Select CSV file' -Filter 'Fichier CSV (*.csv) |*.csv' 112 | $csvValues = Import-Csv $CSVInputFile -Delimiter ';' 113 | 114 | # Set parameter for delegation with a loop 115 | foreach ($line in $csvValues) 116 | { 117 | $UserEmailAddress = $line.UserEmailAddress 118 | $SharedboxName = $line.SharedboxName 119 | $SendAs = $line.SendAs 120 | $Automapping = $line.Automapping 121 | switch ($SendAs) { 122 | 'Oui' { $SendAs = 'Yes' } 123 | 'Non' { $SendAs = 'No' } 124 | default { $SendAs = $false } 125 | } 126 | switch ($Automapping) { 127 | 'Oui' { $Automapping = $true } 128 | 'Non' { $Automapping = $false } 129 | default { $Automapping = $true } 130 | } 131 | 132 | Write-Host $UserEmailAddress $SharedboxName $SendAs $Automapping 133 | 134 | #Adding users to the shared mailbox is a two-step process. First, we'll need to give the user access to the mailbox 135 | Add-MailboxPermission -Identity $SharedboxName -AccessRights 'FullAccess' -InheritanceType All -AutoMapping:$Automapping -User $UserEmailAddress 136 | 137 | if ($SendAs -eq 'Yes') 138 | { 139 | #Give the end user permission to send as the account 140 | Add-RecipientPermission -Identity $SharedboxName -AccessRights SendAs -Confirm:$false -Trustee $UserEmailAddress 141 | } 142 | } 143 | 144 | 145 | [Windows.Forms.MessageBox]::Show( 146 | "Action menée avec succès. 147 | ", 'Boîte partagée', 0, [Windows.Forms.MessageBoxIcon]::Information) 148 | 149 | 150 | # Stop the connection to Office 365 151 | Disconnect-EXOnline 152 | -------------------------------------------------------------------------------- /Office-365/Add-LDAPAddressBook/LdapABManager_ABConfiguration.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | CONTOSO LDAP AdressBook 6 | 7 | 8 | contoso.dom 9 | 10 | 11 | 3268 12 | 13 | 14 | False 15 | 16 | 17 | username@contoso.dom 18 | 19 | 20 | password 21 | 22 | 23 | False 24 | 25 | 26 | 60 27 | 28 | 29 | 100 30 | 31 | 32 | True 33 | 34 | 35 | 36 | 37 | 38 | True 39 | 40 | -------------------------------------------------------------------------------- /Office-365/Add-LDAPAddressBook/LdapABManager_x64.exe: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wikijm/PowerShell-AdminScripts/0f52701924d72a72b74f718cf7a4ce45ff27dbca/Office-365/Add-LDAPAddressBook/LdapABManager_x64.exe -------------------------------------------------------------------------------- /Office-365/Add-LDAPAddressBook/LdapABManager_x86.exe: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wikijm/PowerShell-AdminScripts/0f52701924d72a72b74f718cf7a4ce45ff27dbca/Office-365/Add-LDAPAddressBook/LdapABManager_x86.exe -------------------------------------------------------------------------------- /Office-365/Add-LDAPAddressBook/Office-x64.bat: -------------------------------------------------------------------------------- 1 | @echo off 2 | LdapABManager_x86.exe -m create -f LdapABManager_ABConfiguration.xml 3 | -------------------------------------------------------------------------------- /Office-365/Add-LDAPAddressBook/Office-x86.bat: -------------------------------------------------------------------------------- 1 | @echo off 2 | LdapABManager_x86.exe -m create -f LdapABManager_ABConfiguration.xml 3 | -------------------------------------------------------------------------------- /Office-365/Add-UserToSharedMailbox/Add-UserToSharedMailbox.csv: -------------------------------------------------------------------------------- 1 | UserEmailAddress;SharedboxName;SendAs;Automapping 2 | john.doe@dom.com;Production;Yes;No 3 | jane.roe@dom.com;Production;No;Yes 4 | -------------------------------------------------------------------------------- /Office-365/Add-UserToSharedMailbox/Add-UserToSharedMailbox.ps1: -------------------------------------------------------------------------------- 1 | #requires -version 2 2 | <# 3 | .SYNOPSIS 4 | Add writes on shared mailbox to Office 35 users, with or without automapping 5 | 6 | .DESCRIPTION 7 | Add writes on shared mailbox to Office 35 users, with or without automapping 8 | 9 | .INPUTS 10 | .csv file as defined below 11 | 12 | .OUTPUTS 13 | Create transcript log file similar to $ScriptDir\[SCRIPTNAME]_[YYYY_MM_DD]_[HHhMMmSSs].log 14 | Create a list of SUBJECT, similar to $ScriptDir\[SCRIPTNAME]_SUBJECT_[YYYY_MM_DD]_[HHhMMmSSs].csv 15 | 16 | 17 | .NOTES 18 | Version: 0.2 19 | Author: ALBERT Jean-Marc 20 | Creation Date: 14/09/2017 (DD/MM/YYYY) 21 | Purpose/Change: 0.1 - 2017.09.14 - ALBERT Jean-Marc - Initial script development 22 | 0.2 - 2017.09.27 - ALBERT Jean-Marc - Verify if started as admin 23 | 24 | 25 | .SOURCES 26 | 27 | 28 | 29 | .EXAMPLE 30 | 31 | 32 | #> 33 | 34 | #region ---------------------------------------------------------[Initialisations]-------------------------------------------------------- 35 | Set-StrictMode -version Latest 36 | 37 | #Set Error Action to Silently Continue 38 | $ErrorActionPreference = "SilentlyContinue" 39 | 40 | $scriptPath = split-path -parent $MyInvocation.MyCommand.Definition 41 | $scriptFile = $MyInvocation.MyCommand.Definition 42 | $launchDate = get-date -f "yyyy.MM.dd-HHhmmmss" 43 | $logDirectoryPath = $scriptPath + "\" + $launchDate 44 | $buffer = "$scriptPath\bufferCommand.txt" 45 | $fullScriptPath = (Resolve-Path -Path $buffer).Path 46 | 47 | Add-Type -AssemblyName System.Windows.Forms 48 | #endregion 49 | 50 | #region ----------------------------------------------------------[Declarations]---------------------------------------------------------- 51 | 52 | $scriptName = [System.IO.Path]::GetFileName($scriptFile) 53 | $scriptVersion = "0.2" 54 | 55 | if(!(Test-Path $logDirectoryPath)) { 56 | New-Item $logDirectoryPath -type directory | Out-Null 57 | } 58 | 59 | $logFileName = "Log_" + $launchDate + ".log" 60 | $logPathName = "$logDirectoryPath\$logFileName" 61 | 62 | $global:streamWriter = New-Object System.IO.StreamWriter $logPathName 63 | 64 | #endregion 65 | 66 | #region -----------------------------------------------------------[Functions]------------------------------------------------------------ 67 | 68 | Function Test-IsAdmin { 69 | <# 70 | .SYNOPSIS 71 | Function used to detect if current user is an Administrator. 72 | 73 | .DESCRIPTION 74 | Function used to detect if current user is an Administrator. Presents a menu if not an Administrator 75 | 76 | .NOTES 77 | Name: Test-IsAdmin 78 | Author: Boe Prox 79 | DateCreated: 30April2011 80 | 81 | .EXAMPLE 82 | Test-IsAdmin 83 | 84 | 85 | Description 86 | ----------- 87 | Command will check the current user to see if an Administrator. If not, a menu is presented to the user to either 88 | continue as the current user context or enter alternate credentials to use. If alternate credentials are used, then 89 | the [System.Management.Automation.PSCredential] object is returned by the function. 90 | #> 91 | [cmdletbinding()] 92 | Param() 93 | 94 | Write-Verbose "Checking to see if current user context is Administrator" 95 | If (-NOT ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")) 96 | { 97 | Write-Warning "You are not currently running this under an Administrator account! `nThere is potential that this command could fail if not running under an Administrator account." 98 | Write-Verbose "Presenting option for user to pick whether to continue as current user or use alternate credentials" 99 | #Determine Values for Choice 100 | $choice = [System.Management.Automation.Host.ChoiceDescription[]] @("Use &Alternate Credentials","&Continue with current Credentials") 101 | 102 | #Determine Default Selection 103 | [int]$default = 0 104 | 105 | #Present choice option to user 106 | $userchoice = $host.ui.PromptforChoice("Warning","Please select to use Alternate Credentials or current credentials to run command",$choice,$default) 107 | 108 | Write-Debug "Selection: $userchoice" 109 | 110 | #Determine action to take 111 | Switch ($Userchoice) 112 | { 113 | 0 114 | { 115 | #Prompt for alternate credentials 116 | Write-Verbose "Prompting for Alternate Credentials" 117 | $Credential = Get-Credential 118 | Write-Output $Credential 119 | } 120 | 1 121 | { 122 | #Continue using current credentials 123 | Write-Verbose "Using current credentials" 124 | Write-Output "CurrentUser" 125 | } 126 | } 127 | 128 | } 129 | Else 130 | { 131 | Write-Verbose "Passed Administrator check" 132 | } 133 | } 134 | 135 | Function Hide-PowershellConsole() { 136 | # Hide the powershell console window without hiding the other child windows that it spawns. (I.E. hide the powershell window, but not the Out-Gridview window) 137 | # https://community.spiceworks.com/topic/1710213-hide-a-powershell-console-window-when-running-a-script 138 | $Script:showWindowAsync = Add-Type -MemberDefinition @" 139 | [DllImport("user32.dll")] 140 | public static extern bool ShowWindowAsync(IntPtr hWnd, int nCmdShow); 141 | "@ -Name "Win32ShowWindowAsync" -Namespace Win32Functions -PassThru 142 | 143 | $null = $showWindowAsync::ShowWindowAsync((Get-Process -Id $pid).MainWindowHandle, 2) 144 | } 145 | 146 | Function Start-Log { 147 | [CmdletBinding()] 148 | Param ([Parameter(Mandatory=$true)][string]$scriptName, [Parameter(Mandatory=$true)][string]$scriptVersion, 149 | [Parameter(Mandatory=$true)][string]$streamWriter) 150 | Process{ 151 | $global:streamWriter.WriteLine("================================================================================================") 152 | $global:streamWriter.WriteLine("[$ScriptName] version [$ScriptVersion] started at $([DateTime]::Now)") 153 | $global:streamWriter.WriteLine("================================================================================================`n") 154 | } 155 | } 156 | 157 | Function Write-Log { 158 | [CmdletBinding()] 159 | Param ([Parameter(Mandatory=$true)][string]$streamWriter, [Parameter(Mandatory=$true)][string]$infoToLog) 160 | Process{ 161 | $InfoMessage = "$([DateTime]::Now) [INFO] $infoToLog" 162 | $global:streamWriter.WriteLine($InfoMessage) 163 | Write-Host $InfoMessage -ForegroundColor Cyan 164 | } 165 | } 166 | 167 | Function Write-Error { 168 | [CmdletBinding()] 169 | Param ([Parameter(Mandatory=$true)][string]$streamWriter, [Parameter(Mandatory=$true)][string]$errorCaught, [Parameter(Mandatory=$true)][boolean]$forceExit) 170 | Process{ 171 | $ErrorMessage = "$([DateTime]::Now) [ERROR] $errorCaught" 172 | $global:streamWriter.WriteLine($ErrorMessage) 173 | Write-Host $ErrorMessage -ForegroundColor Red 174 | if ($forceExit -eq $true){ 175 | End-Log -streamWriter $global:streamWriter 176 | break; 177 | } 178 | } 179 | } 180 | 181 | Function End-Log { 182 | [CmdletBinding()] 183 | Param ([Parameter(Mandatory=$true)][string]$streamWriter) 184 | Process{ 185 | $global:streamWriter.WriteLine("`n================================================================================================") 186 | $global:streamWriter.WriteLine("Script ended at $([DateTime]::Now)") 187 | $global:streamWriter.WriteLine("================================================================================================") 188 | 189 | $global:streamWriter.Close() 190 | } 191 | } 192 | 193 | Function Invoke-Office365TenantLogon { 194 | #### Pop-up a dialog for username and request your password 195 | $cred = Get-Credential 196 | #### Import the Local Microsoft Online PowerShell Module Cmdlets and Connect to O365 Online 197 | Import-Module MSOnline 198 | Connect-MsolService -Credential $cred 199 | #### Establish an Remote PowerShell Session to Exchange Online 200 | $msoExchangeURL = “https://ps.outlook.com/powershell/” 201 | $sessionOption = New-PSSessionOption -SkipRevocationCheck #Avoid Certificate error (https://support.microsoft.com/fr-fr/help/2792168/-ssl-certificate-could-not-be-checked-for-revocation-error-when-you-co) 202 | $session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri $msoExchangeURL -Credential $cred -Authentication Basic -AllowRedirection -SessionOption $sessionOption 203 | 204 | if (!$session) { 205 | Write-Error -Message 'Opération annulée' 206 | [Windows.Forms.MessageBox]::Show("Le script n'est pas en mesure de continuer, sans doute à cause de mauvaises informations d'identification. Opération stoppée.", 'Opération stoppée', 0, [Windows.Forms.MessageBoxIcon]::Error) 207 | Stop-TranscriptOnLog 208 | Exit 209 | } 210 | Else { 211 | Import-PSSession $session -AllowClobber 212 | } 213 | 214 | } 215 | 216 | Function Invoke-Office365TenantLogoff { 217 | #### Remove the Remote PowerShell Session to Exchange Online ---- 218 | Get-PsSession | Remove-PsSession 219 | #Remove-PsSession $session 220 | } 221 | 222 | Function Select-FileDialog { 223 | [CmdletBinding()] 224 | param ([string]$Title, 225 | [string]$Filter = 'All files *.*|*.*') 226 | Add-Type -AssemblyName System.Windows.Forms | Out-Null 227 | $fileDialogBox = New-Object -TypeName Windows.Forms.OpenFileDialog 228 | $fileDialogBox.ShowHelp = $false 229 | $fileDialogBox.initialDirectory = $scriptPath 230 | $fileDialogBox.filter = $Filter 231 | $fileDialogBox.Title = $Title 232 | $Show = $fileDialogBox.ShowDialog() 233 | 234 | if ($Show -eq 'OK') 235 | { 236 | Return $fileDialogBox.FileName 237 | } 238 | Else 239 | { 240 | Write-Error -Message 'Opération annulée' 241 | [Windows.Forms.MessageBox]::Show("Le script n'est pas en mesure de continuer. Opération stoppée.", 'Opération stoppée', 0, [Windows.Forms.MessageBoxIcon]::Error) 242 | Stop-TranscriptOnLog 243 | Exit 244 | } 245 | } 246 | 247 | Function Stop-Script () { 248 | Begin{ 249 | Write-Log -streamWriter $global:streamWriter -infoToLog '--- Script terminating ---' 250 | } 251 | Process{ 252 | 'Script terminating...' 253 | Write-Verbose -Message '================================================================================================' 254 | End-Log -streamWriter $global:streamWriter 255 | Exit 256 | } 257 | } 258 | #endregion 259 | 260 | #region ----------------------------------------------------------[Execution]---------------------------------------------------------- 261 | 262 | # Check if Admin 263 | $admincheck = Test-IsAdmin 264 | If ($admincheck -is [System.Management.Automation.PSCredential]) { 265 | Write-Error -Message 'Opération annulée' 266 | Start-Process -FilePath PowerShell.exe -Credential $admincheck -ArgumentList $myinvocation.mycommand.definition 267 | Break 268 | } 269 | 270 | # Start log creation and completion 271 | Start-Log -scriptName $scriptName -scriptVersion $scriptVersion -streamWriter $global:streamWriter 272 | 273 | # Disclaimer 274 | $Disclaimer = [Windows.Forms.MessageBox]::Show( 275 | " 276 | Ce script a pour but de déléguer des droits sur une boîte partagée. 277 | Pour cela, il injecte des données venant d'un fichier .csv directement sur Office 365. 278 | 279 | 280 | /!\ Attention /!\ 281 | 282 | Si vous n'êtes pas sûr des actions à mener, ou de l'impact sur la messagerie, quitter ce script dès à présent. 283 | 284 | Souhaitez-vous continuer ? 285 | 286 | 287 | ", 'Boîte partagée', 1, [Windows.Forms.MessageBoxIcon]::Question) 288 | If ($Disclaimer -eq "OK") 289 | { 290 | Write-Information 'Patientez, traitement en cours ...' 291 | } 292 | Else 293 | { 294 | Write-Error -Message 'Opération annulée' 295 | [Windows.Forms.MessageBox]::Show("Le script n'est pas en mesure de continuer. Opération stoppée.", 'Opération stoppée', 0, [Windows.Forms.MessageBoxIcon]::Error) 296 | Stop-TranscriptOnLog 297 | Exit 298 | } 299 | 300 | # Start a connection to Office 365 301 | Invoke-Office365TenantLogon 302 | 303 | # Import CSV file 304 | [Windows.Forms.MessageBox]::Show( 305 | " 306 | Sélectionner dans cette fenêtre le fichier contenant : 307 | - L'adresse e-mail du nom de l'utilisateur à attacher à une boîte partagée 308 | - Le nom de la boîte partagée concernée 309 | - Si la boîte partagée doit s'automonter (mapping) 310 | 311 | Le fichier doit être de la forme suivante : 312 | 313 | UserEmailAddress SharedboxName SendAs Automapping 314 | john.doe@dom.com Production Yes No 315 | jane.roe@dom.com Production No Yes 316 | 317 | ", 'Shared mailbox', 0, [Windows.Forms.MessageBoxIcon]::Question) 318 | 319 | # Import list of users and related sharedmailbox and rights 320 | $CSVInputFile = Select-FileDialog -Title 'Select CSV file' -Filter 'Fichier CSV (*.csv) |*.csv' 321 | $csvValues = Import-Csv $CSVInputFile -Delimiter ';' 322 | Write-Log -streamWriter $global:streamWriter -infoToLog Fichier source sélectionné : $CSVInputFile 323 | 324 | # Set parameter for delegation with a loop 325 | foreach ($line in $csvValues) 326 | { 327 | $UserEmailAddress = $line.UserEmailAddress 328 | $SharedboxName = $line.SharedboxName 329 | $SendAs = $line.SendAs 330 | $Automapping = $line.Automapping 331 | switch ($SendAs) 332 | { 333 | 'Oui' { $SendAs = 'Yes' } 334 | 'Non' { $SendAs = 'No' } 335 | default { $SendAs = $false } 336 | } 337 | switch ($Automapping) 338 | { 339 | 'Oui' { $Automapping = $true } 340 | 'Non' { $Automapping = $false } 341 | default { $Automapping = $true } 342 | } 343 | 344 | Write-Host $UserEmailAddress $SharedboxName $SendAs $Automapping 345 | Write-Log -streamWriter $global:streamWriter -infoToLog $UserEmailAddress $SharedboxName $SendAs $Automapping 346 | 347 | #Adding users to the shared mailbox is a two-step process. First, we'll need to give the user access to the mailbox 348 | Add-MailboxPermission -Identity $SharedboxName -AccessRights 'FullAccess' -InheritanceType All -AutoMapping:$Automapping -User $UserEmailAddress 349 | 350 | if ($SendAs -eq 'Yes') 351 | { 352 | #Give the end user permission to send as the account 353 | Add-RecipientPermission -Identity $SharedboxName -AccessRights SendAs -Confirm:$false -Trustee $UserEmailAddress 354 | } 355 | } 356 | 357 | 358 | # Success message 359 | [Windows.Forms.MessageBox]::Show( 360 | "Action menée avec succès. 361 | ", 'Boîte partagée', 0, [Windows.Forms.MessageBoxIcon]::Information) 362 | Write-Log -streamWriter $global:streamWriter -infoToLog 'Action menée avec succès.' 363 | 364 | 365 | # Stop the connection to Office 365 366 | Invoke-Office365TenantLogoff 367 | Write-Log -streamWriter $global:streamWriter -infoToLog "Déconnexion de l'instance Office 365 Tenant" 368 | 369 | Stop-Script 370 | #endregion 371 | -------------------------------------------------------------------------------- /Office-365/Check-Office2016Activation.ps1: -------------------------------------------------------------------------------- 1 | $launchdate = Get-Date -f "yyyy.MM.dd-HHhmmmss" 2 | $Office2016FolderPath = 'C:\Program Files\Microsoft Office\Office16' 3 | $CookieFile = 'C:\Users\' + $env:username + '\AppData\Local\Microsoft\Office\16.0\office365ForBusiness.txt' 4 | $Office365LicenceStatusResult = 'C:\' + $env:HOMEPATH + '\office365forbusinessactstat.txt' 5 | 6 | 7 | function Check-Office365ForBusinessActivation () { 8 | C:\Windows\System32\cscript.exe 'C:\Program Files\Microsoft Office\Office16\OSPP.VBS' /dstatus | Out-File -Force $Office365LicenceStatusResult 9 | $ActivationStatus = $(get-content $Office365LicenceStatusResult -ReadCount 24 | foreach { $_ -match "LICENSE STATUS" }) 10 | 11 | $Var = "Office Activated " 12 | if ($ActivationStatus -match "LICENSE STATUS: ---LICENSED--- ") { 13 | $Var = $Var + "OK " 14 | } 15 | 16 | else { 17 | $Var = $Var + "Bad " 18 | } 19 | 20 | if ($Var -like "*Bad*") { 21 | echo "Office Not Activated" 22 | Add-Type -AssemblyName System.Windows.Forms 23 | [System.Windows.Forms.MessageBox]::Show("La mise à jour de la suite Office vient d'être effectuée. 24 | Afin de l'activer, merci de suivre la procédure PDF qui s'ouvrira lorsque vous cliquerez sur le bouton 'OK'.", 25 | "Office 2016 - Activation", 26 | 0, 27 | [Windows.Forms.MessageBoxIcon]::Warning) 28 | 29 | Start-Process 'X:\SomewhereOverTheRainbow\1stLaunch.pdf' -WindowStyle Maximized -Verb Open 30 | } 31 | else 32 | { 33 | echo "Office Activated" 34 | New-Item $CookieFile -ItemType File 35 | Set-Content -Value $launchdate -Path $CookieFile 36 | } 37 | } 38 | 39 | if(!(Test-Path $CookieFile)) { 40 | Check-Office365ForBusinessActivation 41 | } 42 | -------------------------------------------------------------------------------- /Office-365/Get-CopyOnSharedboxForSendAsAndSendOnBehalfMessage.ps1: -------------------------------------------------------------------------------- 1 | #Goal: 2 | # Make a copy on sharedmailbox 'Sent' folder for messages that are sent by using the "Send As" 3 | # and "Send on behalf" permissions are copied only to the Sent Items folder of the sender 4 | # in an Exchange Server 2010 and next/Office 365 environment 5 | #Source: 6 | # https://support.microsoft.com/fr-fr/kb/2632409 7 | 8 | function Invoke-Office365TenantLogon { 9 | #### Pop-up a dialog for username and request your password 10 | $cred = Get-Credential 11 | #### Import the Local Microsoft Online PowerShell Module Cmdlets and Connect to O365 Online 12 | Import-Module MSOnline 13 | Connect-MsolService -Credential $cred 14 | #### Establish an Remote PowerShell Session to Exchange Online 15 | $msoExchangeURL = “https://ps.outlook.com/powershell/” 16 | $session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri $msoExchangeURL -Credential $cred -Authentication Basic -AllowRedirection 17 | Import-PSSession $session -AllowClobber 18 | } 19 | 20 | function Invoke-Office365TenantLogoff { 21 | #### Remove the Remote PowerShell Session to Exchange Online ---- 22 | Get-PsSession | Remove-PsSession 23 | #Remove-PsSession $session 24 | } 25 | 26 | function Active-MessageCopyForSendItemsOnSharedMailbox { 27 | #List SharedMailbox and show MessageCopyForSentAsEnabled and MessageCopyForSendOnBehalfEnabled status 28 | $SharedMailboxList = Get-Mailbox | Where-Object {($_.RecipientTypeDetails) -eq 'SharedMailbox'} 29 | 30 | #Active MessageCopyForSentAsEnabled and MessageCopyForSendOnBehalfEnabled for all SharedMailbox with this parameter defined as 'False' 31 | $SharedMailboxList <#| Where-Object {($_.MessageCopyForSentAsEnabled) -eq 'False'}#> | Set-Mailbox -MessageCopyForSentAsEnabled $True 32 | $SharedMailboxList <#| Where-Object {($_.MessageCopyForSendOnBehalfEnabled) -eq 'False'}#> | Set-Mailbox -MessageCopyForSendOnBehalfEnabled $True 33 | } 34 | 35 | 36 | #Connect to Office 365 Tenant 37 | Invoke-Office365TenantLogon 38 | 39 | #Set MessageCopyForSentAsEnabled and MessageCopyForSendOnBehalfEnabled to $True 40 | Active-MessageCopyForSendItemsOnSharedMailbox 41 | 42 | #Disconnect to Office 365 Tenant 43 | Invoke-Office365TenantLogoff 44 | -------------------------------------------------------------------------------- /Office-365/Get-MailboxUsage.ps1: -------------------------------------------------------------------------------- 1 | $ExportPathName = 'C:\temp\office365-spaceusage.csv' 2 | 3 | function Invoke-Office365TenantLogon { 4 | #### Pop-up a dialog for username and request your password 5 | $cred = Get-Credential 6 | #### Import the Local Microsoft Online PowerShell Module Cmdlets and Connect to O365 Online 7 | Import-Module MSOnline 8 | Connect-MsolService -Credential $cred 9 | #### Establish an Remote PowerShell Session to Exchange Online 10 | $msoExchangeURL = “https://ps.outlook.com/powershell/” 11 | $session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri $msoExchangeURL -Credential $cred -Authentication Basic -AllowRedirection 12 | Import-PSSession $session -AllowClobber 13 | } 14 | 15 | function Invoke-Office365TenantLogoff { 16 | #### Remove the Remote PowerShell Session to Exchange Online ---- 17 | Get-PsSession | Remove-PsSession 18 | #Remove-PsSession $session 19 | } 20 | 21 | 22 | #Connect to Office 365 Tenant 23 | Invoke-Office365TenantLogon 24 | 25 | #List all mail accounts 26 | Get-Mailbox -ResultSize Unlimited | 27 | Get-MailboxStatistics | 28 | Select DisplayName, ` 29 | 30 | @{name="TotalItemSize (MB)"; expression={[math]::Round( ` 31 | ($_.TotalItemSize.ToString().Split("(")[1].Split(" ")[0].Replace(",","")/1MB),2)}}, ` 32 | ItemCount | 33 | Sort "TotalItemSize (MB)" -Descending | 34 | Export-CSV -Path $ExportPathName -Encoding UTF8 -NoType -Force 35 | 36 | #Disconnect to Office 365 Tenant 37 | Invoke-Office365TenantLogoff 38 | -------------------------------------------------------------------------------- /Office-365/Set-DefaultUserAsRoomsCalenderReviewer.ps1: -------------------------------------------------------------------------------- 1 | #requires -version 2 2 | <# 3 | .SYNOPSIS 4 | 5 | 6 | .DESCRIPTION 7 | 8 | 9 | .INPUTS 10 | 11 | 12 | .OUTPUTS 13 | Create transcript log file similar to $ScriptDir\[SCRIPTNAME]_[YYYY_MM_DD]_[HHhMMmSSs].log 14 | Create a list of SUBJECT, similar to $ScriptDir\[SCRIPTNAME]_SUBJECT_[YYYY_MM_DD]_[HHhMMmSSs].csv 15 | 16 | 17 | .NOTES 18 | Version: 1.2 19 | Author: ALBERT Jean-Marc 20 | Creation Date: 10/01/2017 (DD/MM/YYYY) 21 | Current Date: 14/02/2017 (DD/MM/YYYY) 22 | Purpose/Change: 1.0 - 2017.01.10 - ALBERT Jean-Marc - Initial script development 23 | 1.1 - 2017.01.10 - ALBERT Jean-Marc - Redesign script with PowerShell-ScriptTemplate.ps1 24 | 1.2 - 2017.02.14 - ALBERT Jean-Marc - Add "current date" and "region" 25 | 26 | 27 | 28 | .SOURCES 29 | 30 | 31 | 32 | .EXAMPLE 33 | 34 | 35 | #> 36 | 37 | #region ---------------------------------------------------------[Initialisations]-------------------------------------------------------- 38 | Set-StrictMode -version Latest 39 | 40 | #Set Error Action to Silently Continue 41 | $ErrorActionPreference = "SilentlyContinue" 42 | $scriptPath = split-path -parent $MyInvocation.MyCommand.Definition 43 | $scriptFile = $MyInvocation.MyCommand.Definition 44 | $launchDate = get-date -f "yyyy.MM.dd-HHhmmmss" 45 | $logDirectoryPath = $scriptPath + "\" + $launchDate 46 | #endregion 47 | 48 | #region ----------------------------------------------------------[Declarations]---------------------------------------------------------- 49 | $scriptName = [System.IO.Path]::GetFileName($scriptFile) 50 | $scriptVersion = "1.2" 51 | 52 | if(!(Test-Path $logDirectoryPath)) { 53 | New-Item $logDirectoryPath -type directory | Out-Null 54 | } 55 | 56 | $logFileName = "Log_" + $launchDate + ".log" 57 | $logPathName = "$logDirectoryPath\$logFileName" 58 | 59 | $global:streamWriter = New-Object System.IO.StreamWriter $logPathName 60 | #endregion 61 | 62 | #region -----------------------------------------------------------[functions]------------------------------------------------------------ 63 | function Start-Log { 64 | [CmdletBinding()] 65 | Param ([Parameter(Mandatory=$true)][string]$scriptName, [Parameter(Mandatory=$true)][string]$scriptVersion, 66 | [Parameter(Mandatory=$true)][string]$streamWriter) 67 | Process{ 68 | $global:streamWriter.WriteLine("================================================================================================") 69 | $global:streamWriter.WriteLine("[$ScriptName] version [$ScriptVersion] started at $([DateTime]::Now)") 70 | $global:streamWriter.WriteLine("================================================================================================`n") 71 | } 72 | } 73 | 74 | function Write-Log { 75 | [CmdletBinding()] 76 | Param ([Parameter(Mandatory=$true)][string]$streamWriter, [Parameter(Mandatory=$true)][string]$infoToLog) 77 | Process{ 78 | $InfoMessage = "$([DateTime]::Now) [INFO] $infoToLog" 79 | $global:streamWriter.WriteLine($InfoMessage) 80 | Write-Host $InfoMessage -ForegroundColor Cyan 81 | } 82 | } 83 | 84 | function Write-Error { 85 | [CmdletBinding()] 86 | Param ([Parameter(Mandatory=$true)][string]$streamWriter, [Parameter(Mandatory=$true)][string]$errorCaught, [Parameter(Mandatory=$true)][boolean]$forceExit) 87 | Process{ 88 | $ErrorMessage = "$([DateTime]::Now) [ERROR] $errorCaught" 89 | $global:streamWriter.WriteLine($ErrorMessage) 90 | Write-Host $ErrorMessage -ForegroundColor Red 91 | if ($forceExit -eq $true){ 92 | End-Log -streamWriter $global:streamWriter 93 | break; 94 | } 95 | } 96 | } 97 | 98 | function End-Log { 99 | [CmdletBinding()] 100 | Param ([Parameter(Mandatory=$true)][string]$streamWriter) 101 | Process{ 102 | $global:streamWriter.WriteLine("`n================================================================================================") 103 | $global:streamWriter.WriteLine("Script ended at $([DateTime]::Now)") 104 | $global:streamWriter.WriteLine("================================================================================================") 105 | 106 | $global:streamWriter.Close() 107 | } 108 | } 109 | 110 | function Connect-EXOnline { 111 | #Define URL to contact Office 365 112 | $Office365URL = "https://ps.outlook.com/powershell" 113 | 114 | #Imports the installed Azure Active Directory module. 115 | Import-Module MSOnline 116 | 117 | #Capture administrative credential for future connections. 118 | $Office365Credentials = Get-Credential -Message "Enter your Office 365 admin credentials" 119 | 120 | #Establishes Online Services connection to Office 365 Management Layer. 121 | Connect-MsolService -Credential $Office365Credentials 122 | 123 | #Creates an Exchange Online session using defined credential. 124 | $EXOSession = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri $Office365URL -Credential $Office365Credentials -Authentication Basic -AllowRedirection -Name "Exchange Online" 125 | 126 | #This imports the Office 365 session into your active Shell. 127 | Import-PSSession $EXOSession 128 | } 129 | 130 | function Disconnect-EXOnline { 131 | Remove-PSSession -Name "Exchange Online" 132 | } 133 | #endregion 134 | 135 | #region ----------------------------------------------------------[Execution]---------------------------------------------------------- 136 | Start-Log -scriptName $scriptName -scriptVersion $scriptVersion -streamWriter $global:streamWriter 137 | cls 138 | Write-Host "================================================================================================" 139 | Write-Host "[$ScriptName] version [$ScriptVersion] started at $([DateTime]::Now)" 140 | Write-Host "================================================================================================" 141 | 142 | # Disclaimer 143 | $Disclaimer = [Windows.Forms.MessageBox]::Show( 144 | " 145 | Ce script permet à tous les utilisateurs Exchange/Office 365 de devenir relecteur sur les calendriers de salle de réunion et équipements. 146 | 147 | /!\ Attention /!\ 148 | Si vous n'êtes pas sûr des actions à mener ou de l'impact, quitter ce script dès à présent. 149 | 150 | Souhaitez-vous continuer ? 151 | 152 | ", 'Modification de droits sur les calendriers de salle et équipement', 1, [Windows.Forms.MessageBoxIcon]::Question) 153 | If ($Disclaimer -eq "OK") 154 | { 155 | Write-Information 'Patientez, traitement en cours ...' 156 | } 157 | Else 158 | { 159 | Write-Error -Message 'Opération annulée' 160 | [Windows.Forms.MessageBox]::Show("Le script n'est pas en mesure de continuer. Opération stoppée.", 'Opération stoppée', 0, [Windows.Forms.MessageBoxIcon]::Error) 161 | Stop-TranscriptOnLog 162 | Exit 163 | } 164 | 165 | 166 | # Start a connection to Office 365 167 | Connect-EXOnline 168 | 169 | # List all RoomMailbox and set Exchange/Office 365 users as calendar reviewer 170 | $rooms = Get-Mailbox -RecipientTypeDetails RoomMailbox 171 | $rooms | ForEach-Object {Write-Log -streamWriter $global:streamWriter -infoToLog "Room: $_"} 172 | $rooms | %{Set-MailboxFolderPermission $_":\Calendrier" -User Default -AccessRights Reviewer} | ForEach-Object {Write-Log -streamWriter $global:streamWriter -infoToLog $_} #Replace :\Calendrier with :\Calendar for English context 173 | 174 | # List all EquipmentMailbox and set Exchange/Office 365 users as calendar reviewer 175 | $equipments = Get-Mailbox -RecipientTypeDetails EquipmentMailbox 176 | $equipments | ForEach-Object {Write-Log -streamWriter $global:streamWriter -infoToLog "Equipment: $_"} 177 | $equipments | %{Set-MailboxFolderPermission $_":\Calendrier" -User Default -AccessRights Reviewer} | ForEach-Object {Write-Log -streamWriter $global:streamWriter -infoToLog $_} #Replace :\Calendrier with :\Calendar for English context 178 | 179 | Write-Log -streamWriter $global:streamWriter -infoToLog $rooms 180 | 181 | [Windows.Forms.MessageBox]::Show( 182 | "Action menée avec succès. 183 | ", 'Modification de droits sur les calendriers de salle et équipement', 0, [Windows.Forms.MessageBoxIcon]::Information) 184 | 185 | 186 | # Stop the connection to Office 365 187 | Disconnect-EXOnline 188 | 189 | 190 | #Writing informations in the log file 191 | Write-Progress -Activity "Write informations in the log file" -status "Running..." -id 1 192 | End-Log -streamWriter $global:streamWriter 193 | notepad $logPathName 194 | cls 195 | #endregion 196 | -------------------------------------------------------------------------------- /Office-365/Set-Office365Signature.ps1: -------------------------------------------------------------------------------- 1 | $SigFile = "SigTemplate.htm" 2 | $temp = Get-Content -Path $Sigfile -ReadCount 0 3 | 4 | #Connect to Office 365 Tenant 5 | $Cred = Get-Credential 6 | $Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://ps.outlook.com/powershell/ -Credential $Cred -Authentication Basic –AllowRedirection 7 | Import-PSSession $Session 8 | 9 | #Import the active directory module which is needed for Get-ADUser 10 | Import-Module ActiveDirectory 11 | 12 | #Import active AD users with defined e-mail address 13 | $users = Get-ADUser -filter * -Properties * | Where-Object {($_.Enabled) -eq "True" -AND ($_.EmailAddress -ne $null)} 14 | 15 | #Add signature template to all selected AD users, and active AutoAddSignature on new e-mail 16 | foreach ($user in $users) { 17 | $Office365ID = $user.EmailAddress.Split("@")[0] 18 | Set-MailboxMessageConfiguration -identity $Office365ID -SignatureHtml $temp -AutoAddSignature $True 19 | } 20 | -------------------------------------------------------------------------------- /Office-365/Update-UPNandLicence.ps1: -------------------------------------------------------------------------------- 1 | #requires -version 2 2 | <# 3 | .SYNOPSIS 4 | 5 | 6 | .DESCRIPTION 7 | 8 | 9 | .INPUTS 10 | 11 | 12 | .OUTPUTS 13 | Create transcript log file similar to $ScriptDir\[SCRIPTNAME]_[YYYY_MM_DD]_[HHhMMmSSs].log 14 | Create a list of SUBJECT, similar to $ScriptDir\[SCRIPTNAME]_SUBJECT_[YYYY_MM_DD]_[HHhMMmSSs].csv 15 | 16 | 17 | .NOTES 18 | Version: 0.1 19 | Author: ALBERT Jean-Marc 20 | Creation Date: 08/02/2017 (DD/MM/YYYY) 21 | Purpose/Change: 1.0 - 2017.02.08 - ALBERT Jean-Marc - Initial script development 22 | 23 | 24 | .SOURCES 25 | 26 | 27 | 28 | .EXAMPLE 29 | 30 | 31 | #> 32 | 33 | 34 | #region ---------------------------------------------------------[Initialisations]-------------------------------------------------------- 35 | Set-StrictMode -version Latest 36 | 37 | #Set Error Action to Silently Continue 38 | $ErrorActionPreference = "SilentlyContinue" 39 | 40 | $scriptPath = split-path -parent $MyInvocation.MyCommand.Definition 41 | $scriptFile = $MyInvocation.MyCommand.Definition 42 | $launchDate = get-date -f "yyyy.MM.dd-HHhmmmss" 43 | $logDirectoryPath = $scriptPath + "\" + $launchDate 44 | $buffer = "$scriptPath\bufferCommand.txt" 45 | $fullScriptPath = (Resolve-Path -Path $buffer).Path 46 | #endregion 47 | 48 | #region ----------------------------------------------------------[Declarations]---------------------------------------------------------- 49 | $scriptName = [System.IO.Path]::GetFileName($scriptFile) 50 | $scriptVersion = "0.1" 51 | 52 | if(!(Test-Path $logDirectoryPath)) { 53 | New-Item $logDirectoryPath -type directory | Out-Null 54 | } 55 | 56 | $logFileName = "Log_" + $launchDate + ".log" 57 | $logPathName = "$logDirectoryPath\$logFileName" 58 | $global:streamWriter = New-Object System.IO.StreamWriter $logPathName 59 | #endregion 60 | 61 | #region -----------------------------------------------------------[Functions]------------------------------------------------------------ 62 | 63 | Function Start-Log { 64 | [CmdletBinding()] 65 | Param ([Parameter(Mandatory=$true)][string]$scriptName, [Parameter(Mandatory=$true)][string]$scriptVersion, 66 | [Parameter(Mandatory=$true)][string]$streamWriter) 67 | Process{ 68 | $global:streamWriter.WriteLine("================================================================================================") 69 | $global:streamWriter.WriteLine("[$ScriptName] version [$ScriptVersion] started at $([DateTime]::Now)") 70 | $global:streamWriter.WriteLine("================================================================================================`n") 71 | } 72 | } 73 | 74 | Function Write-Log { 75 | [CmdletBinding()] 76 | Param ([Parameter(Mandatory=$true)][string]$streamWriter, [Parameter(Mandatory=$true)][string]$infoToLog) 77 | Process{ 78 | $InfoMessage = "$([DateTime]::Now) [INFO] $infoToLog" 79 | $global:streamWriter.WriteLine($InfoMessage) 80 | Write-Host $InfoMessage -ForegroundColor Cyan 81 | } 82 | } 83 | 84 | Function Write-Error { 85 | [CmdletBinding()] 86 | Param ([Parameter(Mandatory=$true)][string]$streamWriter, [Parameter(Mandatory=$true)][string]$errorCaught, [Parameter(Mandatory=$true)][boolean]$forceExit) 87 | Process{ 88 | $ErrorMessage = "$([DateTime]::Now) [ERROR] $errorCaught" 89 | $global:streamWriter.WriteLine($ErrorMessage) 90 | Write-Host $ErrorMessage -ForegroundColor Red 91 | if ($forceExit -eq $true){ 92 | End-Log -streamWriter $global:streamWriter 93 | break; 94 | } 95 | } 96 | } 97 | 98 | Function End-Log { 99 | [CmdletBinding()] 100 | Param ([Parameter(Mandatory=$true)][string]$streamWriter) 101 | Process{ 102 | $global:streamWriter.WriteLine("`n================================================================================================") 103 | $global:streamWriter.WriteLine("Script ended at $([DateTime]::Now)") 104 | $global:streamWriter.WriteLine("================================================================================================") 105 | 106 | $global:streamWriter.Close() 107 | } 108 | } 109 | 110 | Function Select-FileDialog { 111 | param([string]$Title,[string]$Filter="All files *.*|*.*") 112 | [System.Reflection.Assembly]::LoadWithPartialName( 'System.Windows.Forms' ) | Out-Null 113 | $fileDialogBox = New-Object Windows.Forms.OpenFileDialog 114 | $fileDialogBox.ShowHelp = $false 115 | $fileDialogBox.initialDirectory = $ScriptDir 116 | $fileDialogBox.filter = $Filter 117 | $fileDialogBox.Title = $Title 118 | $Show = $fileDialogBox.ShowDialog( ) 119 | 120 | If ($Show -eq "OK") 121 | { 122 | Return $fileDialogBox.FileName 123 | } 124 | Else 125 | { 126 | Write-Error "Canceled operation" 127 | [System.Windows.Forms.MessageBox]::Show("Script is not able to continue. Operation stopped." , "Operation canceled" , 0, [Windows.Forms.MessageBoxIcon]::Error) 128 | Stop-TranscriptOnLog 129 | Exit 130 | } 131 | } 132 | 133 | Function Connect-Office365_PSSession { 134 | <# 135 | .SYNOPSIS 136 | Connect to Office 365 Cloud Services into active PowerShell shell 137 | 138 | .PARAMETER Office365_URL 139 | URL to Office 365 Cloud Services for PowerShell 140 | 141 | .PARAMETER Office365_Credentials 142 | Capture administrative credential for future connections 143 | 144 | #> 145 | [CmdletBinding()] 146 | param 147 | ( 148 | [string]$Office365_URL = "https://ps.outlook.com/powershell", 149 | $Office365_Credentials 150 | ) 151 | 152 | #Imports the installed Azure Active Directory module. 153 | Import-Module MSOnline 154 | 155 | #Capture administrative credential for future connections. 156 | $Office365_Credentials = Get-Credential -Message "Enter your Office 365 admin credentials" 157 | 158 | #Establishes Online Services connection to Office 365 Management Layer. 159 | Connect-MsolService -Credential $Office365_Credentials 160 | 161 | #Creates an Exchange Online session using defined credential. 162 | $EXOSession = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri $Office365_URL -Credential $Office365_Credentials -Authentication Basic -AllowRedirection -Name "Exchange Online" 163 | 164 | #This imports the Office 365 session into your active Shell. 165 | Import-PSSession $EXOSession 166 | } 167 | 168 | Function Disconnect-Office365_PSSession { 169 | <# 170 | .SYNOPSIS 171 | Disconnect PowerShell session to Office 365 Cloud Services 172 | 173 | .PARAMETER PSSession_Name 174 | Default name is "Exchange Online" 175 | #> 176 | param 177 | ( 178 | [Parameter(Mandatory = $true)] 179 | [string]$PSSession_Name 180 | ) 181 | 182 | Remove-PSSession -Name $PSSession_Name 183 | } 184 | 185 | #endregion 186 | 187 | #region ----------------------------------------------------------[Execution]---------------------------------------------------------- 188 | 189 | Start-Log -scriptName $scriptName -scriptVersion $scriptVersion -streamWriter $global:streamWriter 190 | cls 191 | Write-Host "================================================================================================" 192 | # Prerequisites 193 | #N/A 194 | Write-Host "================================================================================================" 195 | 196 | # Connect to Office 365 Cloud Services into active PowerShell shell 197 | Connect-Office365_PSSession 198 | 199 | # Import CSV input file (user list) 200 | [System.Windows.Forms.MessageBox]::Show( 201 | " 202 | Select on this window the CSV file who contains user list. 203 | Its content must be similar to: 204 | 205 | EmailAddress,UserName,Password,o365OldUPN,UsageLocation,o365License,o365Password (Required line) 206 | firstname.lastname@domain.com,firstname.lastname@domain.com,StrongPassword,firstname.lastname@domain.onmicrosoft.com,FR,reseller-account:EXCHANGESTANDARD, 207 | ", "User list", 0, [Windows.Forms.MessageBoxIcon]::Question) 208 | 209 | $CSVInputFile = Select-FileDialog -Title "Select CSV file" -Filter "CSV File (*.csv) |*.csv" 210 | 211 | # Import list of mailbox who need to create online archive 212 | $csvValues = Import-Csv $CSVInputFile -Delimiter ',' 213 | 214 | 215 | # Update UPN, user license and password 216 | ForEach ($usr in $csvValues) 217 | { 218 | $Lic = $usr.o365License 219 | $OldUPN = $usr.o365OldUPN 220 | $NewUPN = $usr.EmailAddress 221 | # $NewPass = $usr.o365Password 222 | 223 | $msoluser = Get-MsolUser -UserPrincipalName $OldUPN 2>$null | Select-Object UserPrincipalName, UsageLocation 224 | 225 | if ($msoluser) 226 | { 227 | Write-Log -streamWriter $global:streamWriter -infoToLog 'Update $OldUPN to $NewUPN and Licence $Lic' 228 | Set-MsolUserPrincipalName -UserPrincipalName $OldUPN -NewUserPrincipalName $NewUPN 229 | Set-Msoluser -UserPrincipalName $NewUPN -UsageLocation $UsageLocation 230 | Set-MsolUserLicense -UserPrincipalName $NewUPN -AddLicenses $Lic 231 | } 232 | else 233 | { 234 | Write-Error -Message '$OldUPN does not exists on the Tenant' 235 | Write-Log -streamWriter $global:streamWriter -infoToLog 'WARNING: $OldUPN does not exists on the Tenant' 236 | } 237 | } 238 | 239 | End-Log -streamWriter $global:streamWriter 240 | notepad $logPathName 241 | cls 242 | #endregion 243 | -------------------------------------------------------------------------------- /Office/Get-OfficeInstalledVersion.ps1: -------------------------------------------------------------------------------- 1 | $version = 0 2 | $reg = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey('LocalMachine', $computer) 3 | $reg.OpenSubKey('software\Microsoft\Office').GetSubKeyNames() |% { 4 | if ($_ -match '(\d+)\.') { 5 | if ([int]$matches[1] -gt $version) { 6 | $version = $matches[1] 7 | } 8 | } 9 | } 10 | 11 | if ($version) { 12 | "$computer : found $version" 13 | } 14 | 15 | else { 16 | "Could not find version for $computer" 17 | } 18 | -------------------------------------------------------------------------------- /Outlook/Create-Rule_PopupWhenMessageWithAttachment.ps1: -------------------------------------------------------------------------------- 1 | $outlook = New-Object -ComObject outlook.application 2 | $rules = $outlook.Session.DefaultStore.GetRules() 3 | $olRuleType = "Microsoft.Office.Interop.Outlook.OlRuleType" -as [type] 4 | $rule = $rules.Create("Popup Alert - Message with attanchment",$olRuleType::OlRuleReceive) 5 | $FromCondition = $rule.Conditions.HasAttachment 6 | $FromCondition.Enabled = $true 7 | $RuleAction = $rule.Actions.NewItemAlert 8 | $RuleAction.Text = "You received " 9 | $RuleAction.Enabled = $true 10 | $rules.Save() 11 | -------------------------------------------------------------------------------- /Outlook/Import-PST.ps1: -------------------------------------------------------------------------------- 1 | #requires -version 2 2 | <# 3 | .SYNOPSIS 4 | This script uses the Outlook COM object and import .pst files 5 | .DESCRIPTION 6 | This script creates an Outlook object, and import .pst files from "$env:USERPROFILE\Archives\" folder 7 | .INPUTS 8 | PST files from "$env:USERPROFILE\Archives\" folder 9 | .OUTPUTS 10 | N/A 11 | .NOTES 12 | Version: 1.0 13 | Author: ALBERT Jean-Marc 14 | Creation Date: 04/02/2016 15 | Purpose/Change: 1.0 - 2016.02.04 - ALBERT Jean-Marc - Initial script development 16 | .EXAMPLE 17 | N/A 18 | #> 19 | #---------------------------------------------------------[Initialisations]-------------------------------------------------------- 20 | #Set Error Action to Silently Continue 21 | $ErrorActionPreference = "SilentlyContinue" 22 | 23 | #----------------------------------------------------------[Declarations]---------------------------------------------------------- 24 | #Script Version 25 | $sScriptVersion = "1.0" 26 | 27 | #-----------------------------------------------------------[Functions]------------------------------------------------------------ 28 | <# 29 | Empty 30 | #> 31 | 32 | #------------------------------------------------------------[Actions]------------------------------------------------------------- 33 | 34 | 35 | # Create Outlook object 36 | $Outlook = New-Object -ComObject Outlook.Application 37 | $NameSpace = $Outlook.GetNameSpace("MAPI") 38 | $PSTfolder = "$env:USERPROFILE\Archives" 39 | 40 | # List all .pst files and import them 41 | dir “$PSTfolder\*.pst” | % { $NameSpace.AddStore($_.FullName) } 42 | 43 | # Show an information message 44 | [System.Windows.Forms.MessageBox]::Show("All .pst from $PSTfolder were imported to Outlook" , "Information" , 0, [Windows.Forms.MessageBoxIcon]::Information) 45 | 46 | # End Script 47 | -------------------------------------------------------------------------------- /Outlook/List-AllMailboxAndPST.ps1: -------------------------------------------------------------------------------- 1 | #requires -version 2 2 | <# 3 | .SYNOPSIS 4 | This script uses the Outlook COM object to display the data stores in the current profile. 5 | .DESCRIPTION 6 | This script creates an Outlook object, displays user information, and the stores currently attached to the profile. 7 | .INPUTS 8 | 9 | .OUTPUTS 10 | Results on a console. See .EXAMPLE to have an overview. 11 | .NOTES 12 | Version: 1.0 13 | Author: ALBERT Jean-Marc 14 | Creation Date: 29/06/2015 15 | Purpose/Change: 1.0 - 2015.06.29 - ALBERT Jean-Marc - Initial script development 16 | .EXAMPLE 17 | PSH [C:\foo]: .\List-AllMailboxAndPST.ps1' 18 | Current profile has the following configured accounts: 19 | 20 | Account Type User Name SMTP Address 21 | ------------ --------- ------------ 22 | Jean-Marc.Albert-EXT@domain.com Jean-Marc.ALBERT-EXT Jean-Marc.Albert-EXT@domain.com 23 | 24 | Exchange Offile Folder Store: 25 | C:\Users\9999912\AppData\Local\Microsoft\Outlook\Jean-Marc.Albert-EXT@domain.com.ost 26 | 27 | PST Files 28 | Display Name File Path 29 | ------------ --------- 30 | Archive Folders C:\Users\jean-marc.albert\AppData\Local\Microsoft\Outlook\archive.pst 31 | #> 32 | #---------------------------------------------------------[Initialisations]-------------------------------------------------------- 33 | #Set Error Action to Silently Continue 34 | $ErrorActionPreference = "SilentlyContinue" 35 | 36 | #----------------------------------------------------------[Declarations]---------------------------------------------------------- 37 | #Script Version 38 | $sScriptVersion = "1.0" 39 | #Write script directory path on "ScriptDir" variable 40 | $ScriptDir = Split-Path -Path $MyInvocation.MyCommand.Definition -Parent 41 | #Log file creation, similar to $ScriptDir\[SCRIPTNAME]_[YYYY_MM_DD].log 42 | $SystemTime = Get-Date -uformat %Hh%Mm%Ss 43 | $SystemDate = Get-Date -uformat %Y.%m.%d 44 | $ScriptLogFile = "$ScriptDir\$([System.IO.Path]::GetFileNameWithoutExtension($MyInvocation.MyCommand.Definition))" + "_" + $SystemDate + "_" + $SystemTime + ".log" 45 | 46 | #-----------------------------------------------------------[Functions]------------------------------------------------------------ 47 | function Stop-TranscriptOnLog 48 | { 49 | Stop-Transcript 50 | # Add EOL required for Notepad.exe application usage 51 | [string]::Join("`r`n", (Get-Content $ScriptLogFile)) | Out-File $ScriptLogFile 52 | } 53 | 54 | function Pause ($Message = "Press any key to continue . . . ") 55 | { 56 | if ((Test-Path variable:psISE) -and $psISE) 57 | { 58 | $Shell = New-Object -ComObject "WScript.Shell" 59 | $Button = $Shell.Popup("Click OK to continue.", 0, "Script Paused", 0) 60 | } 61 | else 62 | { 63 | Write-Host -NoNewline $Message 64 | [void][System.Console]::ReadKey($true) 65 | Write-Host 66 | } 67 | } 68 | 69 | #------------------------------------------------------------[Actions]------------------------------------------------------------- 70 | # Start of log completion 71 | Start-Transcript $ScriptLogFile | Out-Null 72 | 73 | # Create Outlook object 74 | $Outlook = New-Object -ComObject Outlook.Application 75 | $stores = $Outlook.Session.Stores 76 | $accounts = $outlook.session.accounts 77 | 78 | #$OutputData = @( 79 | # Basic information 80 | "Current profile has the following configured accounts:" 81 | $dn = @{label = "Account Type"; expression={$_.displayname}} 82 | $un = @{label = "User Name"; expression = {$_.username}} 83 | $sm = @{label = "SMTP Address"; expression = {$_.smtpaddress}} 84 | $accounts | Format-Table -AutoSize $dn,$un,$sm 85 | # Check number of stores > 0 86 | if ($stores.Count -le 0) {"No stores found"; return} 87 | 88 | # Outlook Off-Line folder store 89 | $ost = $stores | where{$_.filepath -match ".ost$"} 90 | if (!$ost) 91 | { 92 | "No Outlook Offline Folder store found" 93 | } 94 | else 95 | { 96 | "Exchange Offile Folder Store:" 97 | $ost | ft filepath -HideTableHeaders 98 | } 99 | 100 | # PST Files 101 | $pst = $stores | where {$_.filepath -match ".pst$"} 102 | if (!$pst) 103 | { 104 | "No PST files found" 105 | } 106 | else 107 | { 108 | "PST Files" 109 | $dn = @{label = "Display Name"; expression={$_.displayname}} 110 | $fn = @{label = "File Path"; expression={$_.filepath}} 111 | $pst | ft $dn,$fn 112 | } 113 | #) 114 | 115 | #[System.Windows.Forms.MessageBox]::Show("$OutputData" , "Information" , 0, [Windows.Forms.MessageBoxIcon]::Information) 116 | 117 | # Pause the script to see results on console 118 | Pause 119 | 120 | # End Script -------------------------------------------------------------------------------- /Outlook/Replace-MailSuffixOnADUserObject.ps1: -------------------------------------------------------------------------------- 1 | #requires -version 2 2 | <# 3 | .SYNOPSIS 4 | Replace @olddomain.fr to @newdomain.com on AD User e-mail address 5 | 6 | .DESCRIPTION 7 | List AD users with old suffix on e-mail address, export a list on CSV then replace old suffix by new one. 8 | Be aware to modify $oldSuffix and $newSuffix (lines 128 & 129) before usage. 9 | 10 | 11 | .INPUTS 12 | 13 | 14 | .OUTPUTS 15 | Create transcript log file similar to $ScriptDir\[SCRIPTNAME]_[YYYY_MM_DD]_[HHhMMmSSs].log 16 | Create a list of AD user objects, similar to $ScriptDir\[SCRIPTNAME]_SUBJECT_[YYYY_MM_DD]_[HHhMMmSSs].csv 17 | 18 | 19 | .NOTES 20 | Version: 1.1 21 | Author: ALBERT Jean-Marc 22 | Creation Date: 19/10/2016 (DD/MM/YYYY) 23 | Purpose/Change: 1.0 - 2016.10.19 - ALBERT Jean-Marc - Initial script development 24 | 1.1 - 2016.10.20 - ALBERT Jean-Marc - Replace hard-coded value for old suffix research on Get-AdUser selection with $oldsuffix 25 | 26 | 27 | .SOURCES 28 | N/A 29 | 30 | 31 | .EXAMPLE 32 | 33 | 34 | #> 35 | 36 | #---------------------------------------------------------[Initialisations]-------------------------------------------------------- 37 | Set-StrictMode -version Latest 38 | 39 | #Set Error Action to Silently Continue 40 | $ErrorActionPreference = "SilentlyContinue" 41 | 42 | $scriptPath = split-path -parent $MyInvocation.MyCommand.Definition 43 | $scriptFile = $MyInvocation.MyCommand.Definition 44 | $launchDate = get-date -f "yyyy.MM.dd-HHmmmss" 45 | $logDirectoryPath = $scriptPath + "\" + $launchDate 46 | $buffer = "$scriptPath\bufferCommand.txt" 47 | $fullScriptPath = (Resolve-Path -Path $buffer).Path 48 | 49 | 50 | 51 | #----------------------------------------------------------[Declarations]---------------------------------------------------------- 52 | 53 | $scriptName = [System.IO.Path]::GetFileName($scriptFile) 54 | $scriptVersion = "1.0" 55 | 56 | if(!(Test-Path $logDirectoryPath)) { 57 | New-Item $logDirectoryPath -type directory | Out-Null 58 | } 59 | 60 | $logFileName = "Log_" + $launchDate + ".log" 61 | $logPathName = "$logDirectoryPath\$logFileName" 62 | $ExportFileName = "Export_" + $launchDate + ".csv" 63 | $ExportPathName = "$logDirectoryPath\$ExportFileName" 64 | 65 | $global:streamWriter = New-Object System.IO.StreamWriter $logPathName 66 | 67 | $PrerequisitesModules = "ActiveDirectory" 68 | $PrerequisitesModulesError = "$Module does not exist, please install it then relaunch the script." 69 | 70 | 71 | #-----------------------------------------------------------[Functions]------------------------------------------------------------ 72 | 73 | Function Start-Log { 74 | [CmdletBinding()] 75 | Param ([Parameter(Mandatory=$true)][string]$scriptName, [Parameter(Mandatory=$true)][string]$scriptVersion, 76 | [Parameter(Mandatory=$true)][string]$streamWriter) 77 | Process{ 78 | $global:streamWriter.WriteLine("================================================================================================") 79 | $global:streamWriter.WriteLine("[$ScriptName] version [$ScriptVersion] started at $([DateTime]::Now)") 80 | $global:streamWriter.WriteLine("================================================================================================`n") 81 | } 82 | } 83 | 84 | Function Write-Log { 85 | [CmdletBinding()] 86 | Param ([Parameter(Mandatory=$true)][string]$streamWriter, [Parameter(Mandatory=$true)][string]$infoToLog) 87 | Process{ 88 | $InfoMessage = "$([DateTime]::Now) [INFO] $infoToLog" 89 | $global:streamWriter.WriteLine($InfoMessage) 90 | Write-Host $InfoMessage -ForegroundColor Cyan 91 | } 92 | } 93 | 94 | Function Write-Error { 95 | [CmdletBinding()] 96 | Param ([Parameter(Mandatory=$true)][string]$streamWriter, [Parameter(Mandatory=$true)][string]$errorCaught, [Parameter(Mandatory=$true)][boolean]$forceExit) 97 | Process{ 98 | $ErrorMessage = "$([DateTime]::Now) [ERROR] $errorCaught" 99 | $global:streamWriter.WriteLine($ErrorMessage) 100 | Write-Host $ErrorMessage -ForegroundColor Red 101 | if ($forceExit -eq $true){ 102 | End-Log -streamWriter $global:streamWriter 103 | break; 104 | } 105 | } 106 | } 107 | 108 | Function End-Log { 109 | [CmdletBinding()] 110 | Param ([Parameter(Mandatory=$true)][string]$streamWriter) 111 | Process{ 112 | $global:streamWriter.WriteLine("`n================================================================================================") 113 | $global:streamWriter.WriteLine("Script ended at $([DateTime]::Now)") 114 | $global:streamWriter.WriteLine("================================================================================================") 115 | 116 | $global:streamWriter.Close() 117 | } 118 | } 119 | 120 | 121 | #----------------------------------------------------------[Execution]---------------------------------------------------------- 122 | 123 | Start-Log -scriptName $scriptName -scriptVersion $scriptVersion -streamWriter $global:streamWriter 124 | Write-Host "================================================================================================" 125 | Write-Host "List AD user account without a recent password (unmodified since $NumberOfDays days)" 126 | Write-Host "================================================================================================" 127 | 128 | 129 | $oldSuffix = "@olddomain.fr" 130 | $newSuffix = "@newdomain.com" 131 | 132 | $ADUserSelection = Get-AdUser -Filter * -Property GivenName,sn,mail,lastlogondate,samAccountName | Where-Object {($_.Enabled) -eq "True" -AND ($_.mail) -match $oldSuffix} | select GivenName,sn,mail,lastlogondate,samAccountName 133 | $ADUserSelection | Export-CSV -Path $ExportPathName -Encoding UTF8 -NoType -Force 134 | $ADUserSelection | ForEach-Object { 135 | $newUpn = $_.mail.Replace($oldSuffix,$newSuffix) 136 | $newUpn 137 | Set-ADUser -identity $_.samaccountname -EmailAddress $newUpn 138 | } 139 | 140 | #Writing informations in the log file 141 | Write-Progress -Activity "Write informations in the log file" -status "Running..." -id 1 142 | Write-Log -streamWriter $global:streamWriter -infoToLog "If you don't see any lines between start & end of logfile, it means that everything's OK" 143 | End-Log -streamWriter $global:streamWriter 144 | notepad $logPathName 145 | #cls 146 | -------------------------------------------------------------------------------- /PrepareServer/1-AddAdPrereqs.ps1: -------------------------------------------------------------------------------- 1 | #requires -version 2 2 | <# 3 | .SYNOPSIS 4 | 5 | 6 | .DESCRIPTION 7 | 8 | 9 | .INPUTS 10 | 11 | 12 | .OUTPUTS 13 | Create transcript log file similar to $ScriptDir\[SCRIPTNAME]_[YYYY_MM_DD]_[HHhMMmSSs].log 14 | Create a list of AD Objects, similar to $ScriptDir\[SCRIPTNAME]_FoundADObjects_[YYYY_MM_DD]_[HHhMMmSSs].csv 15 | 16 | 17 | .NOTES 18 | Version: 0.1 19 | Author: ALBERT Jean-Marc 20 | Creation Date: DD/MM/YYYY (DD/MM/YYYY 21 | Purpose/Change: 1.0 - YYYY.MM.DD - ALBERT Jean-Marc - Initial script development 22 | 23 | 24 | .SOURCES 25 | 26 | 27 | 28 | .EXAMPLE 29 | 30 | 31 | #> 32 | 33 | #---------------------------------------------------------[Initialisations]-------------------------------------------------------- 34 | Set-StrictMode -version Latest 35 | 36 | #Set Error Action to Silently Continue 37 | #$ErrorActionPreference = "SilentlyContinue" 38 | 39 | $scriptPath = split-path -parent $MyInvocation.MyCommand.Definition 40 | $scriptFile = $MyInvocation.MyCommand.Definition 41 | $launchDate = get-date -f "yyyy.MM.dd-HHhmmmss" 42 | $logDirectoryPath = $scriptPath + "\" 43 | $buffer = "$scriptPath\bufferCommand.txt" 44 | $fullScriptPath = (Resolve-Path -Path $buffer).Path 45 | 46 | $loggingFunctions = "$scriptPath\logging\Logging.ps1" 47 | $utilsFunctions = "$scriptPath\utilities\Utils.ps1" 48 | $addsFunctions = "$scriptPath\utilities\ADDS.ps1" 49 | 50 | 51 | #----------------------------------------------------------[Declarations]---------------------------------------------------------- 52 | 53 | $scriptName = [System.IO.Path]::GetFileName($scriptFile) 54 | $scriptVersion = "0.1" 55 | 56 | if(!(Test-Path $logDirectoryPath)) { 57 | New-Item $logDirectoryPath -type directory | Out-Null 58 | } 59 | 60 | $logFileName = "Log_" + $launchDate + ".log" 61 | $logPathName = "$logDirectoryPath\$logFileName" 62 | 63 | $global:streamWriter = New-Object System.IO.StreamWriter $logPathName 64 | 65 | #-----------------------------------------------------------[Functions]------------------------------------------------------------ 66 | 67 | . $loggingFunctions 68 | . $utilsFunctions 69 | . $addsFunctions 70 | 71 | #----------------------------------------------------------[Execution]---------------------------------------------------------- 72 | 73 | Start-Log -scriptName $scriptName -scriptVersion $scriptVersion -streamWriter $global:streamWriter 74 | cls 75 | Write-Host "================================================================================================" 76 | 77 | # Prerequisites 78 | Test-LocalAdminRights 79 | if($adminFlag -eq $false){ 80 | Write-Host "You have to launch this script with " -nonewline; Write-Host "local Administrator rights!" -f Red 81 | $scriptPath = Split-Path $MyInvocation.InvocationName 82 | $RWMC = $scriptPath + "\$scriptName.ps1" 83 | $ArgumentList = 'Start-Process -FilePath powershell.exe -ArgumentList \"-ExecutionPolicy Bypass -File "{0}"\" -Verb Runas' -f $RWMC; 84 | Start-Process -FilePath powershell.exe -ArgumentList $ArgumentList -Wait -NoNewWindow; 85 | Stop-Script 86 | } 87 | else { 88 | Write-Host "Administrator rights detected." -nonewline; Write-Host "The script will continue." -f Green 89 | } 90 | 91 | Write-Host "================================================================================================" 92 | 93 | # Modify the Execution Policy 94 | Write-Progress -Activity "Modify the Execution Policy" -status "Running..." -id 1 95 | Set-ExecutionPolicy Bypass -Scope Process 96 | 97 | # Set static IP address 98 | Write-Progress -Activity "Set static IP address" -status "Running..." -id 1 99 | $ipaddress = "192.168.10.11" 100 | $ipprefix = "24" 101 | $ipgw = "192.168.10.1" 102 | $ipdns = "127.0.0.1" 103 | $ipif = (Get-NetAdapter).ifIndex 104 | New-NetIPAddress -IPAddress $ipaddress -PrefixLength $ipprefix ` 105 | -InterfaceIndex $ipif -DefaultGateway $ipgw 106 | # Rename the NetAdapter 107 | Get-NetAdapter -Name * | ? status -eq up | Rename-NetAdapter -NewName "LAN $ipgw" 108 | 109 | # Rename the computer 110 | $newname = "AD1FR1010" 111 | Rename-Computer -NewName $newname -force 112 | 113 | #install features 114 | $addsTools = "RSAT-AD-Tools" 115 | Add-WindowsFeature $addsTools 116 | 117 | # Add informations to logfile 118 | Get-Content env:computername >> $logPathName 119 | Get-NetIPAddress | Where { $_.PrefixLength -eq 24 } >> $logPathName 120 | Get-WindowsFeature | Where installed >> $logPathName 121 | 122 | 123 | 124 | 125 | # Writing informations in the log file 126 | Write-Progress -Activity "Write informations in the log file" -status "Running..." -id 1 127 | End-Log -streamWriter $global:streamWriter 128 | notepad $logPathName 129 | 130 | # Restart the computer 131 | Write-Progress -Activity "Server will restart in 15 seconds" -status "Running..." -id 1 132 | Start-Sleep -s 15 133 | Restart-Computer -------------------------------------------------------------------------------- /PrepareServer/bufferCommand.txt: -------------------------------------------------------------------------------- 1 | dw 00000000 -------------------------------------------------------------------------------- /PrepareServer/logging/Logging.ps1: -------------------------------------------------------------------------------- 1 | Function Start-Log { 2 | [CmdletBinding()] 3 | Param ([Parameter(Mandatory=$true)][string]$scriptName, [Parameter(Mandatory=$true)][string]$scriptVersion, 4 | [Parameter(Mandatory=$true)][string]$streamWriter) 5 | Process{ 6 | $global:streamWriter.WriteLine("================================================================================================") 7 | $global:streamWriter.WriteLine("[$ScriptName] version [$ScriptVersion] started at $([DateTime]::Now)") 8 | $global:streamWriter.WriteLine("================================================================================================`n") 9 | } 10 | } 11 | 12 | Function Write-Log { 13 | [CmdletBinding()] 14 | Param ([Parameter(Mandatory=$true)][string]$streamWriter, [Parameter(Mandatory=$true)][string]$infoToLog) 15 | Process{ 16 | $global:streamWriter.WriteLine("$infoToLog") 17 | } 18 | } 19 | 20 | Function Write-Error { 21 | [CmdletBinding()] 22 | Param ([Parameter(Mandatory=$true)][string]$streamWriter, [Parameter(Mandatory=$true)][string]$errorCaught, [Parameter(Mandatory=$true)][boolean]$forceExit) 23 | Process{ 24 | $global:streamWriter.WriteLine("Error: [$errorCaught]") 25 | if ($forceExit -eq $true){ 26 | End-Log -streamWriter $global:streamWriter 27 | break; 28 | } 29 | } 30 | } 31 | 32 | Function End-Log { 33 | [CmdletBinding()] 34 | Param ([Parameter(Mandatory=$true)][string]$streamWriter) 35 | Process{ 36 | $global:streamWriter.WriteLine("`n================================================================================================") 37 | $global:streamWriter.WriteLine("Script ended at $([DateTime]::Now)") 38 | $global:streamWriter.WriteLine("================================================================================================") 39 | 40 | $global:streamWriter.Close() 41 | } 42 | } -------------------------------------------------------------------------------- /PrepareServer/utilities/Utils.ps1: -------------------------------------------------------------------------------- 1 | function OnApplicationLoad { 2 | return $true #return true for success or false for failure 3 | } 4 | function OnApplicationExit { 5 | $script:ExitCode = 0 #Set the exit code for the Packager 6 | } 7 | 8 | function Set-RegistryKey($computername, $parentKey, $nameRegistryKey, $valueRegistryKey) { 9 | try{ 10 | $remoteBaseKeyObject = [microsoft.win32.registrykey]::OpenRemoteBaseKey('LocalMachine',$computername) 11 | $regKey = $remoteBaseKeyObject.OpenSubKey($parentKey,$true) 12 | $regKey.Setvalue("$nameRegistryKey", "$valueRegistryKey", [Microsoft.Win32.RegistryValueKind]::DWORD) 13 | $remoteBaseKeyObject.close() 14 | } 15 | catch { 16 | $_.Exception 17 | } 18 | } 19 | 20 | function Disable-UAC($computername) { 21 | $parentKey = "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Policies\\System" 22 | $nameRegistryKey = "LocalAccountTokenFilterPolicy" 23 | $valueRegistryKey = "1" 24 | 25 | $objReg = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey('LocalMachine', $computername) 26 | $objRegKey= $objReg.OpenSubKey($parentKey) 27 | $test = $objRegkey.GetValue($nameRegistryKey) 28 | if($test -eq $null){ 29 | Set-RegistryKey $computername $parentKey $nameRegistryKey $valueRegistryKey 30 | Write-Host "Registry key setted, you have to reboot the remote computer" -foregroundcolor "magenta" 31 | Stop-Script 32 | } 33 | else { 34 | if($test -ne 1){ 35 | Set-RegistryKey $computername $parentKey $nameRegistryKey $valueRegistryKey 36 | Write-Host "Registry key setted, you have to reboot the remote computer" -foregroundcolor "magenta" 37 | Stop-Script 38 | } 39 | } 40 | } 41 | 42 | function CreateDirectoryIfNeeded ( [string] $directory ) { 43 | if (!(Test-Path -Path $directory -type "Container")) { 44 | New-Item -type directory -Path $directory > $null 45 | } 46 | } 47 | 48 | function Run-WmiRemoteProcess { 49 | Param( 50 | [string]$computername=$env:COMPUTERNAME, 51 | [string]$cmd=$(Throw "You must enter the full path to the command which will create the process."), 52 | [int]$timeout = 0 53 | ) 54 | 55 | Write-Host "Process to create on $computername is $cmd" 56 | [wmiclass]$wmi="\\$computername\root\cimv2:win32_process" 57 | # Exit if the object didn't get created 58 | if (!$wmi) {return} 59 | 60 | try{ 61 | $remote=$wmi.Create($cmd) 62 | } 63 | catch{ 64 | $_.Exception 65 | } 66 | $test =$remote.returnvalue 67 | if ($remote.returnvalue -eq 0) { 68 | Write-Host ("Successfully launched $cmd on $computername with a process id of " + $remote.processid) 69 | } else { 70 | Write-Host ("Failed to launch $cmd on $computername. ReturnValue is " + $remote.ReturnValue) 71 | } 72 | return 73 | } 74 | 75 | function Stop-Script () { 76 | Begin{ 77 | Write-Log -streamWriter $global:streamWriter -infoToLog "--- Script terminating ---" 78 | } 79 | Process{ 80 | "Script terminating..." 81 | Write-Host "================================================================================================" 82 | End-Log -streamWriter $global:streamWriter 83 | Exit 84 | } 85 | } 86 | 87 | Function Stop-ScriptMessageBox () { 88 | # MessageBox who inform of the end of the process 89 | [System.Windows.Forms.MessageBox]::Show( 90 | "Process done. 91 | The log file will be opened when click on 'OK' button. 92 | Please, check the log file for further informations. 93 | " , "End of process" , 0, [Windows.Forms.MessageBoxIcon]::Information) 94 | } 95 | 96 | function Test-InternetConnection { 97 | if(![Activator]::CreateInstance([Type]::GetTypeFromCLSID([Guid]'{DCB00C01-570F-4A9B-8D69-199FDBA5723B}')).IsConnectedToInternet){ 98 | Write-Host "The script need an Internet Connection to run" -f Red 99 | Stop-Script 100 | } 101 | } 102 | 103 | function Test-LocalAdminRights { 104 | $myComputer = Get-WMIObject Win32_ComputerSystem | Select-Object -ExpandProperty name 105 | $myUser = [System.Security.Principal.WindowsIdentity]::GetCurrent() 106 | $amIAdmin = ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()) 107 | $adminFlag = $amIAdmin.IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator") 108 | if($adminFlag -eq $true){ 109 | $adminMessage = " with administrator rights on " 110 | } 111 | else { 112 | $adminMessage = " without administrator rights on " 113 | } 114 | 115 | Write-Host "Script runs with user " -nonewline; Write-Host $myUser.Name -f Red -nonewline; Write-Host $adminMessage -nonewline; Write-Host $myComputer -f Red -nonewline; Write-Host " computer" 116 | return $adminFlag 117 | } -------------------------------------------------------------------------------- /Printing/Declare-PrintDrivers.ps1: -------------------------------------------------------------------------------- 1 | #Define drivers that we want to install 2 | $DriverBase = @' 3 | Xerox GPD PS V5.645.5.0 4 | Xerox GPD PS V5.645.5.0 5 | Xerox GPD PCL6 V5.645.5.0 6 | Xerox GPD PCL6 V5.645.5.0 7 | Xerox GPD PCL V5.645.5.0 8 | Xerox GPD PCL V5.645.5.0 9 | Xerox Global Print Driver V4 PS 10 | Xerox Global Print Driver V4 PS 11 | Xerox Global Print Driver V4 PCL6 12 | Xerox Global Print Driver V4 PCL6 13 | Xerox Global Print Driver PS 14 | Xerox Global Print Driver PS 15 | Xerox Global Print Driver PCL6 16 | Xerox Global Print Driver PCL6 17 | Xerox Global Print Driver PCL 18 | Xerox Global Print Driver PCL 19 | '@ 20 | 21 | 22 | #Installation of printers in Windows 23 | $DriversSourcePath = "\\NETWORKSHARE\C$\Drivers\Printers\" 24 | Get-ChildItem -Filter "*.inf" -Path $DriversSourcePath -Recurse | ForEach-Object { PnPutil.exe -i -a $_.FullName } 25 | 26 | #Inject drivers (x86 and x64) to the spool service 27 | foreach ($DriverName in $DriverBase) { 28 | Add-PrinterDriver -Name $DriverName -PrinterEnvironment "Windows NT x86" 29 | Add-PrinterDriver -Name $DriverName -PrinterEnvironment "Windows x64" 30 | } 31 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # PowerShell-AdminScripts 2 | [![Buy me a coffee](https://www.buymeacoffee.com/assets/img/custom_images/black_img.png)](https://www.buymeacoff.ee/WikiJM) 3 | 4 | Differents PowerShell scripts that could automatize and help to manage Windows Server role & features like : 5 | * Active Directory 6 | * Active Directory Certificate Services 7 | * Exchange 8 | * FSRM 9 | * Hyper-V 10 | * Prepare Server (global) 11 | 12 | Eventually, you can find scripts related to workstations, like : 13 | * Outlook 14 | * Security (submit suspicious files to malwr.com) 15 | * Manage local accounts and groups (create Admin local account) 16 | -------------------------------------------------------------------------------- /ScheduledTasks/Set-ScheduledTaskCredential.ps1: -------------------------------------------------------------------------------- 1 | # Set-ScheduledTaskCredential.ps1 2 | # Written by Bill Stewart (bstewart@iname.com) 3 | # http://www.itprotoday.com/management-mobility/updating-scheduled-tasks-credentials 4 | 5 | #requires -version 2 6 | 7 | <# 8 | .SYNOPSIS 9 | Sets the credentials for one or more scheduled tasks on a computer. 10 | 11 | .DESCRIPTION 12 | Sets the credentials for one or more scheduled tasks on a computer. 13 | 14 | .PARAMETER TaskName 15 | One or more scheduled task names. Wildcard values are not accepted. This parameter accepts pipeline input. 16 | 17 | .PARAMETER TaskCredential 18 | The credentials for the scheduled task. If you don't specify this parameter, you will be prompted for credentials. 19 | 20 | .PARAMETER ComputerName 21 | The computer name where the scheduled task(s) reside. 22 | 23 | .PARAMETER ConnectionCredential 24 | The credentials to use when connecting to the computer. 25 | 26 | .EXAMPLE 27 | PS C:\>Set-ScheduledTaskCredential "My Scheduled Task" 28 | This command will prompt for credentials and configure the specified task using those credentials. 29 | 30 | .EXAMPLE 31 | PS C:\>Set-ScheduledTaskCredential "Task 1","Task 2" -ComputerName server1 32 | This command will prompt for credentials and configure the named scheduled tasks on the computer server1. 33 | 34 | .EXAMPLE 35 | PS C:\>Set-ScheduledTaskCredential "Task 1","Task 2" -ComputerName server1 36 | This command will prompt for credentials and configure the named scheduled tasks on the computer server1. 37 | 38 | .EXAMPLE 39 | PS C:\>Get-Content TaskNames.txt | Set-ScheduledTaskCredential -ConnectionCredential (Get-Credential) 40 | This command will set scheduled task credentials for all tasks named in the file TaskNames.txt. There will be two credential prompts. The first prompt is to specify credentials to connect to the Task Scheduler service, and the second prompt is to specify credentials to use for the scheduled tasks. 41 | #> 42 | 43 | [CmdletBinding(SupportsShouldProcess=$TRUE)] 44 | param( 45 | [parameter(Mandatory=$TRUE,ValueFromPipeline=$TRUE)] 46 | [String[]] $TaskName, 47 | [System.Management.Automation.PSCredential] $TaskCredential, 48 | [String] $ComputerName=$ENV:COMPUTERNAME, 49 | [System.Management.Automation.PSCredential] $ConnectionCredential 50 | ) 51 | 52 | begin { 53 | $PIPELINEINPUT = (-not $PSBOUNDPARAMETERS.ContainsKey("TaskName")) -and (-not $TaskName) 54 | $TASK_LOGON_PASSWORD = 1 55 | $TASK_LOGON_S4U = 2 56 | $TASK_UPDATE = 4 57 | $MIN_SCHEDULER_VERSION = 0x00010002 58 | 59 | # Try to create the TaskService object on the local computer; throw an error on failure 60 | try { 61 | $TaskService = new-object -comobject "Schedule.Service" 62 | } 63 | catch [System.Management.Automation.PSArgumentException] { 64 | throw $_ 65 | } 66 | 67 | # Assume $NULL for the schedule service connection parameters unless -ConnectionCredential used 68 | $userName = $domainName = $connectPwd = $NULL 69 | if ($ConnectionCredential) { 70 | # Get user name, domain name, and plain-text copy of password from PSCredential object 71 | $userName = $ConnectionCredential.UserName.Split("\")[1] 72 | $domainName = $ConnectionCredential.UserName.Split("\")[0] 73 | $connectPwd = $ConnectionCredential.GetNetworkCredential().Password 74 | } 75 | try { 76 | $TaskService.Connect($ComputerName, $userName, $domainName, $connectPwd) 77 | } 78 | catch [System.Management.Automation.MethodInvocationException] { 79 | write-error "Error connecting to '$ComputerName' - '$_'" 80 | exit 81 | } 82 | 83 | # Returns a 32-bit unsigned value as a version number (x.y, where x is the 84 | # most-significant 16 bits and y is the least-significant 16 bits). 85 | function convertto-versionstr([UInt32] $version) { 86 | $major = [Math]::Truncate($version / [Math]::Pow(2, 0x10)) -band 0xFFFF 87 | $minor = $version -band 0xFFFF 88 | "$($major).$($minor)" 89 | } 90 | 91 | if ($TaskService.HighestVersion -lt $MIN_SCHEDULER_VERSION) { 92 | write-error ("Schedule service on '$ComputerName' is version $($TaskService.HighestVersion) " + 93 | "($(convertto-versionstr($TaskService.HighestVersion))). The Schedule service must " + 94 | "be version $MIN_SCHEDULER_VERSION ($(convertto-versionstr $MIN_SCHEDULER_VERSION)) " + 95 | "or higher.") 96 | exit 97 | } 98 | 99 | # This prevents a scoping problem--if the $TaskCredential variable 100 | # doesn't exist, it won't get created in the correct scope--create 101 | # new variable as a workaround 102 | $NewTaskCredential = $TaskCredential 103 | if (-not $NewTaskCredential) { 104 | $NewTaskCredential = $HOST.UI.PromptForCredential("Task Credentials", 105 | "Please specify credentials for the scheduled task.", "", "") 106 | if (-not $NewTaskCredential) { 107 | write-error "You must specify credentials." 108 | exit 109 | } 110 | } 111 | 112 | function set-scheduledtaskcredential2($taskName) { 113 | $rootFolder = $TaskService.GetFolder("\") 114 | try { 115 | $taskDefinition = $rootFolder.GetTask($taskName).Definition 116 | } 117 | catch [System.Management.Automation.MethodInvocationException] { 118 | write-error "Scheduled task '$taskName' not found on '$computerName'." 119 | return 120 | } 121 | $logonType = $taskDefinition.Principal.LogonType 122 | # No need to set credentials for tasks that don't have stored credentials. 123 | if (-not (($logonType -eq $TASK_LOGON_PASSWORD) -or ($logonType -eq $TASK_LOGON_S4U))) { 124 | write-error "Scheduled task '$taskName' on '$ComputerName' doesn't have stored credentials." 125 | return 126 | } 127 | if (-not $PSCMDLET.ShouldProcess("Task '$taskName' on computer '$ComputerName'", 128 | "Set scheduled task credentials")) { return } 129 | try { 130 | [Void] $rootFolder.RegisterTaskDefinition($taskName, $taskDefinition, $TASK_UPDATE, 131 | $NewTaskCredential.UserName, $NewTaskCredential.GetNetworkCredential().Password, $logonType) 132 | } 133 | catch [System.Management.Automation.MethodInvocationException] { 134 | write-error "Error updating scheduled task '$taskName' on '$computerName' - '$_'" 135 | } 136 | } 137 | } 138 | 139 | process { 140 | if ($PIPELINEINPUT) { 141 | set-scheduledtaskcredential2 $_ 142 | } 143 | else { 144 | $TaskName | foreach-object { 145 | set-scheduledtaskcredential2 $_ 146 | } 147 | } 148 | } 149 | -------------------------------------------------------------------------------- /Security/Submit-SuspiciousFilesToMalwrCOM/Submit-SuspiciousFilesToMalwrCOM.ps1: -------------------------------------------------------------------------------- 1 | #requires -version 2 2 | <# 3 | .SYNOPSIS 4 | Submit all files of a specific folder to Malwr.com webservice 5 | 6 | .DESCRIPTION 7 | Submit all files of a specific folder to Malwr.com webservice 8 | 9 | .INPUTS 10 | Personal API Key 11 | Folder path 12 | 13 | 14 | .OUTPUTS 15 | Create transcript log file similar to $ScriptDir\[SCRIPTNAME]_[YYYY_MM_DD]_[HHhMMmSSs].log 16 | Generate results on console, in the meantime visible on log file 17 | 18 | .NOTES 19 | Version: 1.0 20 | Author: ALBERT Jean-Marc 21 | Creation Date: 10/03/2016 22 | Purpose/Change: 1.0 - 2016.03.10 - ALBERT Jean-Marc - Initial script development 23 | 24 | 25 | .SOURCES 26 | https://malwr.com/account/profile/ - API tab on a personal account profile 27 | 28 | 29 | .EXAMPLE 30 | 31 | #> 32 | 33 | 34 | #---------------------------------------------------------[Initialisations]-------------------------------------------------------- 35 | 36 | #Get input strings 37 | param( 38 | [string] $computername = "$ENV:COMPUTERNAME", 39 | [string] $reportfile = "$ScriptDir\$([System.IO.Path]::GetFileNameWithoutExtension($MyInvocation.MyCommand.Definition))" + "_" + $SystemDate + "_" + $SystemTime + ".html", 40 | [string] $APIkey = "personal_api_key", 41 | [string] $IsFileShared = "no", 42 | [string] $SuspiciousFileContainer = "C:\suspiciousfilecontainer\" 43 | ) 44 | 45 | 46 | 47 | #----------------------------------------------------------[Declarations]---------------------------------------------------------- 48 | 49 | #Script Version 50 | $sScriptVersion = "1.0" 51 | 52 | #Write script directory path on "ScriptDir" variable 53 | $ScriptDir = Split-Path -Path $MyInvocation.MyCommand.Definition -Parent 54 | $Script 55 | $SystemTime = Get-Date -uformat %Hh%Mm%Ss 56 | $SystemDate = Get-Date -uformat %Y.%m.%d 57 | 58 | 59 | 60 | #-----------------------------------------------------------[Functions]------------------------------------------------------------ 61 | 62 | #Send mail function 63 | Function send_mail([string]$message,[string]$subject) { 64 | $emailFrom = "name@domain.com" 65 | $emailCC = "name@domain.com" 66 | $emailTo = "name@domain.com" 67 | $smtpServer = "smtp.domain.com" 68 | Send-MailMessage -SmtpServer $smtpServer -To $emailTo -Cc $emailCC -From $emailFrom -Subject $subject -Body $message -BodyAsHtml -Priority High 69 | } 70 | 71 | 72 | 73 | #------------------------------------------------------------[Actions]------------------------------------------------------------- 74 | 75 | #Start stopwatch 76 | $totalTime = New-Object -TypeName System.Diagnostics.Stopwatch 77 | $totalTime.Start() 78 | 79 | #Credits 80 | Write-Host 81 | Write-Host "Malwr.com - Suspicious file submission " -ForegroundColor "Yellow" 82 | Write-Host 83 | 84 | # List all files and import them 85 | $fileEntries = [IO.Directory]::GetFiles("$SuspiciousFileContainer"); 86 | foreach($fileName in $fileEntries) 87 | { 88 | #Submit all files (located on the selected directory) to Malwr.com threat analysis webservice 89 | curl -F api_key=$APIkey -F shared=$IsFileShared -F file="$fileName" https://malwr.com/api/analysis/add/ 90 | 91 | } 92 | 93 | 94 | #Stop stopwatch 95 | $totalTime.Stop() 96 | $ts = $totalTime.Elapsed 97 | $totalTime = [system.String]::Format("{0:00}:{1:00}:{2:00}",$ts.Hours, $ts.Minutes, $ts.Seconds) 98 | Write-Host "Process total time: $totalTime" -ForegroundColor Yellow 99 | Write-Host 100 | 101 | Invoke-Item $reportfile -------------------------------------------------------------------------------- /VMware Workstation/Start-VMwareWorkstationServices.ps1: -------------------------------------------------------------------------------- 1 | #requires -version 2 2 | <# 3 | .SYNOPSIS 4 | Show a menu to easily check and start VMware Workstation services 5 | 6 | .DESCRIPTION 7 | Show a menu to easily check and start VMware Workstation services. Type a number from 0 to 4 to launch and action. 8 | 9 | .INPUTS 10 | 11 | 12 | .OUTPUTS 13 | 14 | 15 | 16 | .NOTES 17 | Version: 0.1 18 | Author: ALBERT Jean-Marc 19 | Creation Date: 23/04/2016 (DD/MM/YYYY) 20 | Purpose/Change: 1.0 - 2016.04.23 - ALBERT Jean-Marc - Initial script development 21 | 22 | 23 | .SOURCES 24 | 25 | 26 | 27 | .EXAMPLE 28 | 29 | 30 | #> 31 | 32 | #---------------------------------------------------------[Initialisations]-------------------------------------------------------- 33 | Set-StrictMode -version Latest 34 | 35 | #Set Error Action to Silently Continue 36 | $ErrorActionPreference = "SilentlyContinue" 37 | 38 | #----------------------------------------------------------[Declarations]---------------------------------------------------------- 39 | 40 | $ScriptName = [System.IO.Path]::GetFileName($ScriptFile) 41 | $ScriptPath = Split-Path $MyInvocation.InvocationName 42 | $ScriptFilePath = $ScriptPath + "\$ScriptName.ps1" 43 | $ScriptVersion = "0.1" 44 | 45 | #-----------------------------------------------------------[Functions]------------------------------------------------------------ 46 | 47 | function Show-Menu 48 | { 49 | param ( 50 | [string]$selection 51 | ) 52 | 53 | Clear-Host 54 | Write-Host "================ $Title ================" 55 | 56 | Write-Host "1: List VMmware services (with status)" 57 | Write-Host "2: Start System services (Authorization and USB Arbitration)" 58 | Write-Host "3: Start Network services (DHCP and NAT)" 59 | Write-Host "4: Start Remote Administration service (Workstation Server)" 60 | Write-Host "0: Exit" 61 | } 62 | 63 | function Get-VMwareServicesStatus 64 | { 65 | Get-Service | Where-Object {$_.DisplayName -Like "VMware*"} | Sort-Object Status,Name,DisplayName | %{ 66 | if ( $_.Status -eq "Stopped") 67 | { 68 | Write-Host $_.Status "|" $_.Name "|" $_.DisplayName -ForegroundColor red 69 | } 70 | elseif ( $_.Status -eq "Running") 71 | { 72 | Write-Host $_.Status "|" $_.Name "|" $_.DisplayName -ForegroundColor green} 73 | } 74 | } 75 | 76 | #----------------------------------------------------------[Execution]---------------------------------------------------------- 77 | 78 | #Show menu 79 | do 80 | { 81 | Show-Menu 82 | $selection = Read-Host "Please make a selection" 83 | switch ($selection) 84 | { 85 | '1' { 86 | Clear-Host 87 | Get-VMwareServicesStatus 88 | } 89 | '2' { 90 | Start-Service "VMAuthdService" 91 | Start-Service "VMUSBArbService" 92 | Get-VMwareServicesStatus 93 | } 94 | '3' { 95 | Start-Service "VMnetDHCP" 96 | Start-Service "VMware NAT Service" 97 | Get-VMwareServicesStatus 98 | } 99 | '4' { 100 | Start-Service "VMwareHostd" 101 | Get-VMwareServicesStatus 102 | } 103 | '0' { 104 | Exit 105 | } 106 | } 107 | pause 108 | } 109 | until ($selection -ceq '0') 110 | 111 | Exit -------------------------------------------------------------------------------- /WSUS/Get-ComputersToRebootAfterUpdate.ps1: -------------------------------------------------------------------------------- 1 | #requires -version 3 2 | <# 3 | .SYNOPSIS 4 | List AD Computers that have a pending reboot after Windows Update KB install 5 | 6 | .DESCRIPTION 7 | List AD Computers that have a pending reboot after Windows Update KB install, thanks to specific values on two registry key, then export it to .CSV file 8 | 9 | .INPUTS 10 | 11 | .OUTPUTS 12 | Create transcript log file similar to $ScriptDir\[SCRIPTNAME]_[YYYY_MM_DD]_[HHhMMmSSs].log 13 | Create a list of AD user objects, similar to $ScriptDir\[SCRIPTNAME]_SUBJECT_[YYYY_MM_DD]_[HHhMMmSSs].csv 14 | 15 | 16 | .NOTES 17 | Version: 1.0 18 | Author: ALBERT Jean-Marc 19 | Creation Date: 25/10/2016 (DD/MM/YYYY) 20 | Purpose/Change: 1.0 - 2016.10.25 - ALBERT Jean-Marc - Initial script development 21 | 22 | 23 | .SOURCES 24 | N/A 25 | 26 | 27 | .EXAMPLE 28 | 29 | #> 30 | 31 | #---------------------------------------------------------[Initialisations]-------------------------------------------------------- 32 | Set-StrictMode -version Latest 33 | 34 | #Set Error Action to Silently Continue 35 | $ErrorActionPreference = "SilentlyContinue" 36 | 37 | $scriptPath = split-path -parent $MyInvocation.MyCommand.Definition 38 | $scriptFile = $MyInvocation.MyCommand.Definition 39 | $launchDate = get-date -f "yyyy.MM.dd-HHmmmss" 40 | $logDirectoryPath = $scriptPath + "\" + $launchDate 41 | $buffer = "$scriptPath\bufferCommand.txt" 42 | $fullScriptPath = (Resolve-Path -Path $buffer).Path 43 | 44 | 45 | #----------------------------------------------------------[Declarations]---------------------------------------------------------- 46 | 47 | $scriptName = [System.IO.Path]::GetFileName($scriptFile) 48 | $scriptVersion = "1.0" 49 | 50 | if(!(Test-Path $logDirectoryPath)) { 51 | New-Item $logDirectoryPath -type directory | Out-Null 52 | } 53 | 54 | $logFileName = "Log_" + $launchDate + ".log" 55 | $logPathName = "$logDirectoryPath\$logFileName" 56 | $ExportFileName = "Export_" + $launchDate + ".csv" 57 | $ExportPathName = "$logDirectoryPath\$ExportFileName" 58 | 59 | $global:streamWriter = New-Object System.IO.StreamWriter $logPathName 60 | 61 | $PrerequisitesModules = "ActiveDirectory" 62 | $PrerequisitesModulesError = "$Module does not exist, please install it then relaunch the script." 63 | 64 | 65 | #-----------------------------------------------------------[Functions]------------------------------------------------------------ 66 | 67 | Function Start-Log { 68 | [CmdletBinding()] 69 | Param ([Parameter(Mandatory=$true)][string]$scriptName, [Parameter(Mandatory=$true)][string]$scriptVersion, 70 | [Parameter(Mandatory=$true)][string]$streamWriter) 71 | Process{ 72 | $global:streamWriter.WriteLine("================================================================================================") 73 | $global:streamWriter.WriteLine("[$ScriptName] version [$ScriptVersion] started at $([DateTime]::Now)") 74 | $global:streamWriter.WriteLine("================================================================================================`n") 75 | } 76 | } 77 | 78 | Function Write-Log { 79 | [CmdletBinding()] 80 | Param ([Parameter(Mandatory=$true)][string]$streamWriter, [Parameter(Mandatory=$true)][string]$infoToLog) 81 | Process{ 82 | $InfoMessage = "$([DateTime]::Now) [INFO] $infoToLog" 83 | $global:streamWriter.WriteLine($InfoMessage) 84 | Write-Host $InfoMessage -ForegroundColor Cyan 85 | } 86 | } 87 | 88 | Function Write-Error { 89 | [CmdletBinding()] 90 | Param ([Parameter(Mandatory=$true)][string]$streamWriter, [Parameter(Mandatory=$true)][string]$errorCaught, [Parameter(Mandatory=$true)][boolean]$forceExit) 91 | Process{ 92 | $ErrorMessage = "$([DateTime]::Now) [ERROR] $errorCaught" 93 | $global:streamWriter.WriteLine($ErrorMessage) 94 | Write-Host $ErrorMessage -ForegroundColor Red 95 | if ($forceExit -eq $true){ 96 | End-Log -streamWriter $global:streamWriter 97 | break; 98 | } 99 | } 100 | } 101 | 102 | Function End-Log { 103 | [CmdletBinding()] 104 | Param ([Parameter(Mandatory=$true)][string]$streamWriter) 105 | Process{ 106 | $global:streamWriter.WriteLine("`n================================================================================================") 107 | $global:streamWriter.WriteLine("Script ended at $([DateTime]::Now)") 108 | $global:streamWriter.WriteLine("================================================================================================") 109 | 110 | $global:streamWriter.Close() 111 | } 112 | } 113 | 114 | Function Get-PendingReboot($computer = '.') { 115 | $hkey = 'LocalMachine'; 116 | $path_server = 'SOFTWARE\Microsoft\ServerManager'; 117 | $path_control = 'SYSTEM\CurrentControlSet\Control'; 118 | $path_session = join-path $path_control 'Session Manager'; 119 | $path_name = join-path $path_control 'ComputerName'; 120 | $path_name_old = join-path $path_name 'ActiveComputerName'; 121 | $path_name_new = join-path $path_name 'ComputerName'; 122 | $path_wsus = 'SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate\Auto Update\RebootRequired'; 123 | $pending_rename = 'PendingFileRenameOperations'; 124 | $pending_rename_2 = 'PendingFileRenameOperations2'; 125 | $attempts = 'CurrentRebootAttempts'; 126 | $computer_name = 'ComputerName'; 127 | 128 | $num_attempts = 0; 129 | $name_old = $null; 130 | $name_new = $null; 131 | 132 | $reg= [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey($hkey, $computer); 133 | 134 | $key_session = $reg.OpenSubKey($path_session); 135 | if ($key_session -ne $null) { 136 | $session_values = @($key_session.GetValueNames()); 137 | $key_session.Close() | out-null; 138 | } 139 | 140 | $key_server = $reg.OpenSubKey($path_server); 141 | if ($key_server -ne $null) { 142 | $num_attempts = $key_server.GetValue($attempts); 143 | $key_server.Close() | out-null; 144 | } 145 | 146 | $key_name_old = $reg.OpenSubKey($path_name_old); 147 | if ($key_name_old -ne $null) { 148 | $name_old = $key_name_old.GetValue($computer_name); 149 | $key_name_old.Close() | out-null; 150 | 151 | $key_name_new = $reg.OpenSubKey($path_name_new); 152 | if ($key_name_new -ne $null) { 153 | $name_new = $key_name_new.GetValue($computer_name); 154 | $key_name_new.Close() | out-null; 155 | } 156 | } 157 | 158 | $key_wsus = $reg.OpenSubKey($path_wsus); 159 | if ($key_wsus -ne $null) { 160 | $wsus_values = @($key_wsus.GetValueNames()); 161 | if ($wsus_values) { 162 | $wsus_rbpending = $true 163 | } else { 164 | $wsus_rbpending = $false 165 | } 166 | $key_wsus.Close() | out-null; 167 | } 168 | 169 | $reg.Close() | out-null; 170 | #modified return section: 171 | if ( ` 172 | (($session_values -contains $pending_rename) -or ($session_values -contains $pending_rename_2)) ` 173 | -or (($num_attempts -gt 0) -or ($name_old -ne $name_new)) ` 174 | -or ($wsus_rbpending)) { 175 | return $true; 176 | } 177 | else { 178 | return $false; 179 | } 180 | } 181 | 182 | 183 | #----------------------------------------------------------[Execution]---------------------------------------------------------- 184 | 185 | Start-Log -scriptName $scriptName -scriptVersion $scriptVersion -streamWriter $global:streamWriter 186 | Write-Host "================================================================================================" 187 | Write-Host "List AD computers with a pending reboot (after Windows Update KB install)" 188 | Write-Host "================================================================================================" 189 | 190 | 191 | Import-Module ActiveDirectory 192 | 193 | Write-Progress -Activity "List all AD Computer on Windows 7" -status "Running..." -id 1 194 | $Computers = Get-ADComputer -Filter * -Property OperatingSystem | Where-Object {$_.OperatingSystem -match 'Windows 7'} | Select Name 195 | 196 | Write-Progress -Activity "Check on Windows 7 AD computers if there is a pending reboot " -status "Running..." -id 1 197 | ForEach ($Computer in $Computers) { 198 | $ComputerName = $Computer.Name 199 | $IsRebootPending = $(Get-PendingReboot $ComputerName) 200 | $ComputerName + ';' + $IsRebootPending | Out-File -Append $ExportPathName 201 | } 202 | 203 | #Writing informations in the log file 204 | Write-Progress -Activity "Write informations in the log file" -status "Running..." -id 1 205 | Write-Log -streamWriter $global:streamWriter -infoToLog "If you don't see any lines between start & end of logfile, it means that everything's OK" 206 | End-Log -streamWriter $global:streamWriter 207 | notepad $logPathName 208 | #cls 209 | --------------------------------------------------------------------------------