├── Functions ├── AD │ ├── Search-ADLockoutLocation.ps1 │ └── Search-ADUser.ps1 ├── FS │ ├── Find-FSDirectory.ps1 │ ├── Find-FSFile.ps1 │ ├── Get-FSDirectorySize.ps1 │ └── Search-FSBiggestFiles.ps1 └── OS │ ├── Get-OSPerformanceMemoryCommittedBytesHigh.ps1 │ ├── Get-OSPerformanceMemoryPagingFileHigh.ps1 │ ├── Get-OSPerformanceMemoryPoolNonPagedBytesHigh.ps1 │ ├── Get-OSPerformanceProcessorUsageHigh.ps1 │ ├── Get-OSUptime.ps1 │ └── Start-OSAutomaticServices.ps1 ├── LICENSE ├── README.md └── Scripts ├── Console └── IIS │ └── IISSetupWebServer.ps1 └── GUI ├── AD ├── ADUserResetPassword.ps1 └── ADUserUnlock.ps1 └── TOOL └── RandomPasswordGenerator.ps1 /Functions/AD/Search-ADLockoutLocation.ps1: -------------------------------------------------------------------------------- 1 | <# 2 | .SYNOPSIS 3 | Function to find the location (computer) where an Active Directory user was locked out. 4 | .DESCRIPTION 5 | In case an Active Directory user gets frequently locked out, you can use this function to check on which computer the lockout occurs. It does so by querying the Security Event Logs of the Domain Controllers. Once you have determined on which computer the lockout occurs, you still need to determine what exactly is causing the account lockout. This can be manual drive mapping, a service running under the user account, an ODBC connection, etc. 6 | .PARAMETER UserName 7 | In the parameter UserName you can specify the Active Directory user for which you want to find on which computer it was locked out. You need to specify the SamAccountName of the user. 8 | .EXAMPLE 9 | PS C:\>Search-ADLockoutLocation -UserName user1 10 | 11 | This command will search for the location where user1 was locked out. 12 | .NOTES 13 | Author : Ingvald Belmans 14 | Website : http://www.supersysadmin.com 15 | Version : 1.0 16 | Changelog: 17 | - 1.0 (2015-12-30) Initial version. 18 | .LINK 19 | http://www.supersysadmin.com 20 | #> 21 | function Search-ADLockoutLocation 22 | { 23 | [CmdletBinding()] 24 | Param 25 | ( 26 | [Parameter( 27 | Mandatory=$true, 28 | ValueFromPipeline=$true, 29 | ValueFromPipelineByPropertyName=$true 30 | ) 31 | ] 32 | [String] 33 | $UserName 34 | ) 35 | Begin 36 | { 37 | Write-Verbose -Message "Checking if module 'ActiveDirectory' is loaded." 38 | if ((Get-Module -name 'ActiveDirectory') -eq $null) 39 | { 40 | Write-Verbose -Message "Module 'ActiveDirectory' is currently not loaded." 41 | if(Get-Module -ListAvailable | Where-Object { $_.name -eq 'ActiveDirectory' }) 42 | { 43 | Write-Verbose -Message "Module 'ActiveDirectory' is available, importing it." 44 | Import-Module -Name 'ActiveDirectory' 45 | if ((Get-Module -name 'ActiveDirectory') -ne $null) 46 | { 47 | Write-Verbose -Message "Module 'ActiveDirectory' has been loaded now." 48 | } 49 | else 50 | { 51 | Write-Warning -Message "Module 'ActiveDirectory' could not be loaded. Script will exit." 52 | break 53 | } 54 | } 55 | else 56 | { 57 | Write-Warning -Message "Module 'ActiveDirectory' is not available on this system. Script will exit." 58 | break 59 | } 60 | } 61 | else 62 | { 63 | Write-Verbose -Message "Module 'ActiveDirectory' is already loaded." 64 | } 65 | } 66 | Process 67 | { 68 | Write-Verbose -Message "Searching in Active Directory for user '$UserName'." 69 | $QueryLockedUser = Get-ADUser -Filter "(SamAccountName -eq '$UserName')" 70 | if ($QueryLockedUser -eq $null) 71 | { 72 | Write-Warning -Message "Did not find any Active Directory user with username '$UserName'. Please ensure you are searching on the correct username (SamAccountName). Script will now exit." 73 | break 74 | } 75 | else 76 | { 77 | $LockoutEvents = @() 78 | Write-Verbose -Message "Retrieving list of all Domain Controllers." 79 | $DomainControllers = Get-ADDomainController -Filter * 80 | foreach ($DomainController in $DomainControllers) 81 | { 82 | Write-Verbose -Message "Querying Domain Controller '$DomainController'." 83 | Write-Verbose -Message "Checking if Domain Controller '$DomainController' is the PDC Emulator." 84 | if ($DomainController.OperationMasterRoles -contains "PDCEmulator") 85 | { 86 | Write-Verbose -Message "Domain Controller '$DomainController' is the PDC Emulator." 87 | $DomainControllerPDCEmulator = "Yes" 88 | } 89 | else 90 | { 91 | Write-Verbose -Message "Domain Controller '$DomainController' is not the PDC Emulator." 92 | $DomainControllerPDCEmulator = "No" 93 | } 94 | Write-Verbose -Message "Retrieving user information for user '$UserName' from Domain Controller '$DomainController'." 95 | $QueryADUser = Get-ADUser -Filter "(SamAccountName -eq '$UserName')" -Properties * -Server $DomainController 96 | Write-Verbose -Message "Querying the Security Event Log of Domain Controller'$DomainController' for events with ID 4740." 97 | 98 | try 99 | { 100 | $QueryDomainControllerEventLog = Get-WinEvent -ComputerName $DomainController -FilterHashtable @{LogName='Security';Id=4740} -ErrorAction Stop 101 | } 102 | catch [exception] 103 | { 104 | if ($_.Exception -match "No events were found that match the specified selection criteria") 105 | { 106 | Write-Verbose -Message "Did not find any event with ID 4740 in the Security Event Log of Domain Controller '$DomainController'." 107 | } 108 | } 109 | foreach ($LockoutEvent in $QueryDomainControllerEventLog) 110 | { 111 | Write-Verbose -Message "Found event with ID 4740 on Domain Controller '$DomainController'." 112 | $LockoutEventXML = [xml]$LockoutEvent.ToXml() 113 | $LockoutEventXMLEventLogTime = $LockoutEventXML.Event.System.TimeCreated.SystemTime 114 | $LockoutEventXMLLockoutLocation = $LockoutEventXML.Event.EventData.Data[1].'#text' 115 | $LockoutEventXMLSID = $LockoutEventXML.Event.EventData.Data[2].'#text' 116 | if ($QueryADUser.SID.Value -match $LockoutEventXMLSID) 117 | { 118 | Write-Verbose -Message "Found event with ID 4740 in the Security Event Log of Domain Controller '$DomainController' which refers to user '$UserName'." 119 | $LockoutEventsObject = New-Object -TypeName System.Object 120 | $LockoutEventsObject | Add-Member -MemberType NoteProperty -Name "DomainController" -Value $DomainController.HostName 121 | $LockoutEventsObject | Add-Member -MemberType NoteProperty -Name "PDCEmulator" -Value $DomainControllerPDCEmulator 122 | $LockoutEventsObject | Add-Member -MemberType NoteProperty -Name "SamAccountName" -Value $QueryADUser.SamAccountName 123 | $LockoutEventsObject | Add-Member -MemberType NoteProperty -Name "LockedOut" -Value $QueryADUser.LockedOut 124 | $LockoutEventsObject | Add-Member -MemberType NoteProperty -Name "EventLogTime" -Value $LockoutEventXMLEventLogTime 125 | $LockoutEventsObject | Add-Member -MemberType NoteProperty -Name "LockoutLocation" -Value $LockoutEventXMLLockoutLocation 126 | $LockoutEvents += $LockoutEventsObject 127 | } 128 | else 129 | { 130 | Write-Verbose -Message "Found event with ID 4740 in the Security Event Log of Domain Controller '$DomainController', but it does not refer to user '$UserName'." 131 | } 132 | } 133 | } 134 | if ($LockoutEvents.Count -eq '0') 135 | { 136 | Write-Verbose -Message "Did not find any event with ID 4740 in the Security Event Log of any Domain Controller that refer to user '$UserName'." 137 | } 138 | else 139 | { 140 | Write-Output -InputObject $LockoutEvents | Sort-Object EventLogTime -Descending 141 | } 142 | } 143 | } 144 | End 145 | { 146 | } 147 | } 148 | -------------------------------------------------------------------------------- /Functions/AD/Search-ADUser.ps1: -------------------------------------------------------------------------------- 1 | <# 2 | .SYNOPSIS 3 | Function to search users in Active Directory. 4 | .DESCRIPTION 5 | Function to search users in Active Directory. 6 | .PARAMETER SearchQuery 7 | In the parameter SearchQuery you can specify on what you want to search. You can search on multiple search strings in 1 query. 8 | .PARAMETER SearchType 9 | In the parameter SearchType you can specify on which property of the user you want to perform your search query. Possbile types are UserName (searches in SamAccountName), Name (searches in GivenName, SurName and DisplayName) and EmailAddress. The default is UserName. 10 | .PARAMETER Domain 11 | In the parameter Domain you can specify in which domain you want to search. If not specified, it uses a Get-ADDomain query to get the current domain name. 12 | .EXAMPLE 13 | PS C:\>Search-ADUser -SearchQuery user1 14 | 15 | This command will search for users which have user1 in their UserName in the current domain. 16 | .EXAMPLE 17 | PS C:\>Search-ADUser -SearchQuery John -SearchType EmailAddress -Domain example.com 18 | 19 | This command will search for users which have John in their EmailAddress in the domain example.com. 20 | .NOTES 21 | Author : Ingvald Belmans 22 | Website : http://www.supersysadmin.com 23 | Version : 1.0 24 | Changelog: 25 | - 1.0 (2015-12-25) Initial version. 26 | .LINK 27 | http://www.supersysadmin.com 28 | #> 29 | function Search-ADUser 30 | { 31 | [CmdletBinding()] 32 | Param 33 | ( 34 | [Parameter( 35 | Mandatory=$true, 36 | ValueFromPipeline=$true, 37 | ValueFromPipelineByPropertyName=$true 38 | ) 39 | ] 40 | [String[]] 41 | $SearchQuery, 42 | [validateset('UserName','Name','EmailAddress')] 43 | [string] 44 | $SearchType = "UserName", 45 | [string] 46 | $Domain = (Get-ADDomain).Forest 47 | ) 48 | Begin 49 | { 50 | Write-Verbose -Message "Checking module 'ActiveDirectory'." 51 | if ((Get-Module -name 'ActiveDirectory') -eq $null) 52 | { 53 | Write-Verbose -Message "Module 'ActiveDirectory' is currently not loaded." 54 | if(Get-Module -ListAvailable | Where-Object { $_.name -eq 'ActiveDirectory' }) 55 | { 56 | Write-Verbose -Message "Module 'ActiveDirectory' is available, importing it." 57 | Import-Module -Name 'ActiveDirectory' 58 | if ((Get-Module -name 'ActiveDirectory') -ne $null) 59 | { 60 | Write-Verbose -Message "Module 'ActiveDirectory' has been loaded now." 61 | } 62 | else 63 | { 64 | Write-Warning -Message "Module 'ActiveDirectory' could not be loaded. Script will exit." 65 | break 66 | } 67 | } 68 | else 69 | { 70 | Write-Warning -Message "Module 'ActiveDirectory' is not available on this system. Script will exit." 71 | break 72 | } 73 | } 74 | else 75 | { 76 | Write-Verbose -Message "Module 'ActiveDirectory' is already loaded." 77 | } 78 | } 79 | Process 80 | { 81 | $SearchResult = @() 82 | foreach ($SearchQueryItem in $SearchQuery) 83 | { 84 | if ($SearchType -eq 'UserName') 85 | { 86 | $ADQuery = Get-ADUser -Filter "SamAccountName -like '*$SearchQueryItem*'" -Server $Domain -Properties * 87 | Write-Verbose -Message "Searching for users in the domain '$Domain' which have '$SearchQueryItem' in their 'UserName'. Please wait..." 88 | 89 | } 90 | elseif ($SearchType -eq 'Name') 91 | { 92 | $ADQuery = Get-ADUser -Filter "(GivenName -like '*$SearchQueryItem*') -or (SurName -like '*$SearchQueryItem*') -or (DisplayName -like '*$SearchQueryItem*')" -Server $Domain -Properties * 93 | Write-Verbose -Message "Searching for users in the domain '$Domain' which have '$SearchQueryItem' in their 'GivenName, SurName or DisplayName'. Please wait..." 94 | } 95 | elseif ($SearchType -eq 'EmailAddress') 96 | { 97 | $ADQuery = Get-ADUser -Filter "EmailAddress -like '*$SearchQueryItem*'" -Server $Domain -Properties * 98 | Write-Verbose -Message "Searching for users in the domain '$Domain' which have '$SearchQueryItem' in their 'EmailAddress'. Please wait..." 99 | } 100 | foreach ($Result in $ADQuery) 101 | { 102 | $SearchResultObject = New-Object -TypeName System.Object 103 | $SearchResultObject | Add-Member -MemberType NoteProperty -Name "SamAccountName" -Value $Result.SamAccountName 104 | $SearchResultObject | Add-Member -MemberType NoteProperty -Name "DisplayName" -Value $Result.DisplayName 105 | $SearchResultObject | Add-Member -MemberType NoteProperty -Name "GivenName" -Value $Result.GivenName 106 | $SearchResultObject | Add-Member -MemberType NoteProperty -Name "SurName" -Value $Result.SurName 107 | $SearchResultObject | Add-Member -MemberType NoteProperty -Name "EmailAddress" -Value $Result.EmailAddress 108 | $SearchResultObject | Add-Member -MemberType NoteProperty -Name "HomeDirectory" -Value $Result.HomeDirectory 109 | $SearchResultObject | Add-Member -MemberType NoteProperty -Name "DistinguishedName" -Value $Result.DistinguishedName 110 | $SearchResultObject | Add-Member -MemberType NoteProperty -Name "Enabled" -Value $Result.Enabled 111 | $SearchResultObject | Add-Member -MemberType NoteProperty -Name "LockedOut" -Value $Result.LockedOut 112 | $SearchResult += $SearchResultObject 113 | } 114 | } 115 | Write-Output $SearchResult 116 | } 117 | End 118 | { 119 | } 120 | } 121 | -------------------------------------------------------------------------------- /Functions/FS/Find-FSDirectory.ps1: -------------------------------------------------------------------------------- 1 | <# 2 | .SYNOPSIS 3 | Function to find directories which match a certain name. 4 | .DESCRIPTION 5 | Function to find directories which match a certain name. 6 | .PARAMETER Path 7 | In the parameter Path you can specify the directory you want to query. This can be both a local or remote (UNC) path. 8 | .PARAMETER SearchString 9 | In the parameter SearchString you can specify the (partial) directory you want to find. 10 | .PARAMETER Recurse 11 | When using the switch Recurse the function will also search in subdirectories. 12 | .EXAMPLE 13 | PS C:\>Find-FSDirectory -Path C:\Windows -SearchString "System" -Recurse 14 | 15 | This command will retrieve a list of directories in C:\Windows (and subdirectories) which have "System" in their name. 16 | .NOTES 17 | Author : Ingvald Belmans 18 | Website : http://www.supersysadmin.com 19 | Version : 1.0 20 | Changelog: 21 | - 1.0 (2015-12-24) Initial version. 22 | .LINK 23 | http://www.supersysadmin.com 24 | #> 25 | function Find-FSDirectory 26 | { 27 | [CmdletBinding()] 28 | Param 29 | ( 30 | [Parameter( 31 | Mandatory=$true, 32 | ValueFromPipeline=$true, 33 | ValueFromPipelineByPropertyName=$true 34 | ) 35 | ] 36 | [String] 37 | $Path, 38 | [Parameter( 39 | Mandatory=$true, 40 | ValueFromPipeline=$true, 41 | ValueFromPipelineByPropertyName=$true 42 | ) 43 | ] 44 | [String] 45 | $SearchString, 46 | [switch] 47 | $Recurse 48 | ) 49 | Begin 50 | { 51 | } 52 | Process 53 | { 54 | Write-Verbose -Message "Searching for directories in '$Path' which match '$SearchString'. Please wait..." 55 | $SearchResult = @() 56 | if($Recurse) 57 | { 58 | $SearchQuery = Get-ChildItem -Path $Path -Directory -Recurse | Where-Object -FilterScript { $_.Name -match $SearchString} 59 | } 60 | else 61 | { 62 | $SearchQuery = Get-ChildItem -Path $Path -Directory | Where-Object -FilterScript { $_.Name -match $SearchString} 63 | } 64 | foreach ($SearchQueryItem in $SearchQuery) 65 | { 66 | $SearchResultObject = New-Object -TypeName System.Object 67 | $SearchResultObject | Add-Member -MemberType NoteProperty -Name "DirectoryName" -Value $SearchQueryItem.Name 68 | $SearchResultObject | Add-Member -MemberType NoteProperty -Name "FullPath" -Value $SearchQueryItem.FullName 69 | $SearchResultObject | Add-Member -MemberType NoteProperty -Name "LastWriteTime" -Value $SearchQueryItem.LastWriteTime 70 | $SearchResultObject | Add-Member -MemberType NoteProperty -Name "LastAccessTime" -Value $SearchQueryItem.LastAccessTime 71 | $SearchResult += $SearchResultObject 72 | } 73 | Write-Output -InputObject $SearchResult 74 | } 75 | End 76 | { 77 | } 78 | } 79 | -------------------------------------------------------------------------------- /Functions/FS/Find-FSFile.ps1: -------------------------------------------------------------------------------- 1 | <# 2 | .SYNOPSIS 3 | Function to find files which match a certain name. 4 | .DESCRIPTION 5 | Function to find files which match a certain name. 6 | .PARAMETER Path 7 | In the parameter Path you can specify the directory you want to query. This can be both a local or remote (UNC) path. 8 | .PARAMETER SearchString 9 | In the parameter SearchString you can specify the (partial) filename you want to find. 10 | .PARAMETER Recurse 11 | When using the switch Recurse the function will also search in subdirectories. 12 | .EXAMPLE 13 | PS C:\>Find-FSFile -Path C:\Windows -SearchString "exe" -Recurse 14 | 15 | This command will retrieve a list of files in C:\Windows (and subdirectories) which have "exe" in their name. 16 | .NOTES 17 | Author : Ingvald Belmans 18 | Website : http://www.supersysadmin.com 19 | Version : 1.0 20 | Changelog: 21 | - 1.0 (2015-12-24) Initial version. 22 | .LINK 23 | http://www.supersysadmin.com 24 | #> 25 | function Find-FSFile 26 | { 27 | [CmdletBinding()] 28 | Param 29 | ( 30 | [Parameter( 31 | Mandatory=$true, 32 | ValueFromPipeline=$true, 33 | ValueFromPipelineByPropertyName=$true 34 | ) 35 | ] 36 | [String] 37 | $Path, 38 | [Parameter( 39 | Mandatory=$true, 40 | ValueFromPipeline=$true, 41 | ValueFromPipelineByPropertyName=$true 42 | ) 43 | ] 44 | [String] 45 | $SearchString, 46 | [switch] 47 | $Recurse 48 | ) 49 | Begin 50 | { 51 | } 52 | Process 53 | { 54 | Write-Verbose -Message "Searching for files in '$Path' which match '$SearchString'. Please wait..." 55 | $SearchResult = @() 56 | if($Recurse) 57 | { 58 | $SearchQuery = Get-ChildItem -Path $Path -File -Recurse | Where-Object -FilterScript { $_.Name -match $SearchString} 59 | } 60 | else 61 | { 62 | $SearchQuery = Get-ChildItem -Path $Path -File | Where-Object -FilterScript { $_.Name -match $SearchString} 63 | } 64 | foreach ($SearchQueryItem in $SearchQuery) 65 | { 66 | $SearchResultObject = New-Object -TypeName System.Object 67 | $SearchResultObject | Add-Member -MemberType NoteProperty -Name "FileName" -Value $SearchQueryItem.Name 68 | $SearchResultObject | Add-Member -MemberType NoteProperty -Name "Directory" -Value $SearchQueryItem.Directory 69 | $SearchResultObject | Add-Member -MemberType NoteProperty -Name "Extension" -Value $SearchQueryItem.Extension 70 | $SearchResultObject | Add-Member -MemberType NoteProperty -Name "Size(MB)" -Value ($SearchQueryItem.Length/1MB) 71 | $SearchResultObject | Add-Member -MemberType NoteProperty -Name "LastWriteTime" -Value $SearchQueryItem.LastWriteTime 72 | $SearchResultObject | Add-Member -MemberType NoteProperty -Name "LastAccessTime" -Value $SearchQueryItem.LastAccessTime 73 | $SearchResult += $SearchResultObject 74 | } 75 | Write-Output -InputObject $SearchResult 76 | } 77 | End 78 | { 79 | } 80 | } 81 | -------------------------------------------------------------------------------- /Functions/FS/Get-FSDirectorySize.ps1: -------------------------------------------------------------------------------- 1 | <# 2 | .SYNOPSIS 3 | Function to retrieve the size of a directory and the number of files and directories inside of it. 4 | .DESCRIPTION 5 | Function to retrieve the size of a directory and the number of files and directories inside of it. 6 | .PARAMETER Path 7 | In the parameter Path you can specify the directory you want to query. This can be both a local or remote (UNC) path. 8 | .PARAMETER OutputFormat 9 | In the parameter OutputFormat you can specify the format in which the directory size should be outputted. Possible formats are KB, MB and GB. The default is GB. 10 | .PARAMETER NoRecurse 11 | When using the switch NoRecurse the function will only query the directory specified in the Path parameter and will not query child directories and files. 12 | .EXAMPLE 13 | PS C:\>Get-FSDirectorySize -Path C:\Windows 14 | 15 | This command will retrieve the size (in GB) of the directory C:\Windows and the number of files and directories insides of it. 16 | .NOTES 17 | Author : Ingvald Belmans 18 | Website : http://www.supersysadmin.com 19 | Version : 1.0 20 | Changelog: 21 | - 1.0 (2015-12-31) Initial version. 22 | .LINK 23 | http://www.supersysadmin.com 24 | #> 25 | function Get-FSDirectorySize 26 | { 27 | [CmdletBinding()] 28 | Param 29 | ( 30 | [Parameter( 31 | Mandatory=$true, 32 | ValueFromPipeline=$true, 33 | ValueFromPipelineByPropertyName=$true 34 | ) 35 | ] 36 | [String] 37 | $Path, 38 | [validateset('KB','MB','GB')] 39 | [string] 40 | $OutputFormat = "GB", 41 | [switch] 42 | $NoRecurse 43 | ) 44 | Begin 45 | { 46 | } 47 | Process 48 | { 49 | Write-Verbose -Message "Testing if path '$Path' exists." 50 | if (Test-Path -Path $Path) 51 | { 52 | Write-Verbose -Message "Path '$Path' exists." 53 | $DirectorySize = @() 54 | $DirectorySizeObject = New-Object -TypeName System.Object 55 | if ($NoRecurse) 56 | { 57 | Write-Verbose -Message "Performing a non-recursive search on path '$Path'." 58 | $QueryDirectory = Get-ChildItem -Path $Path -ErrorVariable QueryDirectoryErrors -ErrorAction SilentlyContinue 59 | } 60 | else 61 | { 62 | Write-Verbose -Message "Performing a recursive search on path '$Path'." 63 | $QueryDirectory = Get-ChildItem -Path $Path -Recurse -ErrorVariable QueryDirectoryErrors -ErrorAction SilentlyContinue 64 | } 65 | foreach ($QueryDirectoryError in $QueryDirectoryErrors) 66 | { 67 | Write-Warning -Message $QueryDirectoryError 68 | } 69 | $DirectorySizeObject | Add-Member -MemberType NoteProperty -Name "Directory" -Value $Path 70 | Write-Verbose -Message "Calculating size of path '$Path'." 71 | $QueryDirectorySize = $QueryDirectory | Measure-Object -Property Length -Sum 72 | if ($OutputFormat -eq "KB") 73 | { 74 | Write-Verbose -Message "Setting OutputFormat to KB." 75 | $QueryDirectorySizeFormattedHeader = "Size(KB)" 76 | $QueryDirectorySizeFormatted = "{0:N2}" -f ($QueryDirectorySize.Sum / 1KB) 77 | } 78 | elseif ($OutputFormat -eq "MB") 79 | { 80 | Write-Verbose -Message "Setting OutputFormat to MB." 81 | $QueryDirectorySizeFormattedHeader = "Size(MB)" 82 | $QueryDirectorySizeFormatted = "{0:N2}" -f ($QueryDirectorySize.Sum / 1MB) 83 | } 84 | elseif ($OutputFormat -eq "GB") 85 | { 86 | Write-Verbose -Message "Setting OutputFormat to GB." 87 | $QueryDirectorySizeFormattedHeader = "Size(GB)" 88 | $QueryDirectorySizeFormatted = "{0:N2}" -f ($QueryDirectorySize.Sum / 1GB) 89 | } 90 | $DirectorySizeObject | Add-Member -MemberType NoteProperty -Name $QueryDirectorySizeFormattedHeader -Value $QueryDirectorySizeFormatted 91 | Write-Verbose -Message "Calculating amount of directories in path '$Path'." 92 | $QueryDirectoryDirectories = $QueryDirectory | Where-Object -FilterScript {$_.PSIsContainer -eq $true} 93 | $DirectorySizeObject | Add-Member -MemberType NoteProperty -Name "Directories" -Value $QueryDirectoryDirectories.Count 94 | Write-Verbose -Message "Calculating amount of files in path '$Path'." 95 | $QueryDirectoryFiles = $QueryDirectory | Where-Object -FilterScript {$_.PSIsContainer -eq $false} 96 | $DirectorySizeObject | Add-Member -MemberType NoteProperty -Name "Files" -Value $QueryDirectoryFiles.Count 97 | $DirectorySize += $DirectorySizeObject 98 | Write-Output -InputObject $DirectorySize 99 | } 100 | else 101 | { 102 | Write-Warning -Message "Path '$path' does not exist." 103 | break 104 | } 105 | } 106 | End 107 | { 108 | } 109 | } 110 | -------------------------------------------------------------------------------- /Functions/FS/Search-FSBiggestFiles.ps1: -------------------------------------------------------------------------------- 1 | <# 2 | .SYNOPSIS 3 | Function to retrieve a list of files in a directory which are bigger than a given size. 4 | .DESCRIPTION 5 | Function to retrieve a list of files in a directory which are bigger than a given size. 6 | .PARAMETER Path 7 | In the parameter Path you can specify the directory you want to query. This can be both a local or remote (UNC) path. 8 | .PARAMETER MinimumSize 9 | In the parameter MinimumSize you can specify the minimum size of the files you want to search for. 10 | .PARAMETER Recurse 11 | When using the switch Recurse the function will also search in subdirectories. 12 | .EXAMPLE 13 | PS C:\>Search-FSBiggestFiles -Path C:\Temp -MinimumSize 1MB -Recurse 14 | 15 | This command retrieves a list of files from C:\Temp and its subdirectories with a size of 1MB or more. 16 | .NOTES 17 | Author : Ingvald Belmans 18 | Website : http://www.supersysadmin.com 19 | Version : 1.0 20 | Changelog: 21 | - 1.0 (2015-12-23) Initial version. 22 | .LINK 23 | http://www.supersysadmin.com 24 | #> 25 | function Search-FSBiggestFiles 26 | { 27 | [CmdletBinding()] 28 | Param 29 | ( 30 | [Parameter( 31 | Mandatory=$true, 32 | ValueFromPipeline=$true, 33 | ValueFromPipelineByPropertyName=$true 34 | ) 35 | ] 36 | [String] 37 | $Path, 38 | [Parameter( 39 | Mandatory=$true 40 | ) 41 | ] 42 | [string] 43 | $MinimumSize, 44 | [switch] 45 | $Recurse 46 | ) 47 | Begin 48 | { 49 | } 50 | Process 51 | { 52 | Write-Verbose -Message "Querying '$Path'. Please wait..." 53 | $SearchResult = @() 54 | if($Recurse) 55 | { 56 | $SearchQuery = Get-ChildItem -Path $Path -File -Recurse | Where-Object -FilterScript {($_.Length) -ge $MinimumSize} 57 | } 58 | else 59 | { 60 | $SearchQuery = Get-ChildItem -Path $Path -File | Where-Object -FilterScript {($_.Length) -ge $MinimumSize} 61 | } 62 | foreach ($SearchQueryItem in $SearchQuery) 63 | { 64 | $SearchResultObject = New-Object -TypeName System.Object 65 | $SearchResultObject | Add-Member -MemberType NoteProperty -Name "FileName" -Value $SearchQueryItem.Name 66 | $SearchResultObject | Add-Member -MemberType NoteProperty -Name "Directory" -Value $SearchQueryItem.Directory 67 | $SearchResultObject | Add-Member -MemberType NoteProperty -Name "Extension" -Value $SearchQueryItem.Extension 68 | $SearchResultObject | Add-Member -MemberType NoteProperty -Name "Size(MB)" -Value ($SearchQueryItem.Length/1MB) 69 | $SearchResultObject | Add-Member -MemberType NoteProperty -Name "LastWriteTime" -Value $SearchQueryItem.LastWriteTime 70 | $SearchResultObject | Add-Member -MemberType NoteProperty -Name "LastAccessTime" -Value $SearchQueryItem.LastAccessTime 71 | $SearchResult += $SearchResultObject 72 | } 73 | Write-Output $SearchResult 74 | } 75 | End 76 | { 77 | } 78 | } 79 | -------------------------------------------------------------------------------- /Functions/OS/Get-OSPerformanceMemoryCommittedBytesHigh.ps1: -------------------------------------------------------------------------------- 1 | <# 2 | .SYNOPSIS 3 | Function to determine if the committed bytes usage of one or more computers is high. 4 | .DESCRIPTION 5 | Function to determine if the committed bytes usage of one or more computers is high.This is done by analyzing 2 specific performance counters and querying the amount of RAM the computer has installed. The committed bytes usage is considered high if the counter \Memory\Committed Bytes is higher than 80% of the counter \Memory\Commit Limit (if the amount of installed RAM is less than or equal to 8GB) or if the counter \Memory\Committed Bytes is higher than the counter \Memory\Commit Limit -2GB (if the amount of installed RAM is more then 8GB). 6 | .PARAMETER ComputerName 7 | In the parameter ComputerName you can specify which computer(s) you want to target. 8 | .PARAMETER Samples 9 | In the parameter Samples you can specify how many counter samples you want to retrieve. By default this is 5. 10 | .PARAMETER SampleInterval 11 | In the parameter SampleInterval you can specify the interval in seconds between each counter sample that is retrieved. 12 | .EXAMPLE 13 | PS C:\>Get-OSPerformanceMemoryCommittedBytesHigh -ComputerName localhost 14 | 15 | This command analyzes committed bytes usage of the local computer. 16 | .EXAMPLE 17 | PS C:\>Get-OSPerformanceMemoryCommittedBytesHigh -ComputerName computer1,computer2 -Samples 10 -SampleInterval 5 18 | 19 | This command analyzes the committed bytes usage of the computer1 and computer2. It will retrieve 10 samples from each computer with an interval of 5 seconds between each sample. 20 | .NOTES 21 | Author : Ingvald Belmans 22 | Website : http://www.supersysadmin.com 23 | Version : 1.0 24 | Changelog: 25 | - 1.0 (2016-01-06) Initial version. 26 | .LINK 27 | http://www.supersysadmin.com 28 | #> 29 | function Get-OSPerformanceMemoryCommittedBytesHigh 30 | { 31 | [CmdletBinding()] 32 | Param 33 | ( 34 | [Parameter( 35 | Mandatory=$true, 36 | ValueFromPipeline=$true, 37 | ValueFromPipelineByPropertyName=$true 38 | ) 39 | ] 40 | [String[]] 41 | $ComputerName, 42 | [int] 43 | $Samples = 5, 44 | [int] 45 | $SampleInterval = 1 46 | ) 47 | Begin 48 | { 49 | } 50 | Process 51 | { 52 | Write-Verbose -Message "MemoryCommittedBytesAboveThreshold (RAM <= 8GB) is TRUE if '\Memory\Committed Bytes' > (80% x '\Memory\Commit Limit')" 53 | Write-Verbose -Message "MemoryCommittedBytesAboveThreshold (RAM > 8GB) is TRUE if '\Memory\Committed Bytes' > ('\Memory\Commit Limit' - 2GB)" 54 | Write-Verbose -Message "Getting $Samples sample(s) from $($ComputerName.Count) computer(s) with an interval of $SampleInterval seconds. Please wait..." 55 | $CounterResult = @() 56 | $ComputerCounter = 0 57 | foreach ($Computer in $ComputerName) 58 | { 59 | Write-Verbose -Message "Currently processing computer '$Computer'." 60 | $ComputerCounter++ 61 | Write-Progress -Activity "Getting counter samples of $($ComputerName.Count) computer(s)" -Status "Currently processing computer $ComputerCounter of $($ComputerName.Count)" -PercentComplete (($ComputerCounter/$ComputerName.Count)*100) -Id 1 62 | Write-Verbose -Message "Currently retrieving RAM size from computer '$Computer'." 63 | $WMIComputerSystem = Get-WmiObject -Class Win32_ComputerSystem -ComputerName $Computer 64 | $WMIComputerSystemTotalRAM = $WMIComputerSystem.TotalPhysicalMemory 65 | $WMIComputerSystemTotalRAMGB = "{0:N2}" -f ($WMIComputerSystemTotalRAM / 1GB) 66 | $SampleCounter = 0 67 | While ($SampleCounter -lt $Samples) 68 | { 69 | $SampleCounter++ 70 | Write-Progress -Activity "Getting counter samples from computer $Computer" -Status "Currently retrieving sample $SampleCounter of $Samples" -PercentComplete (($SampleCounter/$Samples)*100) -ParentId 1 71 | Write-Verbose -Message "Currently retrieving counter '\Memory\Committed Bytes' from computer '$Computer'." 72 | $CounterMemoryCommittedBytes = Get-Counter -Counter "\\$Computer\Memory\Committed Bytes" -MaxSamples 1 -SampleInterval 1 73 | $CounterMemoryCommittedBytesSample = $CounterMemoryCommittedBytes.CounterSamples 74 | $CounterMemoryCommittedBytesSampleTimestamp = $CounterMemoryCommittedBytesSample.Timestamp 75 | $CounterMemoryCommittedBytesSampleCookedValue = $CounterMemoryCommittedBytesSample.CookedValue 76 | Write-Verbose -Message "Currently retrieving counter '\Memory\Commit Limit' from computer '$Computer'." 77 | $CounterMemoryCommitLimit = Get-Counter -Counter "\\$Computer\Memory\Commit Limit" -MaxSamples 1 -SampleInterval 1 78 | $CounterMemoryCommitLimitSample = $CounterMemoryCommitLimit.CounterSamples 79 | $CounterMemoryCommitLimitSampleTimestamp = $CounterMemoryCommitLimitSample.Timestamp 80 | $CounterMemoryCommitLimitSampleCookedValue = $CounterMemoryCommitLimitSample.CookedValue 81 | if ($WMIComputerSystemTotalRAM -le 8589934592) 82 | { 83 | $CounterMemoryCommitLimitThreshold = $CounterMemoryCommitLimitSampleCookedValue * 0.8 84 | } 85 | else 86 | { 87 | $CounterMemoryCommitLimitThreshold = $CounterMemoryCommitLimitSampleCookedValue - 2147483648 88 | } 89 | if ($CounterMemoryCommittedBytesSampleCookedValue -gt $CounterMemoryCommitLimitThreshold) 90 | { 91 | $MemoryCommittedBytesAboveThreshold = $true 92 | } 93 | else 94 | { 95 | $MemoryCommittedBytesAboveThreshold = $false 96 | } 97 | $CounterResultObject = New-Object -TypeName System.Object 98 | $CounterResultObject | Add-Member -MemberType NoteProperty -Name "ComputerName" -Value $Computer 99 | $CounterResultObject | Add-Member -MemberType NoteProperty -Name "TotalRAM(Bytes)" -Value $WMIComputerSystemTotalRAM 100 | $CounterResultObject | Add-Member -MemberType NoteProperty -Name "TotalRAM(GigaBytes)" -Value $WMIComputerSystemTotalRAMGB 101 | $CounterResultObject | Add-Member -MemberType NoteProperty -Name "Timestamp(CommittedBytes)" -Value $CounterMemoryCommittedBytesSampleTimestamp 102 | $CounterResultObject | Add-Member -MemberType NoteProperty -Name "CommittedBytes" -Value $CounterMemoryCommittedBytesSampleCookedValue 103 | $CounterResultObject | Add-Member -MemberType NoteProperty -Name "Timestamp(CommitLimit)" -Value $CounterMemoryCommitLimitSampleTimestamp 104 | $CounterResultObject | Add-Member -MemberType NoteProperty -Name "CommitLimit" -Value $CounterMemoryCommitLimitSampleCookedValue 105 | $CounterResultObject | Add-Member -MemberType NoteProperty -Name "CommitLimitThreshold" -Value $CounterMemoryCommitLimitThreshold 106 | $CounterResultObject | Add-Member -MemberType NoteProperty -Name "MemoryCommittedBytesAboveThreshold" -Value $MemoryCommittedBytesAboveThreshold 107 | $CounterResult += $CounterResultObject 108 | Start-Sleep -Seconds ($SampleInterval - 1) 109 | } 110 | } 111 | Write-Output -InputObject $CounterResult 112 | } 113 | End 114 | { 115 | } 116 | } 117 | -------------------------------------------------------------------------------- /Functions/OS/Get-OSPerformanceMemoryPagingFileHigh.ps1: -------------------------------------------------------------------------------- 1 | <# 2 | .SYNOPSIS 3 | Function to determine if the paging file usage of one or more computers is high. 4 | .DESCRIPTION 5 | Function to determine if the paging file usage of one or more computers is high. The pool nonpaged bytes usage is considered high if the counter \Paging File(*)\% Usage is higher than 80%. 6 | .PARAMETER ComputerName 7 | In the parameter ComputerName you can specify which computer(s) you want to target. 8 | .PARAMETER Samples 9 | In the parameter Samples you can specify how many counter samples you want to retrieve. By default this is 5. 10 | .PARAMETER SampleInterval 11 | In the parameter SampleInterval you can specify the interval in seconds between each counter sample that is retrieved. 12 | .PARAMETER CounterPagingFileUsageTreshold 13 | In the parameter CounterPagingFileUsageTreshold you can specify the treshold for the counter \Paging File(*)\% Usage. By default this is 80 and this should normally not be changed. 14 | .EXAMPLE 15 | PS C:\>Get-OSPerformanceMemoryPagingFileHigh -ComputerName localhost 16 | 17 | This command analyzes the paging file usage usage of the local computer. 18 | .EXAMPLE 19 | PS C:\>Get-OSPerformanceMemoryPagingFileHigh -ComputerName computer1,computer2 -Samples 10 -SampleInterval 5 20 | 21 | This command analyzes the paging file usage of computer1 and computer2. It will retrieve 10 samples from each computer with an interval of 5 seconds between each sample. 22 | .NOTES 23 | Author : Ingvald Belmans 24 | Website : http://www.supersysadmin.com 25 | Version : 1.1 26 | Changelog: 27 | - 1.0 (2016-01-08) Initial version. 28 | - 1.1 (2016-01-08) Removed some unnecessary code. 29 | .LINK 30 | http://www.supersysadmin.com 31 | #> 32 | function Get-OSPerformanceMemoryPagingFileHigh 33 | { 34 | [CmdletBinding()] 35 | Param 36 | ( 37 | [Parameter( 38 | Mandatory=$true, 39 | ValueFromPipeline=$true, 40 | ValueFromPipelineByPropertyName=$true 41 | ) 42 | ] 43 | [String[]] 44 | $ComputerName, 45 | [int] 46 | $Samples = 5, 47 | [int] 48 | $SampleInterval = 1, 49 | [int] 50 | $CounterPagingFileUsageTreshold = 80 51 | ) 52 | Begin 53 | { 54 | } 55 | Process 56 | { 57 | Write-Verbose -Message "MemoryPageFileAboveThreshold is TRUE if '\Paging File(*)\% Usage' > 80%" 58 | Write-Verbose -Message "Getting $Samples sample(s) from $($ComputerName.Count) computer(s) with an interval of $SampleInterval seconds. Please wait..." 59 | $CounterResult = @() 60 | $ComputerCounter = 0 61 | foreach ($Computer in $ComputerName) 62 | { 63 | Write-Verbose -Message "Currently processing computer '$Computer'." 64 | $ComputerCounter++ 65 | Write-Progress -Activity "Getting counter samples of $($ComputerName.Count) computer(s)" -Status "Currently processing computer $ComputerCounter of $($ComputerName.Count)" -PercentComplete (($ComputerCounter/$ComputerName.Count)*100) -Id 1 66 | $SampleCounter = 0 67 | While ($SampleCounter -lt $Samples) 68 | { 69 | $SampleCounter++ 70 | Write-Progress -Activity "Getting counter samples from computer $Computer" -Status "Currently retrieving sample $SampleCounter of $Samples" -PercentComplete (($SampleCounter/$Samples)*100) -ParentId 1 71 | Write-Verbose -Message "Currently retrieving counter '\Paging File(*)\% Usage' from computer '$Computer'." 72 | $CounterPagingFileUsage = Get-Counter -Counter "\\$Computer\Paging File(*)\% Usage" -MaxSamples 1 -SampleInterval 1 73 | $CounterPagingFileUsageSample = $CounterPagingFileUsage.CounterSamples | Where-Object -FilterScript {$_.InstanceName -eq "_total"} 74 | $CounterPagingFileUsageSampleTimestamp = $CounterPagingFileUsageSample.Timestamp 75 | $CounterPagingFileUsageSampleCookedValue = "{0:N2}" -f ($CounterPagingFileUsageSample.CookedValue) 76 | if ($CounterPagingFileUsageSampleCookedValue -gt $CounterPagingFileUsageTreshold) 77 | { 78 | $MemoryPageFileAboveThreshold = $true 79 | } 80 | else 81 | { 82 | $MemoryPageFileAboveThreshold = $false 83 | } 84 | $CounterResultObject = New-Object -TypeName System.Object 85 | $CounterResultObject | Add-Member -MemberType NoteProperty -Name "ComputerName" -Value $Computer 86 | $CounterResultObject | Add-Member -MemberType NoteProperty -Name "Timestamp" -Value $CounterPagingFileUsageSampleTimestamp 87 | $CounterResultObject | Add-Member -MemberType NoteProperty -Name "PageFileUsage(%)" -Value $CounterPagingFileUsageSampleCookedValue 88 | $CounterResultObject | Add-Member -MemberType NoteProperty -Name "MemoryPageFileAboveThreshold" -Value $MemoryPageFileAboveThreshold 89 | $CounterResult += $CounterResultObject 90 | Start-Sleep -Seconds ($SampleInterval - 1) 91 | } 92 | } 93 | Write-Output -InputObject $CounterResult 94 | } 95 | End 96 | { 97 | } 98 | } 99 | -------------------------------------------------------------------------------- /Functions/OS/Get-OSPerformanceMemoryPoolNonPagedBytesHigh.ps1: -------------------------------------------------------------------------------- 1 | <# 2 | .SYNOPSIS 3 | Function to determine if the pool nonpaged bytes usage of one or more computers is high. 4 | .DESCRIPTION 5 | Function to determine if the pool nonpaged bytes usage of one or more computers is high. The pool nonpaged bytes usage is considered high if the counter \Memory\Pool Nonpaged Bytes is higher than 80% of 75% of the RAM size. 6 | .PARAMETER ComputerName 7 | In the parameter ComputerName you can specify which computer(s) you want to target. 8 | .PARAMETER Samples 9 | In the parameter Samples you can specify how many counter samples you want to retrieve. By default this is 5. 10 | .PARAMETER SampleInterval 11 | In the parameter SampleInterval you can specify the interval in seconds between each counter sample that is retrieved. 12 | .EXAMPLE 13 | PS C:\>Get-OSPerformanceMemoryPoolNonPagedBytesHigh -ComputerName localhost 14 | 15 | This command analyzes pool nonpaged bytes usage of the local computer. 16 | .EXAMPLE 17 | PS C:\>Get-OSPerformanceMemoryPoolNonPagedBytesHigh -ComputerName computer1,computer2 -Samples 10 -SampleInterval 5 18 | 19 | This command analyzes pool nonpaged bytes usage of the computer1 and computer2. It will retrieve 10 samples from each computer with an interval of 5 seconds between each sample. 20 | .NOTES 21 | Author : Ingvald Belmans 22 | Website : http://www.supersysadmin.com 23 | Version : 1.0 24 | Changelog: 25 | - 1.0 (2016-01-06) Initial version. 26 | .LINK 27 | http://www.supersysadmin.com 28 | #> 29 | function Get-OSPerformanceMemoryPoolNonPagedBytesHigh 30 | { 31 | [CmdletBinding()] 32 | Param 33 | ( 34 | [Parameter( 35 | Mandatory=$true, 36 | ValueFromPipeline=$true, 37 | ValueFromPipelineByPropertyName=$true 38 | ) 39 | ] 40 | [String[]] 41 | $ComputerName, 42 | [int] 43 | $Samples = 5, 44 | [int] 45 | $SampleInterval = 1 46 | ) 47 | Begin 48 | { 49 | } 50 | Process 51 | { 52 | Write-Verbose -Message "MemoryPoolNonPagedBytesAboveThreshold is TRUE if '\Memory\Pool Nonpaged Bytes' > (80% x (75% x RAM Size))" 53 | Write-Verbose -Message "Getting $Samples sample(s) from $($ComputerName.Count) computer(s) with an interval of $SampleInterval seconds. Please wait..." 54 | $CounterResult = @() 55 | $ComputerCounter = 0 56 | foreach ($Computer in $ComputerName) 57 | { 58 | Write-Verbose -Message "Currently processing computer '$Computer'." 59 | $ComputerCounter++ 60 | Write-Progress -Activity "Getting counter samples of $($ComputerName.Count) computer(s)" -Status "Currently processing computer $ComputerCounter of $($ComputerName.Count)" -PercentComplete (($ComputerCounter/$ComputerName.Count)*100) -Id 1 61 | Write-Verbose -Message "Currently retrieving RAM size from computer '$Computer'." 62 | $WMIComputerSystem = Get-WmiObject -Class Win32_ComputerSystem -ComputerName $Computer 63 | $WMIComputerSystemTotalRAM = $WMIComputerSystem.TotalPhysicalMemory 64 | $MemoryPoolNonPagedBytesThreshold = 0.80 * (0.75 * $WMIComputerSystemTotalRAM) 65 | $SampleCounter = 0 66 | While ($SampleCounter -lt $Samples) 67 | { 68 | $SampleCounter++ 69 | Write-Progress -Activity "Getting counter samples from computer $Computer" -Status "Currently retrieving sample $SampleCounter of $Samples" -PercentComplete (($SampleCounter/$Samples)*100) -ParentId 1 70 | Write-Verbose -Message "Currently retrieving counter 'Memory\Pool Nonpaged Bytes' from computer '$Computer'." 71 | $CounterMemoryPoolNonPagedBytes = Get-Counter -Counter "\\$Computer\Memory\Pool Nonpaged Bytes" -MaxSamples 1 -SampleInterval 1 72 | $CounterMemoryPoolNonPagedBytesSample = $CounterMemoryPoolNonPagedBytes.CounterSamples 73 | $CounterMemoryPoolNonPagedBytesSampleTimestamp = $CounterMemoryPoolNonPagedBytesSample.Timestamp 74 | $CounterMemoryPoolNonPagedBytesSampleCookedValue = $CounterMemoryPoolNonPagedBytesSample.CookedValue 75 | if ($CounterMemoryPoolNonPagedBytesSampleCookedValue -gt $MemoryPoolNonPagedBytesThreshold) 76 | { 77 | $MemoryPoolNonPagedBytesAboveThreshold = $true 78 | } 79 | else 80 | { 81 | $MemoryPoolNonPagedBytesAboveThreshold = $false 82 | } 83 | 84 | $CounterResultObject = New-Object -TypeName System.Object 85 | $CounterResultObject | Add-Member -MemberType NoteProperty -Name "ComputerName" -Value $Computer 86 | $CounterResultObject | Add-Member -MemberType NoteProperty -Name "Timestamp(PoolNonPagedBytes)" -Value $CounterMemoryPoolNonPagedBytesSampleTimestamp 87 | $CounterResultObject | Add-Member -MemberType NoteProperty -Name "MemoryPoolNonPagedBytes" -Value $CounterMemoryPoolNonPagedBytesSampleCookedValue 88 | $CounterResultObject | Add-Member -MemberType NoteProperty -Name "TotalRAM(Bytes)" -Value $WMIComputerSystemTotalRAM 89 | $CounterResultObject | Add-Member -MemberType NoteProperty -Name "MemoryPoolNonPagedBytesThreshold" -Value $MemoryPoolNonPagedBytesThreshold 90 | $CounterResultObject | Add-Member -MemberType NoteProperty -Name "MemoryPoolNonPagedBytesAboveThreshold" -Value $MemoryPoolNonPagedBytesAboveThreshold 91 | $CounterResult += $CounterResultObject 92 | Start-Sleep -Seconds ($SampleInterval - 1) 93 | } 94 | } 95 | Write-Output -InputObject $CounterResult 96 | } 97 | End 98 | { 99 | } 100 | } 101 | -------------------------------------------------------------------------------- /Functions/OS/Get-OSPerformanceProcessorUsageHigh.ps1: -------------------------------------------------------------------------------- 1 | <# 2 | .SYNOPSIS 3 | Function to determine if the processor usage of one or more computers is high. 4 | .DESCRIPTION 5 | Function to determine if the processor usage of one or more computers is high. This is done by analyzing 3 specific performance counters. The processor usage is considered high if the counter \Processor(_Total)\% Processor Time is higher than 90 AND the counter \System\Context Switches/sec is higher than 20000 AND the counter \System\Processor Queue Length is higher than 2. 6 | .PARAMETER ComputerName 7 | In the parameter ComputerName you can specify which computer(s) you want to target. 8 | .PARAMETER Samples 9 | In the parameter Samples you can specify how many counter samples you want to retrieve. By default this is 5. 10 | .PARAMETER SampleInterval 11 | In the parameter SampleInterval you can specify the interval in seconds between each counter sample that is retrieved. 12 | .PARAMETER CounterProcessorPercentageProcessorTimeThreshold 13 | In the parameter CounterProcessorPercentageProcessorTimeThreshold you can specify the treshold for the counter \Processor(_Total)\% Processor Time. By default this is 90 and this should normally not be changed. 14 | .PARAMETER CounterSystemContextSwitchesTreshold 15 | In the parameter CounterSystemContextSwitchesTreshold you can specify the treshold for the counter \System\Context Switches/sec. By default this is 20000 and this should normally not be changed. 16 | .PARAMETER CounterSystemProcessorQueueLengthTreshold 17 | In the parameter CounterSystemProcessorQueueLengthTreshold you can specify the treshold for the counter \System\Processor Queue Length. By default this is 2 and this should normally not be changed. 18 | .EXAMPLE 19 | PS C:\>Get-OSPerformanceProcessorUsageHigh -ComputerName localhost 20 | 21 | This command analyzes the processor usage of the local computer. 22 | .EXAMPLE 23 | PS C:\>Get-OSPerformanceProcessorUsageHigh -ComputerName computer1,computer2 -Samples 10 -SampleInterval 5 24 | 25 | This command analyzes the processor usage of the computer1 and computer2. It will retrieve 10 samples from each computer with an interval of 5 seconds between each sample. 26 | .NOTES 27 | Author : Ingvald Belmans 28 | Website : http://www.supersysadmin.com 29 | Version : 1.0 30 | Changelog: 31 | - 1.0 (2016-01-05) Initial version. 32 | .LINK 33 | http://www.supersysadmin.com 34 | #> 35 | function Get-OSPerformanceProcessorUsageHigh 36 | { 37 | [CmdletBinding()] 38 | Param 39 | ( 40 | [Parameter( 41 | Mandatory=$true, 42 | ValueFromPipeline=$true, 43 | ValueFromPipelineByPropertyName=$true 44 | ) 45 | ] 46 | [String[]] 47 | $ComputerName, 48 | [int] 49 | $Samples = 5, 50 | [int] 51 | $SampleInterval = 1, 52 | [int] 53 | $CounterProcessorPercentageProcessorTimeThreshold = 90, 54 | [int] 55 | $CounterSystemContextSwitchesTreshold = 20000, 56 | [int] 57 | $CounterSystemProcessorQueueLengthTreshold = 2 58 | ) 59 | Begin 60 | { 61 | } 62 | Process 63 | { 64 | Write-Verbose -Message "ProcessorUsageHighAboveThreshold is TRUE if '\Processor(_Total)\% Processor Time' > 90 AND '\System\Context Switches/sec' > 20000 AND '\System\Processor Queue Length' > 2." 65 | Write-Verbose -Message "Getting $Samples sample(s) from $($ComputerName.Count) computer(s) with an interval of $SampleInterval seconds. Please wait..." 66 | $CounterResult = @() 67 | $ComputerCounter = 0 68 | foreach ($Computer in $ComputerName) 69 | { 70 | Write-Verbose -Message "Currently processing computer '$Computer'." 71 | $ComputerCounter++ 72 | Write-Progress -Activity "Getting counter samples of $($ComputerName.Count) computer(s)" -Status "Currently processing computer $ComputerCounter of $($ComputerName.Count)" -PercentComplete (($ComputerCounter/$ComputerName.Count)*100) -Id 1 73 | $SampleCounter = 0 74 | While ($SampleCounter -lt $Samples) 75 | { 76 | $SampleCounter++ 77 | Write-Progress -Activity "Getting counter samples from computer $Computer" -Status "Currently retrieving sample $SampleCounter of $Samples" -PercentComplete (($SampleCounter/$Samples)*100) -ParentId 1 78 | Write-Verbose -Message "Currently retrieving counter '\Processor(_Total)\% Processor Time' from computer '$Computer'." 79 | $CounterProcessorPercentageProcessorTime = Get-Counter -Counter "\\$Computer\Processor(_Total)\% Processor Time" -MaxSamples 1 -SampleInterval 1 80 | $CounterProcessorPercentageProcessorTimeSample = $CounterProcessorPercentageProcessorTime.CounterSamples 81 | $CounterProcessorPercentageProcessorTimeSampleTimeStamp = $CounterProcessorPercentageProcessorTimeSample.TimeStamp 82 | $CounterProcessorPercentageProcessorTimeSampleCookedValue = $CounterProcessorPercentageProcessorTimeSample.CookedValue 83 | Write-Verbose -Message "Currently retrieving counter '\System\Context Switches/sec' from computer '$Computer'." 84 | $CounterSystemContextSwitches = Get-Counter -Counter "\\$Computer\System\Context Switches/sec" -MaxSamples 1 -SampleInterval 1 85 | $CounterSystemContextSwitchesSample = $CounterSystemContextSwitches.CounterSamples 86 | $CounterSystemContextSwitchesSampleTimeStamp = $CounterSystemContextSwitchesSample.TimeStamp 87 | $CounterSystemContextSwitchesSampleCookedValue = $CounterSystemContextSwitchesSample.CookedValue 88 | Write-Verbose -Message "Currently retrieving counter '\System\Processor Queue Length' from computer '$Computer'." 89 | $CounterSystemProcessorQueueLength = Get-Counter -Counter "\\$Computer\System\Processor Queue Length" -MaxSamples 1 -SampleInterval 1 90 | $CounterSystemProcessorQueueLengthSample = $CounterSystemProcessorQueueLength.CounterSamples 91 | $CounterSystemProcessorQueueLengthSampleTimeStamp = $CounterSystemProcessorQueueLengthSample.TimeStamp 92 | $CounterSystemProcessorQueueLengthSampleCookedValue = $CounterSystemProcessorQueueLengthSample.CookedValue 93 | Write-Verbose -Message "Currently calculating ProcessorUsageHighAboveThreshold for computer '$Computer'." 94 | if (($CounterProcessorPercentageProcessorTimeSampleCookedValue -gt $CounterProcessorPercentageProcessorTimeThreshold) -and ($CounterSystemContextSwitchesSampleCookedValue -gt $CounterSystemContextSwitchesTreshold) -and ($CounterSystemProcessorQueueLengthSampleCookedValue -gt $CounterSystemProcessorQueueLengthTreshold)) 95 | { 96 | $ProcessorUsageHighAboveThreshold = $true 97 | } 98 | else 99 | { 100 | $ProcessorUsageHighAboveThreshold = $false 101 | } 102 | $CounterResultObject = New-Object -TypeName System.Object 103 | $CounterResultObject | Add-Member -MemberType NoteProperty -Name "ComputerName" -Value $Computer 104 | $CounterResultObject | Add-Member -MemberType NoteProperty -Name "Timestamp(%ProcessorTime)" -Value $CounterProcessorPercentageProcessorTimeSampleTimeStamp 105 | $CounterResultObject | Add-Member -MemberType NoteProperty -Name "%ProcessorTime" -Value $CounterProcessorPercentageProcessorTimeSampleCookedValue 106 | $CounterResultObject | Add-Member -MemberType NoteProperty -Name "Timestamp(ContextSwitches/sec)" -Value $CounterSystemContextSwitchesSampleTimeStamp 107 | $CounterResultObject | Add-Member -MemberType NoteProperty -Name "ContextSwitches/sec" -Value $CounterSystemContextSwitchesSampleCookedValue 108 | $CounterResultObject | Add-Member -MemberType NoteProperty -Name "Timestamp(ProcessorQueueLength)" -Value $CounterSystemProcessorQueueLengthSampleTimeStamp 109 | $CounterResultObject | Add-Member -MemberType NoteProperty -Name "ProcessorQueueLength" -Value $CounterSystemProcessorQueueLengthSampleCookedValue 110 | $CounterResultObject | Add-Member -MemberType NoteProperty -Name "ProcessorUsageHighAboveThreshold" -Value $ProcessorUsageHighAboveThreshold 111 | $CounterResult += $CounterResultObject 112 | Start-Sleep -Seconds ($SampleInterval - 1) 113 | } 114 | } 115 | Write-Output -InputObject $CounterResult 116 | } 117 | End 118 | { 119 | } 120 | } 121 | -------------------------------------------------------------------------------- /Functions/OS/Get-OSUptime.ps1: -------------------------------------------------------------------------------- 1 | <# 2 | .SYNOPSIS 3 | Function to get the uptime of one or more computers. 4 | .DESCRIPTION 5 | Function to get the uptime of one or more computers. 6 | .PARAMETER ComputerName 7 | In the parameter ComputerName you can specify which computer(s) you want to target. 8 | .EXAMPLE 9 | PS C:\>Get-OSUptime -ComputerName computer1 10 | 11 | This command retrieves the uptime of computer1. 12 | .EXAMPLE 13 | PS C:\>Get-Content -Path C:\computers.txt | Get-OSUptime | Export-Csv -Path C:\uptime.csv 14 | 15 | This command reads a list of computernames from a .txt file, then retrieves their uptime and finally exports the result to a .csv file. 16 | .NOTES 17 | Author : Ingvald Belmans 18 | Website : http://www.supersysadmin.com 19 | Version : 1.0 20 | Changelog: 21 | - 1.0 (2015-08-23) Initial version. 22 | .LINK 23 | http://www.supersysadmin.com 24 | #> 25 | function Get-OSUptime 26 | { 27 | [CmdletBinding()] 28 | Param 29 | ( 30 | [Parameter( 31 | Mandatory=$true, 32 | ValueFromPipeline=$true, 33 | ValueFromPipelineByPropertyName=$true 34 | ) 35 | ] 36 | [String[]] 37 | $ComputerName 38 | ) 39 | 40 | Begin 41 | { 42 | $CurrentTime = Get-Date 43 | } 44 | Process 45 | { 46 | $UptimeResult = @() 47 | foreach ($Computer in $ComputerName) 48 | { 49 | $WMIOS = Get-WmiObject -Class Win32_OperatingSystem -ComputerName $Computer 50 | $BootTime = [Management.ManagementDateTimeConverter]::ToDateTime($WMIOS.LastBootUpTime) 51 | $Uptime = $CurrentTime - $BootTime 52 | $UptimeResultObject = New-Object -TypeName System.Object 53 | $UptimeResultObject | Add-Member -MemberType NoteProperty -Name "ComputerName" -Value $WMIOS.PSComputerName 54 | $UptimeResultObject | Add-Member -MemberType NoteProperty -Name "BootTime" -Value $BootTime.DateTime 55 | $UptimeResultObject | Add-Member -MemberType NoteProperty -Name "UptimeDays" -Value $Uptime.Days 56 | $UptimeResultObject | Add-Member -MemberType NoteProperty -Name "UptimeHours" -Value $Uptime.Hours 57 | $UptimeResultObject | Add-Member -MemberType NoteProperty -Name "UptimeMinutes" -Value $Uptime.Minutes 58 | $UptimeResultObject | Add-Member -MemberType NoteProperty -Name "UptimeSeconds" -Value $Uptime.Seconds 59 | $UptimeResult += $UptimeResultObject 60 | } 61 | Write-Output $UptimeResult 62 | } 63 | End 64 | { 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /Functions/OS/Start-OSAutomaticServices.ps1: -------------------------------------------------------------------------------- 1 | <# 2 | .SYNOPSIS 3 | Function to start all stopped Automatic services on one or more computers. 4 | .DESCRIPTION 5 | Function to start all stopped Automatic services on one or more computers. 6 | .PARAMETER ComputerName 7 | In the parameter ComputerName you can specific which computer(s) you want to target. 8 | .PARAMETER CheckAll 9 | By default some Automatic services which are sometimes stopped are excluded. By using the -CheckAll switch, these services are targeted as well. 10 | .PARAMETER CheckOnly 11 | By default all Automatic services which are stopped are attempted to be started. By using the -CheckOnly switch, it will just display the stopped Automatic services and will not attempt to start them. 12 | .EXAMPLE 13 | PS C:\>Start-OSAutomaticServices -ComputerName computer1 14 | 15 | This command will check the status of all Automatic services on computer1 and will attempt to start the ones that are stopped. 16 | .NOTES 17 | Author : Ingvald Belmans 18 | Website : http://www.supersysadmin.com 19 | Version : 1.0 20 | Changelog: 21 | - 1.0 (2015-08-30) Initial version. 22 | .LINK 23 | http://www.supersysadmin.com 24 | #> 25 | function Start-OSAutomaticServices 26 | { 27 | [CmdletBinding()] 28 | Param 29 | ( 30 | [Parameter( 31 | Mandatory=$true, 32 | ValueFromPipeline=$true, 33 | ValueFromPipelineByPropertyName=$true 34 | ) 35 | ] 36 | [String[]] 37 | $ComputerName, 38 | [switch] 39 | $CheckAll, 40 | [switch] 41 | $CheckOnly 42 | ) 43 | Begin 44 | { 45 | } 46 | Process 47 | { 48 | foreach ($Computer in $ComputerName) 49 | { 50 | if ($CheckAll) 51 | { 52 | $CheckAutomaticService = Get-WmiObject -Class Win32_Service -ComputerName $Computer | Where-Object -FilterScript {$_.StartMode -eq 'Auto' -and $_.State -ne 'Running'} 53 | } 54 | else 55 | { 56 | $CheckAutomaticService = Get-WmiObject -Class Win32_Service -ComputerName $Computer | Where-Object -FilterScript {$_.StartMode -eq 'Auto' -and $_.State -ne 'Running' -and $_.Name -ne 'clr_optimization_v4.0.30319_32' -and $_.Name -ne 'clr_optimization_v4.0.30319_64'} 57 | } 58 | if ($CheckAutomaticService -eq $null) 59 | { 60 | Write-Information -MessageData "`nAll Automatic services are already started, no action was taken." -InformationAction Continue 61 | } 62 | else 63 | { 64 | Write-Information -MessageData "`nFollowing Automatic services were found stopped:" -InformationAction Continue 65 | $CheckAutomaticService | Select-Object -Property PSComputerName, Name, DisplayName, State, StartMode 66 | if ($CheckOnly) 67 | { 68 | Write-Information -MessageData "`nCheck only, rerun the command without the -CheckOnly switch to start all Automatic services that are stopped." -InformationAction Continue 69 | } 70 | else 71 | { 72 | Write-Information -MessageData "`nAttempting to start the stopped services:`n" -InformationAction Continue 73 | foreach ($StoppedService in $CheckAutomaticService) 74 | { 75 | $StartService = $StoppedService.StartService() 76 | $ServiceName = $StoppedService.Name 77 | $ServiceDisplayName = $StoppedService.DisplayName 78 | switch ($StartService.ReturnValue) 79 | { 80 | 0 { Write-Information -MessageData "[$Computer] Starting service $ServiceName ($ServiceDisplayName): The request was accepted." -InformationAction Continue} 81 | 1 { Write-Warning -Message "[$Computer] Starting service $ServiceName ($ServiceDisplayName): The request is not supported."} 82 | 2 { Write-Warning -Message "[$Computer] Starting service $ServiceName ($ServiceDisplayName): The user did not have the necessary access."} 83 | 3 { Write-Warning -Message "[$Computer] Starting service $ServiceName ($ServiceDisplayName): The service cannot be stopped because other services that are running are dependent on it."} 84 | 4 { Write-Warning -Message "[$Computer] Starting service $ServiceName ($ServiceDisplayName): The requested control code is not valid, or it is unacceptable to the service."} 85 | 5 { Write-Warning -Message "[$Computer] Starting service $ServiceName ($ServiceDisplayName): The requested control code cannot be sent to the service because the state of the service (Win32_BaseService State property) is equal to 0, 1, or 2."} 86 | 6 { Write-Warning -Message "[$Computer] Starting service $ServiceName ($ServiceDisplayName): The service has not been started."} 87 | 7 { Write-Warning -Message "[$Computer] Starting service $ServiceName ($ServiceDisplayName): The service did not respond to the start request in a timely fashion."} 88 | 8 { Write-Warning -Message "[$Computer] Starting service $ServiceName ($ServiceDisplayName): Unknown failure when starting the service."} 89 | 9 { Write-Warning -Message "[$Computer] Starting service $ServiceName ($ServiceDisplayName): The directory path to the service executable file was not found."} 90 | 10 { Write-Warning -Message "[$Computer] Starting service $ServiceName ($ServiceDisplayName): The service is already running."} 91 | 11 { Write-Warning -Message "[$Computer] Starting service $ServiceName ($ServiceDisplayName): The database to add a new service is locked."} 92 | 12 { Write-Warning -Message "[$Computer] Starting service $ServiceName ($ServiceDisplayName): A dependency this service relies on has been removed from the system."} 93 | 13 { Write-Warning -Message "[$Computer] Starting service $ServiceName ($ServiceDisplayName): The service failed to find the service needed from a dependent service."} 94 | 14 { Write-Warning -Message "[$Computer] Starting service $ServiceName ($ServiceDisplayName): The service has been disabled from the system."} 95 | 15 { Write-Warning -Message "[$Computer] Starting service $ServiceName ($ServiceDisplayName): The service does not have the correct authentication to run on the system."} 96 | 16 { Write-Warning -Message "[$Computer] Starting service $ServiceName ($ServiceDisplayName): This service is being removed from the system."} 97 | 17 { Write-Warning -Message "[$Computer] Starting service $ServiceName ($ServiceDisplayName): The service has no execution thread."} 98 | 18 { Write-Warning -Message "[$Computer] Starting service $ServiceName ($ServiceDisplayName): The service has circular dependencies when it starts."} 99 | 19 { Write-Warning -Message "[$Computer] Starting service $ServiceName ($ServiceDisplayName): A service is running under the same name."} 100 | 20 { Write-Warning -Message "[$Computer] Starting service $ServiceName ($ServiceDisplayName): The service name has invalid characters."} 101 | 21 { Write-Warning -Message "[$Computer] Starting service $ServiceName ($ServiceDisplayName): Invalid parameters have been passed to the service."} 102 | 22 { Write-Warning -Message "[$Computer] Starting service $ServiceName ($ServiceDisplayName): The account under which this service runs is either invalid or lacks the permissions to run the service."} 103 | 23 { Write-Warning -Message "[$Computer] Starting service $ServiceName ($ServiceDisplayName): The service exists in the database of services available from the system."} 104 | 24 { Write-Warning -Message "[$Computer] Starting service $ServiceName ($ServiceDisplayName): The service is currently paused in the system."} 105 | default { Write-Warning -Message "[$Computer] Starting service $ServiceName ($ServiceDisplayName): The result of the StartService command could not be determined."} } 106 | } 107 | } 108 | } 109 | } 110 | } 111 | End 112 | { 113 | } 114 | } 115 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2015 SuperSysAdmin 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 | 23 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # WindowsPowerShell 2 | PowerShell functions, scripts and modules 3 | -------------------------------------------------------------------------------- /Scripts/Console/IIS/IISSetupWebServer.ps1: -------------------------------------------------------------------------------- 1 | <# 2 | .SYNOPSIS 3 | PowerShell script to setup a complete web server on Windows Server 2012 R2. 4 | .DESCRIPTION 5 | PowerShell script to setup a complete web server on Windows Server 2012 R2. This includes installing 6 | and configuring IIS, FTP, PHP, MySQL and creating a website and FTP site. 7 | .NOTES 8 | Author : Ingvald Belmans 9 | Website : http://www.supersysadmin.com 10 | Version : 1.0 11 | Changelog: 12 | - 1.0 (2016-03-11) Initial version. 13 | .LINK 14 | http://www.supersysadmin.com 15 | #> 16 | 17 | #################################################################################################### 18 | ### 01: Create Base Directory Structure ############################################################ 19 | #################################################################################################### 20 | 21 | # Variables. 22 | $BaseDirectory = "C:\BASE" 23 | $AppDirectory = "$BaseDirectory\APP" 24 | $SrcDirectory = "$BaseDirectory\SRC" 25 | 26 | # Create BASE directory. 27 | New-Item -ItemType Directory -Path $BaseDirectory 28 | 29 | # Remove NTFS inheritance from the BASE directory. 30 | $ACL = Get-Acl -Path $BaseDirectory 31 | $ACL.SetAccessRuleProtection($True,$True) 32 | Set-Acl -Path $BaseDirectory -AclObject $ACL 33 | 34 | # Remove all NTFS permissions from the BASE directory, except Administrators. 35 | $ACL = Get-Acl -Path $BaseDirectory 36 | $ACL.Access | Where-Object -FilterScript {$_.IdentityReference -notlike "*Administrators*"} | ForEach-Object -Process {$ACL.RemoveAccessRule($_)} 37 | Set-Acl -Path $BaseDirectory -AclObject $ACL 38 | 39 | # Add SYSTEM with Full Control NTFS permissions to the BASE directory. 40 | $ACL = Get-Acl -Path $BaseDirectory 41 | $NTAccount = New-Object System.Security.Principal.NTAccount("SYSTEM") 42 | $FileSystemRights = [System.Security.AccessControl.FileSystemRights]"FullControl" 43 | $InheritanceFlags = [System.Security.AccessControl.InheritanceFlags]"ContainerInherit,ObjectInherit" 44 | $PropagationFlags = [System.Security.AccessControl.PropagationFlags]::None 45 | $AccessControlType =[System.Security.AccessControl.AccessControlType]::Allow 46 | $UserPermissions = $NTAccount,$FileSystemRights,$InheritanceFlags,$PropagationFlags,$AccessControlType 47 | $AccessRule = New-Object -TypeName System.Security.AccessControl.FileSystemAccessRule -ArgumentList $UserPermissions 48 | $ACL.SetAccessRule($AccessRule) 49 | $ACL | Set-Acl -Path $BaseDirectory 50 | 51 | # Create the APP and SRC directories. 52 | New-Item -ItemType Directory -Path $AppDirectory 53 | New-Item -ItemType Directory -Path $SrcDirectory 54 | 55 | #################################################################################################### 56 | ### 02: Install IIS/FTP ############################################################################ 57 | #################################################################################################### 58 | 59 | # Variables. 60 | $IISDirectory = "$AppDirectory\IIS" 61 | $URLRewriteDownloadLocation = "http://go.microsoft.com/?linkid=9722532" 62 | $URLRewritePackage = "rewrite_2.0_rtw_x64.msi" 63 | 64 | # Install IIS. 65 | Install-WindowsFeature -Name Web-Default-Doc, Web-Dir-Browsing, Web-Http-Errors, Web-Static-Content, Web-Http-Redirect, Web-Http-Logging,` 66 | Web-Stat-Compression, Web-Dyn-Compression, Web-Filtering, Web-Basic-Auth, Web-Net-Ext, Web-Net-Ext45, Web-Asp-Net, Web-Asp-Net45,` 67 | Web-CGI, Web-ISAPI-Ext, Web-ISAPI-Filter, Web-Mgmt-Console 68 | 69 | # Install FTP Server. 70 | Install-WindowsFeature -Name Web-Ftp-Server, Web-Ftp-Service 71 | 72 | # Create IIS directory. 73 | New-Item -ItemType Directory -Path $IISDirectory 74 | 75 | # Download URL Rewrite. 76 | Invoke-WebRequest -Uri $URLRewriteDownloadLocation -OutFile $SrcDirectory\$URLRewritePackage 77 | 78 | # Install URL Rewrite. 79 | Start-Process -FilePath "$SrcDirectory\rewrite_2.0_rtw_x64.msi" -ArgumentList "/qn" -Wait 80 | 81 | # Remove Default Web Site. 82 | Remove-Website -Name "Default Web Site" 83 | 84 | # Remove default Application Pools. 85 | Remove-WebAppPool -Name ".NET v2.0" 86 | Remove-WebAppPool -Name ".NET v2.0 Classic" 87 | Remove-WebAppPool -Name ".NET v4.5" 88 | Remove-WebAppPool -Name ".NET v4.5 Classic" 89 | Remove-WebAppPool -Name "Classic .NET AppPool" 90 | Remove-WebAppPool -Name "DefaultAppPool" 91 | 92 | #################################################################################################### 93 | ### 03: Install PHP ################################################################################ 94 | #################################################################################################### 95 | 96 | # Variables. 97 | $VisualStudioRedistributableDownloadLocation = "https://download.microsoft.com/download/9/3/F/93FCF1E7-E6A4-478B-96E7-D4B285925B00/vc_redist.x64.exe" 98 | $VisualStudioRedistributablePackage = "vc_redist.x64.exe" 99 | $PHPDirectory = "$AppDirectory\PHP" 100 | $PHPSessionDirectory = "$PHPDirectory\session" 101 | $PHPUploadDirectory = "$PHPDirectory\upload" 102 | $PHPLogDirectory = "$PHPDirectory\log" 103 | $PHPUserGroup = "PHP Users" 104 | $PHPDownloadLocation = "http://windows.php.net/downloads/releases/php-7.0.4-nts-Win32-VC14-x86.zip" 105 | $PHPPackage = "php-7.0.4-nts-Win32-VC14-x86.zip" 106 | $PHPDefaultDocument = "index.php" 107 | $PHPErrorLogFile = "error.log" 108 | 109 | # Download Visual C++ Redistributable for Visual Studio 2015 x64. 110 | Invoke-WebRequest -Uri $VisualStudioRedistributableDownloadLocation -OutFile $SrcDirectory\$VisualStudioRedistributablePackage 111 | 112 | # Install Visual C++ Redistributable for Visual Studio 2015 x64. 113 | Start-Process -FilePath $SrcDirectory\$VisualStudioRedistributablePackage -ArgumentList "/q /norestart" -Wait 114 | 115 | # Create the PHP directory structure. 116 | New-Item -ItemType Directory -Path $PHPDirectory 117 | New-Item -ItemType Directory -Path $PHPSessionDirectory 118 | New-Item -ItemType Directory -Path $PHPUploadDirectory 119 | New-Item -ItemType Directory -Path $PHPLogDirectory 120 | 121 | # Create the PHP Users local Windows group. 122 | $LocalAccountDB = [ADSI]"WinNT://$env:ComputerName" 123 | $CreateGroupPHPUsers = $LocalAccountDB.Create("Group","$PHPUserGroup") 124 | $CreateGroupPHPUsers.SetInfo() 125 | $CreateGroupPHPUsers.Description = "Members of this group can use PHP on their website" 126 | $CreateGroupPHPUsers.SetInfo() 127 | 128 | # Set Read/Execute NTFS permissions for the group PHP Users on the PHP directory. 129 | $ACL = Get-Acl -Path $PHPDirectory 130 | $NTAccount = New-Object System.Security.Principal.NTAccount("$PHPUserGroup") 131 | $FileSystemRights = [System.Security.AccessControl.FileSystemRights]"ReadAndExecute" 132 | $InheritanceFlags = [System.Security.AccessControl.InheritanceFlags]"ContainerInherit,ObjectInherit" 133 | $PropagationFlags = [System.Security.AccessControl.PropagationFlags]::None 134 | $AccessControlType =[System.Security.AccessControl.AccessControlType]::Allow 135 | $UserPermissions = $NTAccount,$FileSystemRights,$InheritanceFlags,$PropagationFlags,$AccessControlType 136 | $AccessRule = New-Object -TypeName System.Security.AccessControl.FileSystemAccessRule -ArgumentList $UserPermissions 137 | $ACL.SetAccessRule($AccessRule) 138 | $ACL | Set-Acl -Path $PHPDirectory 139 | 140 | # Set Modify NTFS permissions for PHP Users on the session directory. 141 | $ACL = Get-Acl -Path $PHPSessionDirectory 142 | $NTAccount = New-Object System.Security.Principal.NTAccount("$PHPUserGroup") 143 | $FileSystemRights = [System.Security.AccessControl.FileSystemRights]"Modify" 144 | $InheritanceFlags = [System.Security.AccessControl.InheritanceFlags]"ContainerInherit,ObjectInherit" 145 | $PropagationFlags = [System.Security.AccessControl.PropagationFlags]::None 146 | $AccessControlType =[System.Security.AccessControl.AccessControlType]::Allow 147 | $UserPermissions = $NTAccount,$FileSystemRights,$InheritanceFlags,$PropagationFlags,$AccessControlType 148 | $AccessRule = New-Object -TypeName System.Security.AccessControl.FileSystemAccessRule -ArgumentList $UserPermissions 149 | $ACL.SetAccessRule($AccessRule) 150 | $ACL | Set-Acl -Path $PHPSessionDirectory 151 | 152 | # Set Modify NTFS permissions for PHP Users on the upload directory. 153 | $ACL = Get-Acl -Path $PHPUploadDirectory 154 | $NTAccount = New-Object System.Security.Principal.NTAccount("$PHPUserGroup") 155 | $FileSystemRights = [System.Security.AccessControl.FileSystemRights]"Modify" 156 | $InheritanceFlags = [System.Security.AccessControl.InheritanceFlags]"ContainerInherit,ObjectInherit" 157 | $PropagationFlags = [System.Security.AccessControl.PropagationFlags]::None 158 | $AccessControlType =[System.Security.AccessControl.AccessControlType]::Allow 159 | $UserPermissions = $NTAccount,$FileSystemRights,$InheritanceFlags,$PropagationFlags,$AccessControlType 160 | $AccessRule = New-Object -TypeName System.Security.AccessControl.FileSystemAccessRule -ArgumentList $UserPermissions 161 | $ACL.SetAccessRule($AccessRule) 162 | $ACL | Set-Acl -Path $PHPUploadDirectory 163 | 164 | # Set Modify NTFS permissions for PHP Users on the log directory. 165 | $ACL = Get-Acl -Path $PHPLogDirectory 166 | $NTAccount = New-Object System.Security.Principal.NTAccount("$PHPUserGroup") 167 | $FileSystemRights = [System.Security.AccessControl.FileSystemRights]"Modify" 168 | $InheritanceFlags = [System.Security.AccessControl.InheritanceFlags]"ContainerInherit,ObjectInherit" 169 | $PropagationFlags = [System.Security.AccessControl.PropagationFlags]::None 170 | $AccessControlType =[System.Security.AccessControl.AccessControlType]::Allow 171 | $UserPermissions = $NTAccount,$FileSystemRights,$InheritanceFlags,$PropagationFlags,$AccessControlType 172 | $AccessRule = New-Object -TypeName System.Security.AccessControl.FileSystemAccessRule -ArgumentList $UserPermissions 173 | $ACL.SetAccessRule($AccessRule) 174 | $ACL | Set-Acl -Path $PHPLogDirectory 175 | 176 | # Create the PHP log file. 177 | New-Item -ItemType File -Path "$PHPLogDirectory\$PHPErrorLogFile" 178 | 179 | # Download the PHP Non Thread Safe .zip package (x64). 180 | Invoke-WebRequest -Uri $PHPDownloadLocation -OutFile "$SrcDirectory\$PHPPackage" 181 | 182 | # Extract the .zip file to the PHP directory. In PowerShell 5 (Windows 10, Windows Server 2016) we have the Expand-Archive cmdlet for this, 183 | # but since there is no production version yet of PowerShell 5 for previous operating systems, we use .NET for this. 184 | Add-Type -AssemblyName "system.io.compression.filesystem" 185 | [io.compression.zipfile]::ExtractToDirectory("$SrcDirectory\$PHPPackage", $PHPDirectory) 186 | 187 | # Add the PHP installation directory to the Path environment variable. 188 | $CurrentPath = (Get-ItemProperty -Path 'Registry::HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Session Manager\Environment' -Name PATH).PATH 189 | $NewPath = $CurrentPath + ";$PHPDirectory\" 190 | Set-ItemProperty -Path 'Registry::HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Session Manager\Environment' -Name PATH -Value $NewPath 191 | 192 | # Create a Handler Mapping for PHP. 193 | New-WebHandler -Name "PHPFastCGI" -Path "*.php" -Modules FastCgiModule -ScriptProcessor "$PHPDirectory\php-cgi.exe" -Verb 'GET,HEAD,POST' -ResourceType Either 194 | 195 | # Configure FastCGI Settings for PHP. 196 | Add-WebConfiguration -Filter /system.webServer/fastCgi -PSPath IIS:\ -Value @{fullpath="$PHPDirectory\php-cgi.exe"} 197 | 198 | # Add index.php to the Default Documents. 199 | Add-WebConfiguration -Filter /system.webServer/defaultDocument/files -PSPath IIS:\ -Value @{value="$PHPDefaultDocument"} 200 | 201 | # Create php.ini and configure values. 202 | $PHPIniBaseFile = Get-Content -Path "$PHPDirectory\php.ini-production" 203 | $PHPIniValues = @{'max_execution_time = 30' = 'max_execution_time = 600'; 204 | 'max_input_time = 60' = 'max_input_time = 600'; 205 | '; max_input_vars = 1000' = "max_input_vars = 2000"; 206 | 'memory_limit = 128M' = "memory_limit = 256M"; 207 | ';error_log = php_errors.log' = 'error_log = "C:\DATA\APP\PHP\log\error.log"'; 208 | 'post_max_size = 8M' = 'post_max_size = 128M'; 209 | '; extension_dir = "ext"' = 'extension_dir = "C:\DATA\APP\PHP\ext"'; 210 | ';cgi.force_redirect = 1' = 'cgi.force_redirect = 0'; 211 | ';cgi.fix_pathinfo=1' = 'cgi.fix_pathinfo = 1'; 212 | ';fastcgi.impersonate = 1' = 'fastcgi.impersonate = 1'; 213 | ';upload_tmp_dir =' = 'upload_tmp_dir = "C:\DATA\APP\PHP\upload"'; 214 | 'upload_max_filesize = 2M' = 'upload_max_filesize = 128M'; 215 | ';extension=php_bz2.dll' = 'extension=php_bz2.dll'; 216 | ';extension=php_curl.dll' = 'extension=php_curl.dll'; 217 | ';extension=php_gd2.dll' = 'extension=php_gd2.dll'; 218 | ';extension=php_mbstring.dll' = 'extension=php_mbstring.dll'; 219 | ';extension=php_mysqli.dll' = 'extension=php_mysqli.dll'; 220 | ';date.timezone =' = 'date.timezone = Europe/Brussels'; 221 | ';session.save_path = "/tmp"' = 'session.save_path = "C:\DATA\APP\PHP\session"' 222 | } 223 | foreach ($Entry in $PHPIniValues.Keys) 224 | { 225 | $PHPIniBaseFile = $PHPIniBaseFile -replace $Entry, $PHPIniValues[$Entry] 226 | } 227 | Set-Content -Path "$PHPDirectory\php.ini" -Value $PHPIniBaseFile 228 | 229 | #################################################################################################### 230 | ### 04: Install MySQL ############################################################################## 231 | #################################################################################################### 232 | 233 | # Variables. 234 | $MysqlDirectory = "$AppDirectory\MYSQL" 235 | $MysqlDownloadLocation = "http://dev.mysql.com/get/Downloads/MySQL-5.7/mysql-5.7.11-winx64.zip" 236 | $MysqlPackage = "mysql-5.7.11-winx64.zip" 237 | 238 | # Download the Windows (x86, 64-bit) ZIP Archive. 239 | Invoke-WebRequest -Uri $MysqlDownloadLocation -OutFile "$SrcDirectory\$MysqlPackage" 240 | 241 | # Extract the .zip file to the BASE directory. 242 | Add-Type -AssemblyName "system.io.compression.filesystem" 243 | [io.compression.zipfile]::ExtractToDirectory("$SrcDirectory\$MysqlPackage", $AppDirectory) 244 | 245 | # Rename the extracted directory to MYSQL. 246 | Get-ChildItem -Path $AppDirectory | Where-Object -FilterScript {$_.Name -like "*mysql*"} | Rename-Item -NewName "MYSQL" 247 | 248 | # Create my.ini and configure values. 249 | $MyIniBaseFile = Get-Content -Path "$MysqlDirectory\my-default.ini" 250 | $MyIniValues = @{'# basedir = .....' = 'basedir = C:/BASE/APP/MYSQL'; 251 | '# datadir = .....' = 'datadir = C:/BASE/APP/MYSQL/data' 252 | } 253 | foreach ($Entry in $MyIniValues.Keys) 254 | { 255 | $MyIniBaseFile = $MyIniBaseFile -replace $Entry, $MyIniValues[$Entry] 256 | } 257 | Set-Content -Path "$MysqlDirectory\my.ini" -Value $MyIniBaseFile 258 | 259 | # As from MySQL 5.7.7, the noninstall .zip package does no longer include the data directory. So we need to initialize it. 260 | # A new PowerShell window will popup, but no output will be returned. After initialization, a temporary root password will be created. 261 | # You can find it in $MysqlDirectory\data\.err. 262 | Start-Process -FilePath $PSHOME\powershell.exe -ArgumentList "-noexit Set-Location -Path $MysqlDirectory\bin ; .\mysqld --initialize" 263 | 264 | # Perform a test run. A new PowerShell window will popup. Ensure you see "ready for connections" near the end of the output and no errors are returned. 265 | # Once you have confirmed everything is OK, use Control-C to shutdown the MySQL server again. 266 | Start-Process -FilePath $PSHOME\powershell.exe -ArgumentList "-noexit Set-Location -Path $MysqlDirectory\bin ; .\mysqld --console" 267 | 268 | # Verify that the mysqld.exe process has been correctly shutdown from the previous step to avoid problems with starting the service later on. 269 | $CheckMysqldProcess = Get-Process -Name "mysqld" 270 | if ($CheckMysqldProcess) 271 | { 272 | Stop-Process -Name "mysqld" -Force 273 | } 274 | 275 | # Add the MySQL installation directory to the Path Environment variable. 276 | $CurrentPath = (Get-ItemProperty -Path 'Registry::HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Session Manager\Environment' -Name PATH).PATH 277 | $NewPath = $CurrentPath + ";$MysqlDirectory\bin" 278 | Set-ItemProperty -Path 'Registry::HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Session Manager\Environment' -Name PATH -Value $NewPath 279 | 280 | # Install MySQL as a service. 281 | Start-Process -FilePath $PSHOME\powershell.exe -ArgumentList "-noexit Set-Location -Path $MysqlDirectory\bin ; .\mysqld --install MySQL --defaults-file=$MysqlDirectory\my.ini" 282 | 283 | # Start the MySQL service. In case the service fails to start, verify there is no more active mysqld.exe process from the test run. 284 | # If yes, kill the process and attempt to start the service again. 285 | Start-Service -Name "MySQL" -PassThru 286 | 287 | #################################################################################################### 288 | ### 05: Configure firewall ######################################################################### 289 | #################################################################################################### 290 | 291 | # Variables. 292 | $FWDirectory = "$AppDirectory\FW" 293 | $FWLogDirectory = "$FWDirectory\Log" 294 | $FWLogFileDomain = "FWLogDomain.log" 295 | $FWLogFilePrivate = "FWLogPrivate.log" 296 | $FWLogFilePublic = "FWLogPublic.log" 297 | $FWLogFileSize = 32767 298 | 299 | # Create the FW Directory. 300 | New-Item -ItemType Directory -Path $FWDirectory 301 | 302 | # Create the FW log Directory. 303 | New-Item -ItemType Directory -Path $FWLogDirectory 304 | 305 | # Configure the log file for the Domain profile. 306 | New-Item -ItemType File -Path $FWLogDirectory -Name $FWLogFileDomain 307 | Set-NetFirewallProfile -Profile Domain -LogFileName $FWLogDirectory\$FWLogFileDomain -LogMaxSizeKilobytes $FWLogFileSize -LogBlocked True 308 | 309 | # Configure the log file for the Private profile. 310 | New-Item -ItemType File -Path $FWLogDirectory -Name $FWLogFilePrivate 311 | Set-NetFirewallProfile -Profile Private -LogFileName $FWLogDirectory\$FWLogFilePrivate -LogMaxSizeKilobytes $FWLogFileSize -LogBlocked True 312 | 313 | # Configure the log file for the Public profile. 314 | New-Item -ItemType File -Path $FWLogDirectory -Name $FWLogFilePublic 315 | Set-NetFirewallProfile -Profile Public -LogFileName $FWLogDirectory\$FWLogFilePublic -LogMaxSizeKilobytes $FWLogFileSize -LogBlocked True 316 | 317 | # Configure the Domain profile to block outbound connections by default. 318 | Set-NetFirewallProfile -Profile Domain -DefaultOutboundAction Block 319 | 320 | # Configure the Private profile to block outbound connections by default. 321 | Set-NetFirewallProfile -Profile Private -DefaultOutboundAction Block 322 | 323 | # Configure the Public profile to block outbound connections by default. 324 | Set-NetFirewallProfile -Profile Public -DefaultOutboundAction Block 325 | 326 | # Disable the inbound rules that are enabled by default and are not required. 327 | [array]$FWRulesInboundDefault = ` 328 | "Core Networking - Dynamic Host Configuration Protocol (DHCP-In)",` 329 | "Core Networking - Dynamic Host Configuration Protocol for IPv6(DHCPV6-In)",` 330 | "File and Printer Sharing (LLMNR-UDP-In)",` 331 | "File and Printer Sharing (NB-Datagram-In)",` 332 | "File and Printer Sharing (NB-Name-In)",` 333 | "File and Printer Sharing (NB-Session-In)",` 334 | "File and Printer Sharing (SMB-In)",` 335 | "File and Printer Sharing (Spooler Service - RPC)",` 336 | "File and Printer Sharing (Spooler Service - RPC-EPMAP)",` 337 | "Remote Desktop - Shadow (TCP-In)",` 338 | "Windows Remote Management (HTTP-In)",` 339 | "Windows Remote Management (HTTP-In)" 340 | foreach ($Rule in $FWRulesInboundDefault) 341 | { 342 | Set-NetFirewallRule -DisplayName $Rule -Enabled False 343 | } 344 | 345 | # Disable the outbound rules that are enabled by default and are not required. 346 | [array]$FWRulesOutboundDefault = ` 347 | "Core Networking - Dynamic Host Configuration Protocol (DHCP-Out)",` 348 | "Core Networking - Dynamic Host Configuration Protocol for IPv6(DHCPV6-Out)",` 349 | "Core Networking - Group Policy (LSASS-Out)",` 350 | "Core Networking - Group Policy (NP-Out)",` 351 | "Core Networking - Group Policy (TCP-Out)",` 352 | "File and Printer Sharing (LLMNR-UDP-Out)",` 353 | "File and Printer Sharing (NB-Datagram-Out)",` 354 | "File and Printer Sharing (NB-Name-Out)",` 355 | "File and Printer Sharing (NB-Session-Out)",` 356 | "File and Printer Sharing (SMB-Out)" 357 | foreach ($Rule in $FWRulesOutboundDefault) 358 | { 359 | Set-NetFirewallRule -DisplayName $Rule -Enabled False 360 | } 361 | 362 | # Enable the outbound rules that are disabled by default and that are useful to have enabled. 363 | [array]$FWRulesOutboundDefaultDisabled = ` 364 | "File and Printer Sharing (Echo Request - ICMPv4-Out)",` 365 | "File and Printer Sharing (Echo Request - ICMPv6-Out)" 366 | foreach ($Rule in $FWRulesOutboundDefaultDisabled) 367 | { 368 | Set-NetFirewallRule -DisplayName $Rule -Enabled True 369 | } 370 | 371 | # Modify the port range for FTP Server passive incoming traffic to a more limited range. 372 | Get-NetFirewallRule -Name "IIS-WebServerRole-FTP-Passive-In-TCP" | Set-NetFirewallRule -LocalPort "10000-10500" 373 | 374 | # Custom rule to enable outbound web traffic from the server on port 80 (HTTP). 375 | New-NetFirewallRule -Profile Public -Direction Outbound -Protocol TCP -RemotePort 80 -Name "WebAccess-HTTP-TCP-Out" -DisplayName "WebAccess (HTTP-TCP-Out)" -Group "Custom - WebAccess" -Action Allow 376 | 377 | # Custom rule to enable outbound web traffic from the server on port 443 (HTTPS). 378 | New-NetFirewallRule -Profile Public -Direction Outbound -Protocol TCP -RemotePort 443 -Name "WebAccess-HTTPS-TCP-Out" -DisplayName "WebAccess (HTTPS-TCP-Out)" -Group "Custom - WebAccess" -Action Allow 379 | 380 | #################################################################################################### 381 | ### 06: Configure website ########################################################################## 382 | #################################################################################################### 383 | 384 | # Variables. 385 | $Domain = "supersysadmin.com" 386 | $DomainDirectory = "$IISDirectory\$Domain" 387 | $DomainWebDirectory = "$DomainDirectory\wwwroot" 388 | $DomainLogDirectory = "$DomainDirectory\logs" 389 | $DomainIPAddress = "10.10.20.100" 390 | 391 | # Create website directories. 392 | New-Item -ItemType Directory -Path $DomainDirectory 393 | New-Item -ItemType Directory -Path $DomainLogDirectory 394 | New-Item -ItemType Directory -Path $DomainWebDirectory 395 | 396 | # Create application pool for the website. 397 | New-WebAppPool -Name $Domain 398 | 399 | # Set Read/Execute NTFS permissions for the application pool user on the wwwroot directory. 400 | # For each application pool you create, IIS will create a Windows user with the same name. However you will not find it in Local Users and Computers. 401 | # If you want to add it manually to the NTFS permissions of a directory, you have to type it ass "IIS AppPool\user" (where user is the name of your application pool. 402 | $ACL = Get-Acl -Path $DomainWebDirectory 403 | $NTAccount = New-Object System.Security.Principal.NTAccount("IIS AppPool\$Domain") 404 | $FileSystemRights = [System.Security.AccessControl.FileSystemRights]"ReadAndExecute" 405 | $InheritanceFlags = [System.Security.AccessControl.InheritanceFlags]"ContainerInherit,ObjectInherit" 406 | $PropagationFlags = [System.Security.AccessControl.PropagationFlags]::None 407 | $AccessControlType =[System.Security.AccessControl.AccessControlType]::Allow 408 | $UserPermissions = $NTAccount,$FileSystemRights,$InheritanceFlags,$PropagationFlags,$AccessControlType 409 | $AccessRule = New-Object -TypeName System.Security.AccessControl.FileSystemAccessRule -ArgumentList $UserPermissions 410 | $ACL.SetAccessRule($AccessRule) 411 | $ACL | Set-Acl -Path $DomainWebDirectory 412 | 413 | # Create the website. 414 | New-Website -Name $Domain -ApplicationPool $Domain -HostHeader $Domain -IPAddress $DomainIPAddress -PhysicalPath $DomainWebDirectory 415 | 416 | # Add host header for www. 417 | $WWWHostHeader = "www." + $Domain 418 | New-WebBinding -Name $Domain -IPAddress $DomainIPAddress -HostHeader $WWWHostHeader 419 | 420 | # Configure logging settings for the website. 421 | Set-ItemProperty -Path IIS:\Sites\$Domain -Name logFile.logExtFileFlags -Value "Date,Time,ClientIP,UserName,SiteName,ComputerName,ServerIP,Method,UriStem,UriQuery,HttpStatus,Win32Status,BytesSent,BytesRecv,TimeTaken,ServerPort,UserAgent,Cookie,Referer,ProtocolVersion,Host,HttpSubStatus" 422 | Set-ItemProperty -Path IIS:\Sites\$Domain -Name logFile.directory -Value $DomainLogDirectory 423 | Set-ItemProperty -Path IIS:\Sites\$Domain -Name logFile.localTimeRollover -Value $True 424 | 425 | # Configure the website to use the application pool identity for anonymous authentication. 426 | Set-WebConfigurationProperty -Filter /system.webServer/security/authentication/anonymousAuthentication -Name userName -Value "" -PSPath IIS:\ -Location $Domain 427 | 428 | # Add the application pool user to the group PHP Users. 429 | $NTAccount = New-Object System.Security.Principal.NTAccount("IIS AppPool\$Domain") 430 | $NTAccountSID = $NTAccount.Translate([System.Security.Principal.SecurityIdentifier]) 431 | $GroupPHPUsers = [ADSI]"WinNT://$env:ComputerName/$PHPUserGroup,Group" 432 | $AppPoolUser = [ADSI]"WinNT://$NTACcountSID" 433 | $GroupPHPUsers.Add($AppPoolUser.Path) 434 | 435 | # Create a basic index.html page. 436 | $IndexFileContent = @" 437 | 438 | 439 | $($Domain) 440 | 441 | 442 |

$($Domain)

443 | 444 | 445 | "@ 446 | New-Item -ItemType File -Path $DomainWebDirectory -Name index.html -Value $IndexFileContent 447 | 448 | # Create a page to test PHP. 449 | $PhpTestFileContent = @" 450 | 451 | 452 | $($Domain) - phpinfo 453 | 454 | 455 | 456 | 457 | 458 | "@ 459 | New-Item -ItemType File -Path $DomainWebDirectory -Name test.php -Value $PhpTestFileContent 460 | 461 | # Test our website by calling the two files we created via our browser. 462 | Start-Process -FilePath "http://$Domain/index.html" 463 | Start-Process -FilePath "http://$Domain/test.php" 464 | 465 | #################################################################################################### 466 | ### 07: Configure ftp site ######################################################################### 467 | #################################################################################################### 468 | 469 | #Variables. 470 | $DomainFTP = "ftp.supersysadmin.com" 471 | $DomainFTPDirectory = "$IISDirectory\$DomainFTP" 472 | $DomainFTPRootDirectory = "$DomainFTPDirectory\ftproot" 473 | $DomainFTPLocalUserDirectory = "$DomainFTPRootDirectory\LocalUser" 474 | $DomainFTPLogDirectory = "$DomainFTPDirectory\logs" 475 | $DomainFTPIPAddress = "10.10.20.100" 476 | $FTPPort = "21" 477 | $FTPLowDataChannelPort = 10000 478 | $FTPHighDataChannelPort = 10500 479 | $FTPUserGroup = "FTP Users" 480 | $FTPUser = "ftp_supersysadmin" 481 | $FTPPassword = "P@ssword" 482 | 483 | # Configure FTP Firewall Support (server level). 484 | Set-WebConfigurationProperty -Filter system.ftpServer/firewallSupport -Name lowDataChannelPort -Value $FTPLowDataChannelPort 485 | Set-WebConfigurationProperty -Filter system.ftpServer/firewallSupport -Name highDataChannelPort -Value $FTPHighDataChannelPort 486 | 487 | # Create directories. 488 | New-Item -ItemType Directory -Path $DomainFTPDirectory 489 | New-Item -ItemType Directory -Path $DomainFTPRootDirectory 490 | New-Item -ItemType Directory -Path $DomainFTPLocalUserDirectory 491 | New-Item -ItemType Directory -Path $DomainFTPLogDirectory 492 | 493 | # Create FTP Users local Windows group. 494 | $LocalAccountDB = [ADSI]"WinNT://$env:ComputerName" 495 | $CreateGroupFTPUsers = $LocalAccountDB.Create("Group","$FTPUserGroup") 496 | $CreateGroupFTPUsers.SetInfo() 497 | $CreateGroupFTPUsers.Description = "Members of this group can use connect via FTP" 498 | $CreateGroupFTPUsers.SetInfo() 499 | 500 | # Create FTP user. 501 | $LocalAccountDB = [ADSI]"WinNT://$env:ComputerName" 502 | $CreateUserFTPUser = $LocalAccountDB.Create("User","$FTPUser") 503 | $CreateUserFTPUser.SetInfo() 504 | $CreateUserFTPUser.SetPassword("$FTPPassword") 505 | $CreateUserFTPUser.SetInfo() 506 | 507 | # Add FTP user to the group FTP Users. 508 | $NTAccount = New-Object System.Security.Principal.NTAccount("$FTPUser") 509 | $NTAccountSID = $NTAccount.Translate([System.Security.Principal.SecurityIdentifier]) 510 | $GroupFTPUsers = [ADSI]"WinNT://$env:ComputerName/$FTPUserGroup,Group" 511 | $UserFTPUser = [ADSI]"WinNT://$NTACcountSID" 512 | $GroupFTPUsers.Add($UserFTPUser.Path) 513 | 514 | # Set Read NTFS permissions for the group FTP Users to the ftproot directory. 515 | $ACL = Get-Acl -Path $DomainFTPRootDirectory 516 | $NTAccount = New-Object System.Security.Principal.NTAccount("$FTPUserGroup") 517 | $FileSystemRights = [System.Security.AccessControl.FileSystemRights]"ReadAndExecute" 518 | $InheritanceFlags = [System.Security.AccessControl.InheritanceFlags]"ContainerInherit,ObjectInherit" 519 | $PropagationFlags = [System.Security.AccessControl.PropagationFlags]::None 520 | $AccessControlType =[System.Security.AccessControl.AccessControlType]::Allow 521 | $UserPermissions = $NTAccount,$FileSystemRights,$InheritanceFlags,$PropagationFlags,$AccessControlType 522 | $AccessRule = New-Object -TypeName System.Security.AccessControl.FileSystemAccessRule -ArgumentList $UserPermissions 523 | $ACL.SetAccessRule($AccessRule) 524 | $ACL | Set-Acl -Path $DomainFTPRootDirectory 525 | 526 | # Create the FTP site. 527 | New-WebFtpSite -Name $DomainFTP -IPAddress $DomainFTPIPAddress -Port $FTPPort -PhysicalPath $DomainFTPRootDirectory 528 | 529 | # Enable basic authentication on the FTP site. 530 | Set-ItemProperty -Path IIS:\Sites\$DomainFTP -Name ftpServer.security.authentication.basicAuthentication.enabled -Value $True 531 | 532 | # Change the SSL policy from Require SSL connections to Allow SSL connections. 533 | Set-ItemProperty -Path IIS:\Sites\$DomainFTP -Name ftpServer.security.ssl.controlChannelPolicy -Value 0 534 | Set-ItemProperty -Path IIS:\Sites\$DomainFTP -Name ftpServer.security.ssl.dataChannelPolicy -Value 0 535 | 536 | # Add an Authorization read rule for FTP Users. 537 | Add-WebConfiguration -Filter "/system.ftpServer/security/authorization" -Value @{accessType="Allow";roles="$FTPUserGroup";permissions=1} -PSPath IIS:\ -Location $DomainFTP 538 | 539 | # Enable virtual directories in FTP Directory Browsing. 540 | Set-ItemProperty -Path IIS:\Sites\$DomainFTP -Name ftpServer.directoryBrowse.showFlags -Value "DisplayVirtualDirectories" 541 | 542 | # Configure FTP Firewall Support (site level). 543 | Set-ItemProperty -Path IIS:\Sites\$DomainFTP -Name ftpServer.firewallSupport.externalIp4Address -Value $DomainFTPIPAddress 544 | 545 | # Configure logging settings for the FTP site. 546 | Set-ItemProperty -Path IIS:\Sites\$DomainFTP -Name ftpServer.logFile.logExtFileFlags -Value "Date,Time,ClientIP,UserName,SiteName,ComputerName,ServerIP,Method,UriStem,FtpStatus,Win32Status,BytesSent,BytesRecv,TimeTaken,ServerPort,Host,FtpSubStatus,Session,FullPath,Info,ClientPort" 547 | Set-ItemProperty -Path IIS:\Sites\$DomainFTP -Name ftpServer.logFile.directory -Value $DomainFTPLogDirectory 548 | Set-ItemProperty -Path IIS:\Sites\$DomainFTP -Name ftpServer.logFile.localTimeRollover -Value $True 549 | 550 | # Enable user isolation. 551 | Set-ItemProperty -Path IIs:\Sites\$DomainFTP -Name ftpServer.userIsolation.mode -Value "IsolateAllDirectories" 552 | 553 | # Create the username directory. 554 | New-Item -ItemType Directory -Path $DomainFTPLocalUserDirectory\$FTPUser 555 | 556 | # Set Modify NTFS permissions for the FTP user on the username directory. 557 | $ACL = Get-Acl -Path $DomainFTPLocalUserDirectory\$FTPUser 558 | $NTAccount = New-Object System.Security.Principal.NTAccount("$FTPUser") 559 | $FileSystemRights = [System.Security.AccessControl.FileSystemRights]"Modify" 560 | $InheritanceFlags = [System.Security.AccessControl.InheritanceFlags]"ContainerInherit,ObjectInherit" 561 | $PropagationFlags = [System.Security.AccessControl.PropagationFlags]::None 562 | $AccessControlType =[System.Security.AccessControl.AccessControlType]::Allow 563 | $UserPermissions = $NTAccount,$FileSystemRights,$InheritanceFlags,$PropagationFlags,$AccessControlType 564 | $AccessRule = New-Object -TypeName System.Security.AccessControl.FileSystemAccessRule -ArgumentList $UserPermissions 565 | $ACL.SetAccessRule($AccessRule) 566 | $ACL | Set-Acl -Path $DomainFTPLocalUserDirectory\$FTPUser 567 | 568 | # Create a virtual directory for the website domain root directory under the FTP site. 569 | New-WebVirtualDirectory -Site "$DomainFTP\LocalUser\$FTPUser" -Name "$Domain" -PhysicalPath $DomainDirectory 570 | 571 | # Set Modify NTFS permissions for the FTP user on the website domain root. 572 | $ACL = Get-Acl -Path $DomainDirectory 573 | $NTAccount = New-Object System.Security.Principal.NTAccount("$FTPUser") 574 | $FileSystemRights = [System.Security.AccessControl.FileSystemRights]"Modify" 575 | $InheritanceFlags = [System.Security.AccessControl.InheritanceFlags]"ContainerInherit,ObjectInherit" 576 | $PropagationFlags = [System.Security.AccessControl.PropagationFlags]::None 577 | $AccessControlType =[System.Security.AccessControl.AccessControlType]::Allow 578 | $UserPermissions = $NTAccount,$FileSystemRights,$InheritanceFlags,$PropagationFlags,$AccessControlType 579 | $AccessRule = New-Object -TypeName System.Security.AccessControl.FileSystemAccessRule -ArgumentList $UserPermissions 580 | $ACL.SetAccessRule($AccessRule) 581 | $ACL | Set-Acl -Path $DomainDirectory 582 | 583 | # Add an Authorization rule for FTP user on virtual directory. 584 | Add-WebConfiguration "/system.ftpServer/security/authorization" -Value @{accessType="Allow";roles="$FTPUser";permissions=3} -PSPath IIS:\ -Location $DomainFTP/LocalUser/$FTPUser/$Domain 585 | -------------------------------------------------------------------------------- /Scripts/GUI/AD/ADUserResetPassword.ps1: -------------------------------------------------------------------------------- 1 | #------------------------------------------------------------------------ 2 | # Source File Information (DO NOT MODIFY) 3 | # Source ID: 71c976ed-5ef1-475a-a5c7-a288af2929d6 4 | # Source File: ADUserResetPassword.psproj 5 | #------------------------------------------------------------------------ 6 | #region Project Recovery Data (DO NOT MODIFY) 7 | <#RecoveryData: 8 | /AEAAB+LCAAAAAAABACNkUFPgzAYhu9L9h8I945BZIyka6IhmB3UhU2v5hM+XLWjpC1b9u+tUham 9 | F2992rfPm6+lBZbyiOqcgQE2nXge3Sj5gaX5AYsvqDSXDYtmcxoM4M5yLnCdsSQs02SBFYmxDslN 10 | EgOBuEwIRMsl1FEapdWCBi7srrqW3blFZsVjHORSVLbOC8Zt2oFD767jolr5c59tDSjTtbNW677r 11 | V7LAGhU2JeZdUxo7xMrf7uWJPABvcqkOr62u/ZFv2LfC+r/CdXOUn0juhXwDoa0xHBm97R4U2uVO 12 | degzF7L68ErfQz/n5V16elL8nTcgvgOPcEB2mz1rVAVqNBvQ+iRVZX2tvUODP+HphAZXv/0FwIaM 13 | 0vwBAAA=#> 14 | #endregion 15 | <# 16 | .NOTES 17 | -------------------------------------------------------------------------------- 18 | Code generated by: SAPIEN Technologies, Inc., PowerShell Studio 2016 v5.3.130 19 | Generated on: 2016-12-11 15:34 20 | Generated by: ibelmans 21 | -------------------------------------------------------------------------------- 22 | .DESCRIPTION 23 | Script generated by PowerShell Studio 2016 24 | #> 25 | 26 | 27 | #region Source: Startup.pss 28 | #region File Recovery Data (DO NOT MODIFY) 29 | <#RecoveryData: 30 | ZAMAAB+LCAAAAAAABAC9k99Lw0AMx98F/4djz+Xa2tU6uBZkshdBxYn6mnbpOLwfI7lz9L93mzJF 31 | HwSRkpd8E5IPIYm6x86/Ig1XEEDsHNbe1ZMzmU+a0xMh1C3ptXZgFtrgDVhslgEoxI3cMKv0R/ZQ 32 | c8mMtjUa+aA/I0NjufNkdJuIxw/WVGZ7S8Q8mhAJa4cxEJhE3MVdj+4ahwf/gq5uqwrKrjzPZ8UU 33 | s4uZSo9dv1OWAwe0YzDkk3Yrv2W58GR5FOJ+U+OACLbarf/Cyoq+7Ks+z1dlBgX8znq2ZpSZ5p7w 34 | /0FH+X7yKv36Vc0baArZVmQDAAA=#> 35 | #endregion 36 | #---------------------------------------------- 37 | #region Import Assemblies 38 | #---------------------------------------------- 39 | [void][Reflection.Assembly]::Load('System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089') 40 | [void][Reflection.Assembly]::Load('System.Data, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089') 41 | [void][Reflection.Assembly]::Load('System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a') 42 | #endregion Import Assemblies 43 | 44 | #################################################################################################### 45 | ### Begin: Script information ###################################################################### 46 | #################################################################################################### 47 | 48 | <# 49 | .SYNOPSIS 50 | PowerShell GUI script to reset an Active Directory user's password. 51 | .DESCRIPTION 52 | PowerShell GUI script to reset an Active Directory user's password. 53 | .NOTES 54 | Author : Ingvald Belmans 55 | Website : http://www.supersysadmin.com 56 | Version : 2.0 57 | Changelog: 58 | - 1.0 (2016-01-04) Initial version. 59 | - 1.1 (2016-01-05) Cleanup output text and simplify try/catch for $ButtonMainChangePasswordChangePassword_Click. 60 | - 1.2 (2016-12-08) Fixed bug where error handling was not working when using implicit remoting for the ActiveDirectory PowerShell module. 61 | - 2.0 (2016-12-11) 62 | - Added support for alternate credentials. 63 | - Added options for "User cannot change password" and "Password never expires". 64 | - Added support to connect to other domains/forests. 65 | - Removed unnecessary logging of ActiveDirectory PowerShell module being loaded at each password update. 66 | - Generalized application name, version and URL. 67 | - Some code correction (parameters not fully written out). 68 | - Code commenting restructuring. 69 | .LINK 70 | http://www.supersysadmin.com 71 | #> 72 | 73 | #################################################################################################### 74 | ### End: Script information ######################################################################## 75 | #################################################################################################### 76 | 77 | #################################################################################################### 78 | ### Begin: Main function ########################################################################### 79 | #################################################################################################### 80 | 81 | #region function Main 82 | function Main { 83 | <# 84 | .SYNOPSIS 85 | The Main function starts the project application. 86 | 87 | .PARAMETER Commandline 88 | $Commandline contains the complete argument string passed to the script packager executable. 89 | 90 | .NOTES 91 | Use this function to initialize your script and to call GUI forms. 92 | 93 | .NOTES 94 | To get the console output in the Packager (Forms Engine) use: 95 | $ConsoleOutput (Type: System.Collections.ArrayList) 96 | #> 97 | Param 98 | ( 99 | [String]$Commandline 100 | ) 101 | if((Show-MainForm_psf) -eq 'OK') 102 | { 103 | } 104 | $global:ExitCode = 0 #Set the exit code for the Packager 105 | } 106 | #endregion 107 | 108 | #################################################################################################### 109 | ### End: Main function ############################################################################# 110 | #################################################################################################### 111 | 112 | #endregion Source: Startup.pss 113 | 114 | #region Source: MainForm.psf 115 | function Show-MainForm_psf 116 | { 117 | #region File Recovery Data (DO NOT MODIFY) 118 | <#RecoveryData: 119 | 9jkAAB+LCAAAAAAABADlW1tv4jgUfl9p/4PF06yEgHApVKJIlLar0badqnRn960ywYC3SYwcZyj7 120 | 6/c4JjSQhNjcprCq1DbF5/7587Hjtp+JzX4QPr/BAiP4xafMuypUS1ah8+svCLW/cTqmHnbuqEMe 121 | sUs6D5h6d4y7pak/apcTHyuhwT/EFkjMp+Sq0J/7grilv6g3ZDO/JGXV9yJK+6iIvi+8qJcq8quI 122 | eoEjAk6uPBIIjp0iegoGDrX/IPMX9ka8q0GziRt248K6rNVJpXVZQB64clWQ+qS7BWRPqDPkMLTQ 123 | Y57gzPFVeODrE2dTwsV8IdMNBOvb2CE31CWe9AOGXhSRVWuXo6F5og9sSAqdO7CUK9NzKPFEn/4L 124 | Ao3WZRHVK/mGZEwPxAv6gtNpFAgMeyYjAkHaJBoXjVFJKEfqcvVTj7qBq7y6qDTAq3o1V0qWX0at 125 | cp47vC8wF0/MpwJyXOj0IA2E921OSL7sC3kXhU735k+f8GfiE/GEfX/G+DApefsDFC/E7hkefnj4 126 | Kh/b5XBA2uj+hM282PDweW18PtB/5yyYXrP3g4M9MiR9/RaIaSA2wT4FvZ49YbzQeWHTIrpmQjCY 127 | oPdkJIromY4nSSgnVdwzG6tqWjWYMS1LQ0ahJum8huhi1lyArWrlUkPgBQ++ekPyDkJ6o/uCwfy6 128 | w45PdARCVGa7nw+WZ2pPpJZj4CVmSxcyewFNUokkSiAAYFrmYAixVao2pnqiH4hrShBoySjEpYav 129 | JQ8cxRznGnM/JAebDKEmggLx64kr1NZbMEOaaajdhFu9CBUQY5+nCsW5Tkr0Jtgbk2FGal5jQ1ZJ 130 | UOpX0F6uL6uPn5QkVTDRymFGlh+4q1XBnWprK6Zb9UCb8aoN2Y/Um0aMl+wq9sZ4Kgy0KY58CPQm 131 | xH47BgQiQ8kCRD8fCfTBt+9TyolvSogfwIAatZJNUzYwzPwyoJpqXS6QdUOmScNLFgAiB5EnPUTE 132 | wEXo4L5TP8BOX8wdco3ttx5zwhWFB2kIXOOtMGlkuKQusyS+rorn0NqpwFg2xT3seUyYMFwOlBtp 133 | vZw5lLN8Ozic9WaigrN0Etmhl5CykNumJn4eDdNZ2TxfXD8E/lqsXfEIRbtnY7Zxm58LcKPmcQcn 134 | D450vYkaQ7oL7q7jHGFAIwxBjrbPR0X9xhQfAP7XAWxtvIODX5lJhrxHIrcsk6ZEzyFjTKe1y5sw 135 | rTkHNLvR/WMXavumm6zXcPR5bKEeyWzX/ZNVBUxW0sg3f/8UM6+9eapVrCJqap7/bGge9rR3ghCW 136 | UEVfxIza5LftNlDHOjeKnQzE8l81JaW9HPq0iih1G5wFngzfTfirpd8rmK7JwEKqdjHiyOagbZax 137 | n4sR66dgxPRgMMN3I4zo2zQ92tsJIyeyqsgGL6zFDkvKlidykWmD5QSCrpu9fNB5LbLlchL5j770 138 | sdu1bRZ4Qj6fzpqiV/zPxxUbkHN4nth5ni/fFB+81GvvpE1m+FfwaxUD8i8b8cuYo4yBVTn4cOHF 139 | 3Ep5E59wJLxFQR3y8VZeFU5+dj4R9jgZwi6HAoedd6A3zF25YpESo9H7c3Bbf0u0MqX035vL2yap 140 | p0uG3JO6ELngky99Si52K+y0+qCxIh0PBrlTN+Nyyg083rCZt0ZXnxTh+lTVHTB5QaAcQ/QqwE89 141 | wHs2Pufwbt9pdvk0b3dlKs+/7qXa5fSOJ51DUvSeMF1IdG2XW5DUTK9VkfnNv6qn8puqN+Vcc5Nj 142 | ydPMEy6RYrjtihTKHqRMGZpNChWqOKtShWS2XaWkqG6hGlWDQqUrNqmT1HA2ZYo3//+jVikW9q28 143 | 0pyxBzqn7iIWYs8hWCvkXRqOmH7NidxsGfQd2epPfyYmILlT9te16dJqeGVbm1alEbTRii7HbnD9 144 | HGk3MRkz8nzr4YEjL12kHzZvh4114wfBRmhk79hYd/1ssLE4pjKvqxLULOGFZUC2WZp1y6bk8yrU 145 | 9X3iQt6IH+lf/GXecX2bcYcO9pD7dnmpdd2KqvYxbOwdUfkW5f8OHscQxzPqjbexVamNGqPmyLKG 146 | jQqu4Xxbf7vOUWLqMU72b2j5qCDfLsf/z7PzH/Th6PP2OQAA#> 147 | #endregion 148 | #---------------------------------------------- 149 | #region Import the Assemblies 150 | #---------------------------------------------- 151 | [void][reflection.assembly]::Load('System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089') 152 | [void][reflection.assembly]::Load('System.Data, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089') 153 | [void][reflection.assembly]::Load('System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a') 154 | [void][reflection.assembly]::Load('System.Design, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a') 155 | #endregion Import Assemblies 156 | 157 | #---------------------------------------------- 158 | #region Generated Form Objects 159 | #---------------------------------------------- 160 | [System.Windows.Forms.Application]::EnableVisualStyles() 161 | $FormMain = New-Object 'System.Windows.Forms.Form' 162 | $GroupBoxMainOutput = New-Object 'System.Windows.Forms.GroupBox' 163 | $RichTextBoxMainOutput = New-Object 'System.Windows.Forms.RichTextBox' 164 | $GroupBoxMainChangePassword = New-Object 'System.Windows.Forms.GroupBox' 165 | $CheckBoxMainChangePasswordPasswordNeverExpires = New-Object 'System.Windows.Forms.CheckBox' 166 | $CheckBoxMainChangePasswordUserCannotChangePassword = New-Object 'System.Windows.Forms.CheckBox' 167 | $CheckBoxMainChangePasswordUserMustChangePasswordAtNextLogon = New-Object 'System.Windows.Forms.CheckBox' 168 | $ButtonMainChangePasswordChangePassword = New-Object 'System.Windows.Forms.Button' 169 | $GroupBoxMainNewPassword = New-Object 'System.Windows.Forms.GroupBox' 170 | $TextBoxMainNewPassword2 = New-Object 'System.Windows.Forms.TextBox' 171 | $TextBoxMainNewPassword1 = New-Object 'System.Windows.Forms.TextBox' 172 | $GroupBoxMainUserName = New-Object 'System.Windows.Forms.GroupBox' 173 | $TextBoxMainUserName = New-Object 'System.Windows.Forms.TextBox' 174 | $MenuStripMain = New-Object 'System.Windows.Forms.MenuStrip' 175 | $ToolStripMenuItemMainFile = New-Object 'System.Windows.Forms.ToolStripMenuItem' 176 | $ToolStripMenuItemMainFileLog = New-Object 'System.Windows.Forms.ToolStripMenuItem' 177 | $ToolStripMenuItemMainFileAbout = New-Object 'System.Windows.Forms.ToolStripMenuItem' 178 | $ToolStripMenuItemMainFileExit = New-Object 'System.Windows.Forms.ToolStripMenuItem' 179 | $ToolStripMenuItemMainCredentials = New-Object 'System.Windows.Forms.ToolStripMenuItem' 180 | $ToolStripMenuItemMainCredentialsEnterCredentials = New-Object 'System.Windows.Forms.ToolStripMenuItem' 181 | $ToolStripMenuItemMainCredentialsClearCredentials = New-Object 'System.Windows.Forms.ToolStripMenuItem' 182 | $ToolStripMenuItemMainDomain = New-Object 'System.Windows.Forms.ToolStripMenuItem' 183 | $InitialFormWindowState = New-Object 'System.Windows.Forms.FormWindowState' 184 | #endregion Generated Form Objects 185 | 186 | #---------------------------------------------- 187 | # User Generated Script 188 | #---------------------------------------------- 189 | #region Form > Main 190 | #################################################################################################### 191 | ### Begin: Form > Main ############################################################################# 192 | #################################################################################################### 193 | 194 | # Form load. 195 | $FormMain_Load = 196 | { 197 | # Application name and version. 198 | $global:SSAApplicationName = "ADUserResetPassword" 199 | $global:SSAApplicationVersion = "2.0" 200 | $global:SSAApplicationURL = "http://supersysadmin.com/96/powershell-gui-script-to-reset-an-active-directory-users-password/" 201 | 202 | # Set application title. 203 | $global:SSAApplicationDisplayCurrentUser = [System.Security.Principal.WindowsIdentity]::GetCurrent() 204 | $FormMain.Text = "$SSAApplicationName v$SSAApplicationVersion ($($SSAApplicationDisplayCurrentUser.Name))" 205 | 206 | # Create log file. 207 | $SSALogFileTimeStamp = Get-Date -UFormat "%Y%m%d_%H%M%S" 208 | $global:SSALogFile = New-Item -ItemType File -Path "$env:USERPROFILE\Documents" -Name "SSA_ADUserResetPassword_$SSALogFileTimeStamp.log" 209 | 210 | # Define variable for application user. 211 | $global:SSAApplicationUser = @{ } 212 | 213 | # Populate ActiveDirectoryDomain variable with the current domain. 214 | $global:SSAActiveDirectoryDomain = (Get-WmiObject -Class Win32_ComputerSystem).Domain 215 | 216 | # Set global ErrorActionPreference to Stop to ensure that error handling correctly works when using implicit remoting for the ActiveDirectory PowerShell module. 217 | $global:ErrorActionPreference = "Stop" 218 | 219 | # Show result of log file creation. 220 | Add-SSAOutput -OutputText "Creating log file." 221 | if (Test-Path -Path $SSALogFile) 222 | { 223 | Add-SSAOutput -OutputText "Logfile $SSALogFile has been created." 224 | } 225 | else 226 | { 227 | Add-SSAOutput -OutputText "Logfile $SSALogFile could not be created." 228 | } 229 | } 230 | 231 | # Form Shown. 232 | $FormMain_Shown = 233 | { 234 | Import-SSAActiveDirectoryModule 235 | if ($SSAActiveDirectoryModuleLoaded -eq $False) 236 | { 237 | [System.Windows.Forms.MessageBox]::Show("The ActiveDirectory PowerShell module could not be loaded. You can review the log for more details. Please restart the application to try again.", "Error", [System.Windows.Forms.MessageBoxButtons]::OK, [System.Windows.Forms.MessageBoxIcon]::Error) 238 | } 239 | } 240 | 241 | # Menu File > About. 242 | $ToolStripMenuItemMainFileAbout_Click = 243 | { 244 | Start-Process -FilePath $SSAApplicationURL 245 | } 246 | 247 | # Menu File > Log. 248 | $ToolStripMenuItemMainFileLog_Click = 249 | { 250 | Invoke-Item -Path $SSALogFile 251 | } 252 | 253 | # Menu File > Exit. 254 | $ToolStripMenuItemMainFileExit_Click = 255 | { 256 | $FormMain.Close() 257 | } 258 | 259 | # Menu Credentials > Enter Credentials. 260 | $ToolStripMenuItemMainCredentialsEnterCredentials_Click = 261 | { 262 | Add-SSAOutput -OutputText "Entering alternate credentials." 263 | try 264 | { 265 | $global:SSAApplicationUser = @{ Credential = Get-Credential -Message "Enter Credentials" -ErrorAction Stop } 266 | $FormMain.Text = "$SSAApplicationName v$SSAApplicationVersion ($($SSAApplicationUser.Credential.UserName))" 267 | $ToolStripMenuItemMainCredentialsEnterCredentials.Enabled = $False 268 | $ToolStripMenuItemMainCredentialsClearCredentials.Enabled = $True 269 | Add-SSAOutput -OutputText "Alternate credentials have been saved. The current user is now $($SSAApplicationUser.Credential.UserName)." 270 | } 271 | catch 272 | { 273 | Add-SSAOutput -OutputText $_ 274 | Add-SSAOutput -OutputText "Alternate credentials could not be saved." 275 | } 276 | } 277 | 278 | # Menu Credentials > Clear Credentials. 279 | $ToolStripMenuItemMainCredentialsClearCredentials_Click = 280 | { 281 | Add-SSAOutput -OutputText "Clearing alternate credentials." 282 | $global:SSAApplicationUser = @{ } 283 | $global:SSAApplicationDisplayCurrentUser = [System.Security.Principal.WindowsIdentity]::GetCurrent() 284 | $FormMain.Text = "$SSAApplicationName v$SSAApplicationVersion ($($SSAApplicationDisplayCurrentUser.Name))" 285 | $ToolStripMenuItemMainCredentialsClearCredentials.Enabled = $False 286 | $ToolStripMenuItemMainCredentialsEnterCredentials.Enabled = $True 287 | Add-SSAOutput -OutputText "Alternate credentials have been cleared. The current user is now $($SSAApplicationDisplayCurrentUser.Name)." 288 | } 289 | 290 | # Menu Domain. 291 | $ToolStripMenuItemMainDomain_Click = 292 | { 293 | Add-SSAOutput -OutputText "Updating Active Directory Domain." 294 | [Reflection.Assembly]::LoadWithPartialName("Microsoft.VisualBasic") 295 | $SSAUpdateActiveDirectoryDomain = [Microsoft.VisualBasic.Interaction]::InputBox("Enter in the textbox below the Active Directory Domain against which you want to run your queries:", "Active Directory Domain", $SSAActiveDirectoryDomain) 296 | # If you press Cancel or press OK when the textbox is empty, an empty string is returned (not the same as $null). 297 | if ($SSAUpdateActiveDirectoryDomain -eq "") 298 | { 299 | if ($SSAActiveDirectoryDomain -eq $null) 300 | { 301 | $global:SSAActiveDirectoryDomain = (Get-WmiObject -Class Win32_ComputerSystem).Domain 302 | Add-SSAOutput -OutputText "Input was empty or cancelled and current domain is null. Resetting domain to $SSAActiveDirectoryDomain." 303 | } 304 | else 305 | { 306 | Add-SSAOutput -OutputText "Input was empty or cancelled and current domain is not null. No action was taken." 307 | } 308 | } 309 | else 310 | { 311 | if ($SSAUpdateActiveDirectoryDomain -eq $SSAActiveDirectoryDomain) 312 | { 313 | Add-SSAOutput -OutputText "Input was equal to current domain. No action was taken." 314 | } 315 | else 316 | { 317 | $global:SSAActiveDirectoryDomain = $SSAUpdateActiveDirectoryDomain 318 | Add-SSAOutput -OutputText "Active Directory Domain has been updated to '$SSAActiveDirectoryDomain'." 319 | } 320 | } 321 | } 322 | 323 | # When checkbox CheckBoxMainChangePasswordUserMustChangePasswordAtNextLogon is checked, unsure checkboxs CheckBoxMainChangePasswordUserCannotChangePassword and CheckBoxMainChangePasswordPasswordNeverExpires are unchecked. 324 | $CheckBoxMainChangePasswordUserMustChangePasswordAtNextLogon_CheckedChanged = 325 | { 326 | if ($CheckBoxMainChangePasswordUserMustChangePasswordAtNextLogon.Checked -eq $True) 327 | { 328 | $CheckBoxMainChangePasswordUserCannotChangePassword.Checked = $False 329 | $CheckBoxMainChangePasswordPasswordNeverExpires.Checked = $False 330 | } 331 | } 332 | 333 | # When checkbox CheckBoxMainChangePasswordUserCannotChangePassword is checked, unsure checkbox CheckBoxMainChangePasswordUserMustChangePasswordAtNextLogon is unchecked. 334 | $CheckBoxMainChangePasswordUserCannotChangePassword_CheckedChanged = 335 | { 336 | if ($CheckBoxMainChangePasswordUserCannotChangePassword.Checked -eq $True) 337 | { 338 | $CheckBoxMainChangePasswordUserMustChangePasswordAtNextLogon.Checked = $False 339 | } 340 | } 341 | 342 | # When checkbox CheckBoxMainChangePasswordPasswordNeverExpires is checked, unsure checkbox CheckBoxMainChangePasswordUserMustChangePasswordAtNextLogon is unchecked. 343 | $CheckBoxMainChangePasswordPasswordNeverExpires_CheckedChanged = 344 | { 345 | if ($CheckBoxMainChangePasswordPasswordNeverExpires.Checked -eq $True) 346 | { 347 | $CheckBoxMainChangePasswordUserMustChangePasswordAtNextLogon.Checked = $False 348 | } 349 | } 350 | 351 | # Change password. 352 | $ButtonMainChangePasswordChangePassword_Click = 353 | { 354 | if ($SSAActiveDirectoryModuleLoaded -eq $True) 355 | { 356 | Get-SSAUserName 357 | if ($SSAUserName) 358 | { 359 | Add-SSAOutput -OutputText "Changing password of user '$SSAUserName'." 360 | try 361 | { 362 | $QueryADUser = Get-ADUser -Identity $SSAUserName -Properties * @SSAApplicationUser -Server $SSAActiveDirectoryDomain -ErrorAction Stop 363 | Get-SSAPassword1 364 | Get-SSAPassword2 365 | if ($SSAPassword1 -and $SSAPassword2) 366 | { 367 | if ($SSAPassword1 -eq $SSAPassword2) 368 | { 369 | Set-ADAccountPassword -Identity $SSAUserName -NewPassword (ConvertTo-SecureString -String $SSAPassword1 -AsPlainText –Force) –Reset @SSAApplicationUser -Server $SSAActiveDirectoryDomain -ErrorAction Stop -PassThru 370 | Add-SSAOutput -OutputText "Password for user '$SSAUserName' has been updated." 371 | if ($CheckBoxMainChangePasswordUserMustChangePasswordAtNextLogon.Checked -eq $True) 372 | { 373 | if ($QueryADUser.pwdLastSet -ne 0) 374 | { 375 | if ($QueryADUser.PasswordNeverExpires -eq $True) 376 | { 377 | Set-ADUser -Identity $SSAUserName -PasswordNeverExpires $False @SSAApplicationUser -Server $SSAActiveDirectoryDomain -ErrorAction Stop 378 | } 379 | Set-ADUser -Identity $SSAUserName -ChangePasswordAtLogon $True @SSAApplicationUser -Server $SSAActiveDirectoryDomain -ErrorAction Stop 380 | Add-SSAOutput -OutputText "Option 'Change password at next logon' has been enabled for user '$SSAUserName'." 381 | } 382 | } 383 | else 384 | { 385 | if ($QueryADUser.pwdLastSet -eq 0) 386 | { 387 | Set-ADUser -Identity $SSAUserName -ChangePasswordAtLogon $False @SSAApplicationUser -Server $SSAActiveDirectoryDomain -ErrorAction Stop 388 | Add-SSAOutput -OutputText "Option 'Change password at next logon' has been disabled for user '$SSAUserName'." 389 | } 390 | } 391 | if ($CheckBoxMainChangePasswordUserCannotChangePassword.Checked -eq $True) 392 | { 393 | if ($QueryADUser.CannotChangePassword -ne $True) 394 | { 395 | Set-ADUser -Identity $SSAUserName -CannotChangePassword $True @SSAApplicationUser -Server $SSAActiveDirectoryDomain -ErrorAction Stop 396 | Add-SSAOutput -OutputText "Option 'User cannot change password' has been enabled for user '$SSAUserName'." 397 | } 398 | } 399 | else 400 | { 401 | if ($QueryADUser.CannotChangePassword -ne $False) 402 | { 403 | Set-ADUser -Identity $SSAUserName -CannotChangePassword $False @SSAApplicationUser -Server $SSAActiveDirectoryDomain -ErrorAction Stop 404 | Add-SSAOutput -OutputText "Option 'User cannot change password' has been disabled for user '$SSAUserName'." 405 | } 406 | } 407 | if ($CheckBoxMainChangePasswordPasswordNeverExpires.Checked -eq $True) 408 | { 409 | if ($QueryADUser.PasswordNeverExpires -ne $True) 410 | { 411 | Set-ADUser -Identity $SSAUserName -PasswordNeverExpires $True @SSAApplicationUser -Server $SSAActiveDirectoryDomain -ErrorAction Stop 412 | Add-SSAOutput -OutputText "Option 'Password never expires' has been enabled for user '$SSAUserName'." 413 | } 414 | } 415 | else 416 | { 417 | if ($QueryADUser.PasswordNeverExpires -ne $False) 418 | { 419 | Set-ADUser -Identity $SSAUserName -PasswordNeverExpires $False @SSAApplicationUser -Server $SSAActiveDirectoryDomain -ErrorAction Stop 420 | Add-SSAOutput -OutputText "Option 'Password never expires' has been disabled for user '$SSAUserName'." 421 | } 422 | } 423 | } 424 | else 425 | { 426 | Add-SSAOutput -OutputText "Passwords do not match, please review your input." 427 | } 428 | } 429 | else 430 | { 431 | Add-SSAOutput -OutputText "One or both password fields are empty, please review your input." 432 | } 433 | } 434 | catch 435 | { 436 | Add-SSAOutput -OutputText "$_" 437 | } 438 | } 439 | else 440 | { 441 | Add-SSAOutput -OutputText "UserName field is empty, please review your input." 442 | } 443 | } 444 | else 445 | { 446 | Add-SSAOutput -OutputText "ActiveDirectory PowerShell module is currently not loaded, cannot proceed with the request. Restart the application to attempt load the module." 447 | } 448 | } 449 | 450 | # Scroll Output window to bottom. 451 | $RichTextBoxMainOutput_TextChanged = 452 | { 453 | $RichTextBoxMainOutput.SelectionStart = $RichTextBoxMainOutput.Text.Length 454 | $RichTextBoxMainOutput.ScrollToCaret() 455 | } 456 | 457 | #################################################################################################### 458 | ### End: Form > Main ############################################################################### 459 | #################################################################################################### 460 | #endregion 461 | # --End User Generated Script-- 462 | #---------------------------------------------- 463 | #region Generated Events 464 | #---------------------------------------------- 465 | 466 | $Form_StateCorrection_Load= 467 | { 468 | #Correct the initial state of the form to prevent the .Net maximized form issue 469 | $FormMain.WindowState = $InitialFormWindowState 470 | } 471 | 472 | $Form_StoreValues_Closing= 473 | { 474 | #Store the control values 475 | $script:MainForm_RichTextBoxMainOutput = $RichTextBoxMainOutput.Text 476 | $script:MainForm_CheckBoxMainChangePasswordPasswordNeverExpires = $CheckBoxMainChangePasswordPasswordNeverExpires.Checked 477 | $script:MainForm_CheckBoxMainChangePasswordUserCannotChangePassword = $CheckBoxMainChangePasswordUserCannotChangePassword.Checked 478 | $script:MainForm_CheckBoxMainChangePasswordUserMustChangePasswordAtNextLogon = $CheckBoxMainChangePasswordUserMustChangePasswordAtNextLogon.Checked 479 | $script:MainForm_TextBoxMainNewPassword2 = $TextBoxMainNewPassword2.Text 480 | $script:MainForm_TextBoxMainNewPassword1 = $TextBoxMainNewPassword1.Text 481 | $script:MainForm_TextBoxMainUserName = $TextBoxMainUserName.Text 482 | } 483 | 484 | 485 | $Form_Cleanup_FormClosed= 486 | { 487 | #Remove all event handlers from the controls 488 | try 489 | { 490 | $RichTextBoxMainOutput.remove_TextChanged($RichTextBoxMainOutput_TextChanged) 491 | $CheckBoxMainChangePasswordPasswordNeverExpires.remove_CheckedChanged($CheckBoxMainChangePasswordPasswordNeverExpires_CheckedChanged) 492 | $CheckBoxMainChangePasswordUserCannotChangePassword.remove_CheckedChanged($CheckBoxMainChangePasswordUserCannotChangePassword_CheckedChanged) 493 | $CheckBoxMainChangePasswordUserMustChangePasswordAtNextLogon.remove_CheckedChanged($CheckBoxMainChangePasswordUserMustChangePasswordAtNextLogon_CheckedChanged) 494 | $ButtonMainChangePasswordChangePassword.remove_Click($ButtonMainChangePasswordChangePassword_Click) 495 | $FormMain.remove_Load($FormMain_Load) 496 | $FormMain.remove_Shown($FormMain_Shown) 497 | $ToolStripMenuItemMainFileLog.remove_Click($ToolStripMenuItemMainFileLog_Click) 498 | $ToolStripMenuItemMainFileAbout.remove_Click($ToolStripMenuItemMainFileAbout_Click) 499 | $ToolStripMenuItemMainFileExit.remove_Click($ToolStripMenuItemMainFileExit_Click) 500 | $ToolStripMenuItemMainCredentialsEnterCredentials.remove_Click($ToolStripMenuItemMainCredentialsEnterCredentials_Click) 501 | $ToolStripMenuItemMainCredentialsClearCredentials.remove_Click($ToolStripMenuItemMainCredentialsClearCredentials_Click) 502 | $ToolStripMenuItemMainDomain.remove_Click($ToolStripMenuItemMainDomain_Click) 503 | $FormMain.remove_Load($Form_StateCorrection_Load) 504 | $FormMain.remove_Closing($Form_StoreValues_Closing) 505 | $FormMain.remove_FormClosed($Form_Cleanup_FormClosed) 506 | } 507 | catch { Out-Null <# Prevent PSScriptAnalyzer warning #> } 508 | } 509 | #endregion Generated Events 510 | 511 | #---------------------------------------------- 512 | #region Generated Form Code 513 | #---------------------------------------------- 514 | $FormMain.SuspendLayout() 515 | $GroupBoxMainOutput.SuspendLayout() 516 | $GroupBoxMainChangePassword.SuspendLayout() 517 | $GroupBoxMainNewPassword.SuspendLayout() 518 | $GroupBoxMainUserName.SuspendLayout() 519 | $MenuStripMain.SuspendLayout() 520 | # 521 | # FormMain 522 | # 523 | $FormMain.Controls.Add($GroupBoxMainOutput) 524 | $FormMain.Controls.Add($GroupBoxMainChangePassword) 525 | $FormMain.Controls.Add($GroupBoxMainNewPassword) 526 | $FormMain.Controls.Add($GroupBoxMainUserName) 527 | $FormMain.Controls.Add($MenuStripMain) 528 | $FormMain.AutoScaleDimensions = '6, 13' 529 | $FormMain.AutoScaleMode = 'Font' 530 | $FormMain.ClientSize = '589, 403' 531 | $FormMain.MainMenuStrip = $MenuStripMain 532 | $FormMain.MinimumSize = '605, 442' 533 | $FormMain.Name = 'FormMain' 534 | $FormMain.StartPosition = 'CenterScreen' 535 | $FormMain.Text = 'ADUserResetPassword' 536 | $FormMain.add_Load($FormMain_Load) 537 | $FormMain.add_Shown($FormMain_Shown) 538 | # 539 | # GroupBoxMainOutput 540 | # 541 | $GroupBoxMainOutput.Controls.Add($RichTextBoxMainOutput) 542 | $GroupBoxMainOutput.Anchor = 'Top, Bottom, Left, Right' 543 | $GroupBoxMainOutput.Location = '13, 181' 544 | $GroupBoxMainOutput.Name = 'GroupBoxMainOutput' 545 | $GroupBoxMainOutput.Size = '563, 209' 546 | $GroupBoxMainOutput.TabIndex = 5 547 | $GroupBoxMainOutput.TabStop = $False 548 | $GroupBoxMainOutput.Text = 'Output' 549 | # 550 | # RichTextBoxMainOutput 551 | # 552 | $RichTextBoxMainOutput.Anchor = 'Top, Bottom, Left, Right' 553 | $RichTextBoxMainOutput.Font = 'Consolas, 8.25pt' 554 | $RichTextBoxMainOutput.Location = '7, 20' 555 | $RichTextBoxMainOutput.Name = 'RichTextBoxMainOutput' 556 | $RichTextBoxMainOutput.ScrollBars = 'ForcedVertical' 557 | $RichTextBoxMainOutput.Size = '548, 179' 558 | $RichTextBoxMainOutput.TabIndex = 0 559 | $RichTextBoxMainOutput.Text = '' 560 | $RichTextBoxMainOutput.add_TextChanged($RichTextBoxMainOutput_TextChanged) 561 | # 562 | # GroupBoxMainChangePassword 563 | # 564 | $GroupBoxMainChangePassword.Controls.Add($CheckBoxMainChangePasswordPasswordNeverExpires) 565 | $GroupBoxMainChangePassword.Controls.Add($CheckBoxMainChangePasswordUserCannotChangePassword) 566 | $GroupBoxMainChangePassword.Controls.Add($CheckBoxMainChangePasswordUserMustChangePasswordAtNextLogon) 567 | $GroupBoxMainChangePassword.Controls.Add($ButtonMainChangePasswordChangePassword) 568 | $GroupBoxMainChangePassword.Location = '320, 28' 569 | $GroupBoxMainChangePassword.Name = 'GroupBoxMainChangePassword' 570 | $GroupBoxMainChangePassword.Size = '256, 147' 571 | $GroupBoxMainChangePassword.TabIndex = 3 572 | $GroupBoxMainChangePassword.TabStop = $False 573 | $GroupBoxMainChangePassword.Text = 'Change Password' 574 | # 575 | # CheckBoxMainChangePasswordPasswordNeverExpires 576 | # 577 | $CheckBoxMainChangePasswordPasswordNeverExpires.Location = '6, 82' 578 | $CheckBoxMainChangePasswordPasswordNeverExpires.Name = 'CheckBoxMainChangePasswordPasswordNeverExpires' 579 | $CheckBoxMainChangePasswordPasswordNeverExpires.Size = '243, 24' 580 | $CheckBoxMainChangePasswordPasswordNeverExpires.TabIndex = 3 581 | $CheckBoxMainChangePasswordPasswordNeverExpires.Text = 'Password never expires' 582 | $CheckBoxMainChangePasswordPasswordNeverExpires.UseVisualStyleBackColor = $True 583 | $CheckBoxMainChangePasswordPasswordNeverExpires.add_CheckedChanged($CheckBoxMainChangePasswordPasswordNeverExpires_CheckedChanged) 584 | # 585 | # CheckBoxMainChangePasswordUserCannotChangePassword 586 | # 587 | $CheckBoxMainChangePasswordUserCannotChangePassword.Location = '6, 51' 588 | $CheckBoxMainChangePasswordUserCannotChangePassword.Name = 'CheckBoxMainChangePasswordUserCannotChangePassword' 589 | $CheckBoxMainChangePasswordUserCannotChangePassword.Size = '243, 24' 590 | $CheckBoxMainChangePasswordUserCannotChangePassword.TabIndex = 2 591 | $CheckBoxMainChangePasswordUserCannotChangePassword.Text = 'User cannot change password' 592 | $CheckBoxMainChangePasswordUserCannotChangePassword.UseVisualStyleBackColor = $True 593 | $CheckBoxMainChangePasswordUserCannotChangePassword.add_CheckedChanged($CheckBoxMainChangePasswordUserCannotChangePassword_CheckedChanged) 594 | # 595 | # CheckBoxMainChangePasswordUserMustChangePasswordAtNextLogon 596 | # 597 | $CheckBoxMainChangePasswordUserMustChangePasswordAtNextLogon.Location = '6, 20' 598 | $CheckBoxMainChangePasswordUserMustChangePasswordAtNextLogon.Name = 'CheckBoxMainChangePasswordUserMustChangePasswordAtNextLogon' 599 | $CheckBoxMainChangePasswordUserMustChangePasswordAtNextLogon.Size = '243, 24' 600 | $CheckBoxMainChangePasswordUserMustChangePasswordAtNextLogon.TabIndex = 1 601 | $CheckBoxMainChangePasswordUserMustChangePasswordAtNextLogon.Text = 'User must change password at next logon' 602 | $CheckBoxMainChangePasswordUserMustChangePasswordAtNextLogon.UseVisualStyleBackColor = $True 603 | $CheckBoxMainChangePasswordUserMustChangePasswordAtNextLogon.add_CheckedChanged($CheckBoxMainChangePasswordUserMustChangePasswordAtNextLogon_CheckedChanged) 604 | # 605 | # ButtonMainChangePasswordChangePassword 606 | # 607 | $ButtonMainChangePasswordChangePassword.Location = '6, 112' 608 | $ButtonMainChangePasswordChangePassword.Name = 'ButtonMainChangePasswordChangePassword' 609 | $ButtonMainChangePasswordChangePassword.Size = '243, 28' 610 | $ButtonMainChangePasswordChangePassword.TabIndex = 4 611 | $ButtonMainChangePasswordChangePassword.Text = 'Change Password' 612 | $ButtonMainChangePasswordChangePassword.UseVisualStyleBackColor = $True 613 | $ButtonMainChangePasswordChangePassword.add_Click($ButtonMainChangePasswordChangePassword_Click) 614 | # 615 | # GroupBoxMainNewPassword 616 | # 617 | $GroupBoxMainNewPassword.Controls.Add($TextBoxMainNewPassword2) 618 | $GroupBoxMainNewPassword.Controls.Add($TextBoxMainNewPassword1) 619 | $GroupBoxMainNewPassword.Location = '12, 100' 620 | $GroupBoxMainNewPassword.Name = 'GroupBoxMainNewPassword' 621 | $GroupBoxMainNewPassword.Size = '301, 75' 622 | $GroupBoxMainNewPassword.TabIndex = 2 623 | $GroupBoxMainNewPassword.TabStop = $False 624 | $GroupBoxMainNewPassword.Text = 'New Password (twice)' 625 | # 626 | # TextBoxMainNewPassword2 627 | # 628 | $TextBoxMainNewPassword2.Font = 'Consolas, 8.25pt' 629 | $TextBoxMainNewPassword2.Location = '8, 47' 630 | $TextBoxMainNewPassword2.Name = 'TextBoxMainNewPassword2' 631 | $TextBoxMainNewPassword2.Size = '286, 20' 632 | $TextBoxMainNewPassword2.TabIndex = 1 633 | $TextBoxMainNewPassword2.UseSystemPasswordChar = $True 634 | # 635 | # TextBoxMainNewPassword1 636 | # 637 | $TextBoxMainNewPassword1.Font = 'Consolas, 8.25pt' 638 | $TextBoxMainNewPassword1.Location = '7, 20' 639 | $TextBoxMainNewPassword1.Name = 'TextBoxMainNewPassword1' 640 | $TextBoxMainNewPassword1.Size = '287, 20' 641 | $TextBoxMainNewPassword1.TabIndex = 0 642 | $TextBoxMainNewPassword1.UseSystemPasswordChar = $True 643 | # 644 | # GroupBoxMainUserName 645 | # 646 | $GroupBoxMainUserName.Controls.Add($TextBoxMainUserName) 647 | $GroupBoxMainUserName.Location = '12, 28' 648 | $GroupBoxMainUserName.Name = 'GroupBoxMainUserName' 649 | $GroupBoxMainUserName.Size = '300, 49' 650 | $GroupBoxMainUserName.TabIndex = 1 651 | $GroupBoxMainUserName.TabStop = $False 652 | $GroupBoxMainUserName.Text = 'UserName (SamAccountName)' 653 | # 654 | # TextBoxMainUserName 655 | # 656 | $TextBoxMainUserName.Font = 'Consolas, 8.25pt' 657 | $TextBoxMainUserName.Location = '7, 20' 658 | $TextBoxMainUserName.Name = 'TextBoxMainUserName' 659 | $TextBoxMainUserName.Size = '287, 20' 660 | $TextBoxMainUserName.TabIndex = 0 661 | # 662 | # MenuStripMain 663 | # 664 | [void]$MenuStripMain.Items.Add($ToolStripMenuItemMainFile) 665 | [void]$MenuStripMain.Items.Add($ToolStripMenuItemMainCredentials) 666 | [void]$MenuStripMain.Items.Add($ToolStripMenuItemMainDomain) 667 | $MenuStripMain.Location = '0, 0' 668 | $MenuStripMain.Name = 'MenuStripMain' 669 | $MenuStripMain.Size = '589, 24' 670 | $MenuStripMain.TabIndex = 0 671 | $MenuStripMain.Text = 'menustrip1' 672 | # 673 | # ToolStripMenuItemMainFile 674 | # 675 | [void]$ToolStripMenuItemMainFile.DropDownItems.Add($ToolStripMenuItemMainFileAbout) 676 | [void]$ToolStripMenuItemMainFile.DropDownItems.Add($ToolStripMenuItemMainFileLog) 677 | [void]$ToolStripMenuItemMainFile.DropDownItems.Add($ToolStripMenuItemMainFileExit) 678 | $ToolStripMenuItemMainFile.Name = 'ToolStripMenuItemMainFile' 679 | $ToolStripMenuItemMainFile.Size = '37, 20' 680 | $ToolStripMenuItemMainFile.Text = 'File' 681 | # 682 | # ToolStripMenuItemMainFileLog 683 | # 684 | $ToolStripMenuItemMainFileLog.Name = 'ToolStripMenuItemMainFileLog' 685 | $ToolStripMenuItemMainFileLog.Size = '107, 22' 686 | $ToolStripMenuItemMainFileLog.Text = 'Log' 687 | $ToolStripMenuItemMainFileLog.add_Click($ToolStripMenuItemMainFileLog_Click) 688 | # 689 | # ToolStripMenuItemMainFileAbout 690 | # 691 | $ToolStripMenuItemMainFileAbout.Name = 'ToolStripMenuItemMainFileAbout' 692 | $ToolStripMenuItemMainFileAbout.Size = '107, 22' 693 | $ToolStripMenuItemMainFileAbout.Text = 'About' 694 | $ToolStripMenuItemMainFileAbout.add_Click($ToolStripMenuItemMainFileAbout_Click) 695 | # 696 | # ToolStripMenuItemMainFileExit 697 | # 698 | $ToolStripMenuItemMainFileExit.Name = 'ToolStripMenuItemMainFileExit' 699 | $ToolStripMenuItemMainFileExit.Size = '152, 22' 700 | $ToolStripMenuItemMainFileExit.Text = 'Exit' 701 | $ToolStripMenuItemMainFileExit.add_Click($ToolStripMenuItemMainFileExit_Click) 702 | # 703 | # ToolStripMenuItemMainCredentials 704 | # 705 | [void]$ToolStripMenuItemMainCredentials.DropDownItems.Add($ToolStripMenuItemMainCredentialsEnterCredentials) 706 | [void]$ToolStripMenuItemMainCredentials.DropDownItems.Add($ToolStripMenuItemMainCredentialsClearCredentials) 707 | $ToolStripMenuItemMainCredentials.Name = 'ToolStripMenuItemMainCredentials' 708 | $ToolStripMenuItemMainCredentials.Size = '78, 20' 709 | $ToolStripMenuItemMainCredentials.Text = 'Credentials' 710 | # 711 | # ToolStripMenuItemMainCredentialsEnterCredentials 712 | # 713 | $ToolStripMenuItemMainCredentialsEnterCredentials.Name = 'ToolStripMenuItemMainCredentialsEnterCredentials' 714 | $ToolStripMenuItemMainCredentialsEnterCredentials.Size = '163, 22' 715 | $ToolStripMenuItemMainCredentialsEnterCredentials.Text = 'Enter Credentials' 716 | $ToolStripMenuItemMainCredentialsEnterCredentials.add_Click($ToolStripMenuItemMainCredentialsEnterCredentials_Click) 717 | # 718 | # ToolStripMenuItemMainCredentialsClearCredentials 719 | # 720 | $ToolStripMenuItemMainCredentialsClearCredentials.Enabled = $False 721 | $ToolStripMenuItemMainCredentialsClearCredentials.Name = 'ToolStripMenuItemMainCredentialsClearCredentials' 722 | $ToolStripMenuItemMainCredentialsClearCredentials.Size = '163, 22' 723 | $ToolStripMenuItemMainCredentialsClearCredentials.Text = 'Clear Credentials' 724 | $ToolStripMenuItemMainCredentialsClearCredentials.add_Click($ToolStripMenuItemMainCredentialsClearCredentials_Click) 725 | # 726 | # ToolStripMenuItemMainDomain 727 | # 728 | $ToolStripMenuItemMainDomain.Name = 'ToolStripMenuItemMainDomain' 729 | $ToolStripMenuItemMainDomain.Size = '61, 20' 730 | $ToolStripMenuItemMainDomain.Text = 'Domain' 731 | $ToolStripMenuItemMainDomain.add_Click($ToolStripMenuItemMainDomain_Click) 732 | $MenuStripMain.ResumeLayout() 733 | $GroupBoxMainUserName.ResumeLayout() 734 | $GroupBoxMainNewPassword.ResumeLayout() 735 | $GroupBoxMainChangePassword.ResumeLayout() 736 | $GroupBoxMainOutput.ResumeLayout() 737 | $FormMain.ResumeLayout() 738 | #endregion Generated Form Code 739 | 740 | #---------------------------------------------- 741 | 742 | #Save the initial state of the form 743 | $InitialFormWindowState = $FormMain.WindowState 744 | #Init the OnLoad event to correct the initial state of the form 745 | $FormMain.add_Load($Form_StateCorrection_Load) 746 | #Clean up the control events 747 | $FormMain.add_FormClosed($Form_Cleanup_FormClosed) 748 | #Store the control values when form is closing 749 | $FormMain.add_Closing($Form_StoreValues_Closing) 750 | #Show the Form 751 | return $FormMain.ShowDialog() 752 | 753 | } 754 | #endregion Source: MainForm.psf 755 | 756 | #region Source: Globals.ps1 757 | #################################################################################################### 758 | ### Begin: Custom functions ######################################################################## 759 | #################################################################################################### 760 | 761 | #region function Add-SSAOutput 762 | function Add-SSAOutput 763 | { 764 | [CmdletBinding()] 765 | Param 766 | ( 767 | [Parameter( 768 | Mandatory = $true 769 | ) 770 | ] 771 | $OutputText 772 | ) 773 | Begin 774 | { 775 | } 776 | Process 777 | { 778 | $OutputDate = Get-Date -UFormat "%Y-%m-%d" 779 | $OutputTime = Get-Date -UFormat "%H:%M:%S" 780 | $RichTextBoxMainOutput.Text += "[$OutputDate][$OutputTime] $OutputText`n" 781 | Add-Content -Path $SSALogFile -Value "[$OutputDate][$OutputTime] $OutputText`n" 782 | } 783 | End 784 | { 785 | } 786 | } 787 | #endregion 788 | 789 | #region function Import-SSAActiveDirectoryModule 790 | function Import-SSAActiveDirectoryModule 791 | { 792 | [CmdletBinding()] 793 | Param 794 | ( 795 | ) 796 | Begin 797 | { 798 | } 799 | Process 800 | { 801 | Add-SSAOutput -OutputText "Loading ActiveDirectory PowerShell module." 802 | if ((Get-Module -name "ActiveDirectory") -eq $null) 803 | { 804 | Add-SSAOutput -OutputText "ActiveDirectory PowerShell module is currently not loaded." 805 | if (Get-Module -ListAvailable | Where-Object { $_.name -eq "ActiveDirectory" }) 806 | { 807 | Add-SSAOutput -OutputText "ActiveDirectory PowerShell module is available, importing module." 808 | Import-Module -Name "ActiveDirectory" 809 | if ((Get-Module -name "ActiveDirectory") -eq $null) 810 | { 811 | Add-SSAOutput -OutputText "ActiveDirectory PowerShell module could not be loaded." 812 | $global:SSAActiveDirectoryModuleLoaded = $false 813 | } 814 | else 815 | { 816 | Add-SSAOutput -OutputText "ActiveDirectory PowerShell module has been loaded." 817 | $global:SSAActiveDirectoryModuleLoaded = $true 818 | } 819 | } 820 | else 821 | { 822 | Add-SSAOutput -OutputText "ActiveDirectory PowerShell module is not available on this computer, attempting to import it from a Domain Controller." 823 | try 824 | { 825 | $DomainDNSName = (Get-WmiObject -Class WIN32_ComputerSystem -ErrorAction Stop).Domain 826 | $DomainNetBiosName = (Get-WmiObject -Class Win32_NTDomain -Filter "DnsForestName = '$((Get-WmiObject Win32_ComputerSystem).Domain)'" -ErrorAction Stop).DomainName 827 | $DomainControllerName = ((Get-WmiObject -Class WIN32_NTDomain -Filter "DomainName = '$DomainNetBiosName'" -ErrorAction Stop).DomainControllerName) -replace "\\", "" 828 | $DomainController = "$DomainControllerName.$DomainDNSName" 829 | $DomainControllerSession = New-PSSession -Computername $DomainController -ErrorAction Stop 830 | Invoke-Command -Command { Import-Module -Name "ActiveDirectory" } -Session $DomainControllerSession -ErrorAction Stop 831 | $ImportSession = Import-PSSession -Session $DomainControllerSession -Module ActiveDirectory -AllowClobber -ErrorAction Stop 832 | if ($ImportSession.Name) 833 | { 834 | Add-SSAOutput -OutputText "ActiveDirectory PowerShell module has been imported from Domain Controller $DomainController." 835 | $global:SSAActiveDirectoryModuleLoaded = $true 836 | } 837 | } 838 | catch 839 | { 840 | Add-SSAOutput -OutputText "ActiveDirectory PowerShell module could not be imported. Possible reasons are: This workstation is not joined to the Active Directory domain, PowerShell remoting towards the Domain Controller does not work or is not setup, the current user does not have appropriate rights to open a PowerShell session to the Domain Controller." 841 | $global:SSAActiveDirectoryModuleLoaded = $false 842 | } 843 | } 844 | } 845 | else 846 | { 847 | Add-SSAOutput -OutputText "ActiveDirectory PowerShell module is already loaded." 848 | $global:SSAActiveDirectoryModuleLoaded = $true 849 | } 850 | } 851 | End 852 | { 853 | } 854 | } 855 | #endregion 856 | 857 | #region function Get-SSAUserName 858 | function Get-SSAUserName 859 | { 860 | [CmdletBinding()] 861 | Param 862 | ( 863 | ) 864 | Begin 865 | { 866 | } 867 | Process 868 | { 869 | $global:SSAUserName = $TextBoxMainUserName.text 870 | } 871 | End 872 | { 873 | } 874 | } 875 | #endregion 876 | 877 | #region function Get-SSAPassword1 878 | function Get-SSAPassword1 879 | { 880 | [CmdletBinding()] 881 | Param 882 | ( 883 | ) 884 | Begin 885 | { 886 | } 887 | Process 888 | { 889 | $global:SSAPassword1 = $TextBoxMainNewPassword1.text 890 | } 891 | End 892 | { 893 | } 894 | } 895 | #endregion 896 | 897 | #region function Get-SSAPassword2 898 | function Get-SSAPassword2 899 | { 900 | [CmdletBinding()] 901 | Param 902 | ( 903 | ) 904 | Begin 905 | { 906 | } 907 | Process 908 | { 909 | $global:SSAPassword2 = $TextBoxMainNewPassword2.text 910 | } 911 | End 912 | { 913 | } 914 | } 915 | #endregion 916 | 917 | #################################################################################################### 918 | ### End: Custom functions ########################################################################## 919 | #################################################################################################### 920 | 921 | #endregion Source: Globals.ps1 922 | 923 | #Start the application 924 | Main ($CommandLine) 925 | -------------------------------------------------------------------------------- /Scripts/GUI/AD/ADUserUnlock.ps1: -------------------------------------------------------------------------------- 1 | #------------------------------------------------------------------------ 2 | # Source File Information (DO NOT MODIFY) 3 | # Source ID: 44edef10-2e31-4c78-b361-2532a3176b0d 4 | # Source File: ADUserUnlock.psproj 5 | #------------------------------------------------------------------------ 6 | #region Project Recovery Data (DO NOT MODIFY) 7 | <#RecoveryData: 8 | 9QEAAB+LCAAAAAAABACNkc1vgyAchu9N+j8Y71RR1+5ASbYYlx72kX7suiD+XFkpGNAu/e/HJjZ2 9 | u+zGAy/Pmx+QNXB9AnPOWcvodBIE5MXoD+DtDzh8BWOFVjSZxSQawJ8VQsIqp1kGFdQ4RgmkGGV8 10 | cYvKdI5RcpMmLMWLeRlXJPJhf9W3bM8NUCce4yDXsnJ1QTRusx48BvedkNUyjEO6aZlpu2bWWNt3 11 | /UquoQYDikPRKd66IZbhZq8/0SMTqtDm+NbYOhz5hn0nrP8rXKmTPgB6kLpk0jojHhmDzZ4ZcMut 12 | 6SCkPuT0+ErfQz/n5V16ejbiXSgmvwNP7Aj0Lt9ZMDslNT84UePCJPqTmk5IdPXNX/WGaW71AQAA#> 13 | #endregion 14 | <# 15 | .NOTES 16 | -------------------------------------------------------------------------------- 17 | Code generated by: SAPIEN Technologies, Inc., PowerShell Studio 2016 v5.3.130 18 | Generated on: 2016-12-08 18:55 19 | Generated by: ibelmans 20 | -------------------------------------------------------------------------------- 21 | .DESCRIPTION 22 | Script generated by PowerShell Studio 2016 23 | #> 24 | 25 | 26 | #region Source: Startup.pss 27 | #region File Recovery Data (DO NOT MODIFY) 28 | <#RecoveryData: 29 | ZAMAAB+LCAAAAAAABAC9k99Lw0AMx98F/4djz+Xa2tU6uBZkshdBxYn6mnbpOLwfI7lz9L93mzJF 30 | HwSRkpd8E5IPIYm6x86/Ig1XEEDsHNbe1ZMzmU+a0xMh1C3ptXZgFtrgDVhslgEoxI3cMKv0R/ZQ 31 | c8mMtjUa+aA/I0NjufNkdJuIxw/WVGZ7S8Q8mhAJa4cxEJhE3MVdj+4ahwf/gq5uqwrKrjzPZ8UU 32 | s4uZSo9dv1OWAwe0YzDkk3Yrv2W58GR5FOJ+U+OACLbarf/Cyoq+7Ks+z1dlBgX8znq2ZpSZ5p7w 33 | /0FH+X7yKv36Vc0baArZVmQDAAA=#> 34 | #endregion 35 | #---------------------------------------------- 36 | #region Import Assemblies 37 | #---------------------------------------------- 38 | [void][Reflection.Assembly]::Load('System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089') 39 | [void][Reflection.Assembly]::Load('System.Data, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089') 40 | [void][Reflection.Assembly]::Load('System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a') 41 | #endregion Import Assemblies 42 | 43 | #################################################################################################### 44 | ### Begin: Script information ###################################################################### 45 | #################################################################################################### 46 | 47 | <# 48 | .SYNOPSIS 49 | PowerShell GUI script to unlock an Active Directory user's account. 50 | .DESCRIPTION 51 | PowerShell GUI script to unlock an Active Directory user's account. 52 | .NOTES 53 | Author : Ingvald Belmans 54 | Website : http://www.supersysadmin.com 55 | Version : 1.0 56 | Changelog: 57 | - 1.0 (2016-01-05) Initial version. 58 | - 1.1 (2016-12-08) Fixed bug where error handling was not working when using implicit remoting for the ActiveDirectory PowerShell module. 59 | .LINK 60 | http://www.supersysadmin.com 61 | #> 62 | 63 | #################################################################################################### 64 | ### End: Script information ######################################################################## 65 | #################################################################################################### 66 | 67 | #################################################################################################### 68 | ### Begin: Main function ########################################################################### 69 | #################################################################################################### 70 | 71 | #region function Main 72 | function Main 73 | { 74 | <# 75 | .SYNOPSIS 76 | The Main function starts the project application. 77 | 78 | .PARAMETER Commandline 79 | $Commandline contains the complete argument string passed to the script packager executable. 80 | 81 | .NOTES 82 | Use this function to initialize your script and to call GUI forms. 83 | 84 | .NOTES 85 | To get the console output in the Packager (Forms Engine) use: 86 | $ConsoleOutput (Type: System.Collections.ArrayList) 87 | #> 88 | Param 89 | ( 90 | [String]$Commandline 91 | ) 92 | if ((Show-MainForm_psf) -eq 'OK') 93 | { 94 | } 95 | $global:ExitCode = 0 #Set the exit code for the Packager 96 | } 97 | #endregion 98 | 99 | #################################################################################################### 100 | ### End: Main function ############################################################################# 101 | #################################################################################################### 102 | 103 | #endregion Source: Startup.pss 104 | 105 | #region Source: MainForm.psf 106 | function Show-MainForm_psf 107 | { 108 | #region File Recovery Data (DO NOT MODIFY) 109 | <#RecoveryData: 110 | jCIAAB+LCAAAAAAABADdWm1v6jYU/j5p/8HKp01CQBIoIAESL7fT1drdrum927fKBANeHRs5Tlv2 111 | 62cnoQRiiMMAXa4qoZqcV5/Hz3GO6D4in70ivhpDAYH8J8SM9iynalv9n38CoPuF4zmmkNxigv6A 112 | AerfQ0xvGQ+qy3DWreUeJ0qTf5AvgFgtUc/yVqFAQfUvTKfsLawq3eSzAnSPKuBbGkWjWld/FTCK 113 | iIg46lEUCQ5JBTxEE4L939Hqib0g2pu0WrDpN2/sjttA9XbHAlSG0rOUPRWuBfwFJlMuRa0Ro4Iz 114 | EibpyVgfOFsiLlapziASzPMhQWMcIKrikKI3FWC73dpatEj1nk2R1b+Vngp1RgQjKjz8r1S4cd0K 115 | cDrtQiWV0z2ikSc4Xq4TkWKPaIZkkj5ay61lkk2orc0V2scUB1GQRtXoVIDrtgq1VPlV1smeF4p7 116 | AnLxwEIs5B5b/ZHcBsQ9nyNUrPuE3oXVH4y/hoh/pYT5L+DVrtbzep9epdlU6Y7B6Sa+Z7Xs1mIB 117 | nbS3YG80Ix6vd+SLYf4bZ9FyyN7PDvW1IxXrl0gsI3EI9BrsUn/BuNV/YssKGDIhmDyed2gmKuAR 118 | zxd5IOdN3DEfJrW0JY7bHQOVBDL52A1UU3DWJTjtjomvJzj5TKfo3ernT7JW2hNMHq5bSEJkohBD 119 | cn/4xVh5xP5CWbkEXDK+TBFzEszkjSiWlKdf0iwjUKbYrjrNpZnqBnAtBQIjnQRx2vSN9CVBMUKG 120 | kIcxN/hoKmsisGR9M/UYtc2OaiithpHKBrd5ftsPxMxzrVKW6pTGaAHpHE33bM1zRmSbA5X9BNof 121 | zWV7+Z1yZNI1Br7PIlqSKjewcx0ZjZPv1yZEtxWAMd+5dacCmjrg7IeNcz66S3vvgSyKyz+MJHHQ 122 | sxc/cZPb+RI4ONjxmg2JBLMDmmDBJJ4SlGI3JDAcXWc7BA27BKMU1jqvKK9n33AYQeKJFUFD6L+M 123 | GIk7Bo90INvhJXk39l/Mduo5li2gpiuA45+RfBWTsHqRt2MRhccDsnUaOO7EUwqQ9hGALNPi4tiA 124 | Cg6UiO6smNzZLiNUXkvDlK9aMVSO7JXqneDYVpm6LtEl66W7pI4KT9Ul0/jBLx4MUqSo9a/HNcxL 125 | vSNkboFmxT/f5b4UlWniLsFbTtvc32He+t/n/GN8c/ZS7wyKypzwzzKubQyobw7ilzGSOJNelfD5 126 | 0suEpRmP5QKJR5uYoM2oLCmcepYpa4lJiAxaCw0tcLeqYD4CiaeG5cjOJKaEuw7HtIXp7YUBj10O 127 | B4UF3zNnHMvlmL3RHZB/pxA3B/gdm2cxvovwa09vMGFqmvXjJvjpHe/Pz3BQv9d48eQ+uWTp+6Se 128 | RjR2r5gu1PE5bm+lpuH22nW1v/nZjX5/tXY17y2HAsu/rVxxiRIKOK5Ise5ZyrTHcplCxSZ+qFLF 129 | ZHZcpZSqaaGaTolC6Q2XqZOyUFSmQRiiQG4eCtce0m9W/SD0GSd4coICdGsfVne9JCW/hI+Tw6rY 130 | o/pFw2UccfiG6fwYX3V31py1ZrY9bdahC4t9/R2Qi+Q0Yhyd3tHHMoF8t5b99Un/P2OcKQyMIgAA#> 131 | #endregion 132 | #---------------------------------------------- 133 | #region Import the Assemblies 134 | #---------------------------------------------- 135 | [void][reflection.assembly]::Load('System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089') 136 | [void][reflection.assembly]::Load('System.Data, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089') 137 | [void][reflection.assembly]::Load('System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a') 138 | [void][reflection.assembly]::Load('System.Design, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a') 139 | #endregion Import Assemblies 140 | 141 | #---------------------------------------------- 142 | #region Generated Form Objects 143 | #---------------------------------------------- 144 | [System.Windows.Forms.Application]::EnableVisualStyles() 145 | $FormMain = New-Object 'System.Windows.Forms.Form' 146 | $GroupBoxMainOutput = New-Object 'System.Windows.Forms.GroupBox' 147 | $RichTextBoxMainOutput = New-Object 'System.Windows.Forms.RichTextBox' 148 | $GroupBoxMainUnlockAccount = New-Object 'System.Windows.Forms.GroupBox' 149 | $ButtonMainUnlockAccountUnlockAccount = New-Object 'System.Windows.Forms.Button' 150 | $ButtonMainUnlockAccountQueryLockStatus = New-Object 'System.Windows.Forms.Button' 151 | $GroupBoxMainUserName = New-Object 'System.Windows.Forms.GroupBox' 152 | $TextBoxMainUserName = New-Object 'System.Windows.Forms.TextBox' 153 | $MenuStripMain = New-Object 'System.Windows.Forms.MenuStrip' 154 | $ToolStripMenuItemMainFile = New-Object 'System.Windows.Forms.ToolStripMenuItem' 155 | $ToolStripMenuItemMainFileLog = New-Object 'System.Windows.Forms.ToolStripMenuItem' 156 | $ToolStripMenuItemMainFileAbout = New-Object 'System.Windows.Forms.ToolStripMenuItem' 157 | $ToolStripMenuItemMainFileExit = New-Object 'System.Windows.Forms.ToolStripMenuItem' 158 | $InitialFormWindowState = New-Object 'System.Windows.Forms.FormWindowState' 159 | #endregion Generated Form Objects 160 | 161 | #---------------------------------------------- 162 | # User Generated Script 163 | #---------------------------------------------- 164 | #################################################################################################### 165 | ### Begin: Main form ############################################################################### 166 | #################################################################################################### 167 | 168 | $FormMain_Load = 169 | { 170 | # Create log file 171 | $SSALogFileTimeStamp = Get-Date -UFormat "%Y%m%d_%H%M%S" 172 | $global:SSALogFile = New-Item -ItemType File -Path "$env:USERPROFILE\Documents" -Name "SSA_ADUserUnlock_$SSALogFileTimeStamp.log" 173 | # Set global ErrorActionPreference to Stop to ensure that error handling correctly works when using implicit remoting for the ActiveDirectory PowerShell module 174 | $global:ErrorActionPreference = "Stop" 175 | Add-SSAOutput -OutputText "Creating log file." 176 | if (Test-Path -Path $SSALogFile) 177 | { 178 | Add-SSAOutput -OutputText "Logfile $SSALogFile has been created." 179 | } 180 | else 181 | { 182 | Add-SSAOutput -OutputText "Logfile $SSALogFile could not be created." 183 | } 184 | } 185 | 186 | $FormMain_Shown = 187 | { 188 | Import-SSAActiveDirectoryModule 189 | if ($SSAActiveDirectoryModuleLoaded -eq $false) 190 | { 191 | [System.Windows.Forms.MessageBox]::Show("The ActiveDirectory PowerShell module could not be loaded. You can review the log for more details. Please restart the application to try again.", "Error", [System.Windows.Forms.MessageBoxButtons]::OK, [System.Windows.Forms.MessageBoxIcon]::Error) 192 | } 193 | } 194 | 195 | $ToolStripMenuItemMainFileLog_Click = 196 | { 197 | Invoke-Item -Path $SSALogFile 198 | } 199 | 200 | $ToolStripMenuItemMainFileAbout_Click = 201 | { 202 | Start-Process -FilePath "http://supersysadmin.com/100/powershell-gui-script-to-unlock-an-active-directory-users-account/" 203 | } 204 | 205 | $ToolStripMenuItemMainFileExit_Click = 206 | { 207 | $FormMain.Close() 208 | } 209 | 210 | $ButtonMainUnlockAccountQueryLockStatus_Click = 211 | { 212 | Add-SSAOutput -OutputText "Checking if ActiveDirectory PowerShell module is loaded." 213 | if ($SSAActiveDirectoryModuleLoaded -eq $true) 214 | { 215 | Add-SSAOutput -OutputText "ActiveDirectory PowerShell module is loaded." 216 | Get-SSAUserName 217 | if ($SSAUserName) 218 | { 219 | Add-SSAOutput -OutputText "Checking if user '$SSAUserName' is currently locked." 220 | try 221 | { 222 | $QueryADUser = Get-ADUser -Identity $SSAUserName -Properties LockedOut,lockoutTime -ErrorAction Stop 223 | if ($QueryADUser.LockedOut -eq $true) 224 | { 225 | $QueryADUserLockoutTime = [datetime]::FromFileTime($($QueryADUser.lockoutTime)).ToString('yyyy-MM-dd HH:mm:ss') 226 | Add-SSAOutput -OutputText "User '$SSAUserName' is currently locked (since $QueryADUserLockoutTime)." 227 | } 228 | else 229 | { 230 | Add-SSAOutput -OutputText "User '$SSAUserName' is currently not locked." 231 | } 232 | } 233 | catch [exception] 234 | { 235 | Add-SSAOutput -OutputText "$_" 236 | } 237 | } 238 | else 239 | { 240 | Add-SSAOutput -OutputText "UserName field is empty, please review your input." 241 | } 242 | } 243 | else 244 | { 245 | Add-SSAOutput -OutputText "ActiveDirectory PowerShell module is currently not loaded, cannot proceed with the request. Restart the application to attempt load the module." 246 | } 247 | 248 | } 249 | 250 | $ButtonMainUnlockAccountUnlockAccount_Click = 251 | { 252 | Add-SSAOutput -OutputText "Checking if ActiveDirectory PowerShell module is loaded." 253 | if ($SSAActiveDirectoryModuleLoaded -eq $true) 254 | { 255 | Add-SSAOutput -OutputText "ActiveDirectory PowerShell module is loaded." 256 | Get-SSAUserName 257 | if ($SSAUserName) 258 | { 259 | Add-SSAOutput -OutputText "Checking if user '$SSAUserName' is currently locked." 260 | try 261 | { 262 | $QueryADUser = Get-ADUser -Identity $SSAUserName -Properties LockedOut, lockoutTime -ErrorAction Stop 263 | if ($QueryADUser.LockedOut -eq $true) 264 | { 265 | $QueryADUserLockoutTime = [datetime]::FromFileTime($($QueryADUser.lockoutTime)).ToString('yyyy-MM-dd HH:mm:ss') 266 | Add-SSAOutput -OutputText "User '$SSAUserName' is currently locked (since $QueryADUserLockoutTime)." 267 | Add-SSAOutput -OutputText "Attempting to unlock '$SSAUserName'." 268 | Unlock-ADAccount -Identity $SSAUserName -ErrorAction Stop 269 | $QueryADUser = Get-ADUser -Identity $SSAUserName -Properties LockedOut, lockoutTime -ErrorAction Stop 270 | if ($QueryADUser.LockedOut -eq $false) 271 | { 272 | Add-SSAOutput -OutputText "User '$SSAUserName' is now unlocked." 273 | } 274 | else 275 | { 276 | Add-SSAOutput -OutputText "User '$SSAUserName' could not be unlocked." 277 | } 278 | } 279 | else 280 | { 281 | Add-SSAOutput -OutputText "User '$SSAUserName' is currently not locked." 282 | } 283 | } 284 | catch [exception] 285 | { 286 | Add-SSAOutput -OutputText "$_" 287 | } 288 | } 289 | else 290 | { 291 | Add-SSAOutput -OutputText "UserName field is empty, please review your input." 292 | } 293 | } 294 | else 295 | { 296 | Add-SSAOutput -OutputText "ActiveDirectory PowerShell module is currently not loaded, cannot proceed with the request. Restart the application to attempt load the module." 297 | } 298 | } 299 | 300 | $RichTextBoxMainOutput_TextChanged = 301 | { 302 | $RichTextBoxMainOutput.SelectionStart = $RichTextBoxMainOutput.Text.Length 303 | $RichTextBoxMainOutput.ScrollToCaret() 304 | } 305 | 306 | #################################################################################################### 307 | ### End: Main form ################################################################################# 308 | #################################################################################################### 309 | # --End User Generated Script-- 310 | #---------------------------------------------- 311 | #region Generated Events 312 | #---------------------------------------------- 313 | 314 | $Form_StateCorrection_Load= 315 | { 316 | #Correct the initial state of the form to prevent the .Net maximized form issue 317 | $FormMain.WindowState = $InitialFormWindowState 318 | } 319 | 320 | $Form_StoreValues_Closing= 321 | { 322 | #Store the control values 323 | $script:MainForm_RichTextBoxMainOutput = $RichTextBoxMainOutput.Text 324 | $script:MainForm_TextBoxMainUserName = $TextBoxMainUserName.Text 325 | } 326 | 327 | 328 | $Form_Cleanup_FormClosed= 329 | { 330 | #Remove all event handlers from the controls 331 | try 332 | { 333 | $RichTextBoxMainOutput.remove_TextChanged($RichTextBoxMainOutput_TextChanged) 334 | $ButtonMainUnlockAccountUnlockAccount.remove_Click($ButtonMainUnlockAccountUnlockAccount_Click) 335 | $ButtonMainUnlockAccountQueryLockStatus.remove_Click($ButtonMainUnlockAccountQueryLockStatus_Click) 336 | $FormMain.remove_Load($FormMain_Load) 337 | $FormMain.remove_Shown($FormMain_Shown) 338 | $ToolStripMenuItemMainFileLog.remove_Click($ToolStripMenuItemMainFileLog_Click) 339 | $ToolStripMenuItemMainFileAbout.remove_Click($ToolStripMenuItemMainFileAbout_Click) 340 | $ToolStripMenuItemMainFileExit.remove_Click($ToolStripMenuItemMainFileExit_Click) 341 | $FormMain.remove_Load($Form_StateCorrection_Load) 342 | $FormMain.remove_Closing($Form_StoreValues_Closing) 343 | $FormMain.remove_FormClosed($Form_Cleanup_FormClosed) 344 | } 345 | catch { Out-Null <# Prevent PSScriptAnalyzer warning #> } 346 | } 347 | #endregion Generated Events 348 | 349 | #---------------------------------------------- 350 | #region Generated Form Code 351 | #---------------------------------------------- 352 | $FormMain.SuspendLayout() 353 | $GroupBoxMainOutput.SuspendLayout() 354 | $GroupBoxMainUnlockAccount.SuspendLayout() 355 | $GroupBoxMainUserName.SuspendLayout() 356 | $MenuStripMain.SuspendLayout() 357 | # 358 | # FormMain 359 | # 360 | $FormMain.Controls.Add($GroupBoxMainOutput) 361 | $FormMain.Controls.Add($GroupBoxMainUnlockAccount) 362 | $FormMain.Controls.Add($GroupBoxMainUserName) 363 | $FormMain.Controls.Add($MenuStripMain) 364 | $FormMain.AutoScaleDimensions = '6, 13' 365 | $FormMain.AutoScaleMode = 'Font' 366 | $FormMain.ClientSize = '633, 298' 367 | $FormMain.MainMenuStrip = $MenuStripMain 368 | $FormMain.MinimumSize = '649, 337' 369 | $FormMain.Name = 'FormMain' 370 | $FormMain.StartPosition = 'CenterScreen' 371 | $FormMain.Text = 'ADUserUnlock v1.0' 372 | $FormMain.add_Load($FormMain_Load) 373 | $FormMain.add_Shown($FormMain_Shown) 374 | # 375 | # GroupBoxMainOutput 376 | # 377 | $GroupBoxMainOutput.Controls.Add($RichTextBoxMainOutput) 378 | $GroupBoxMainOutput.Anchor = 'Top, Bottom, Left, Right' 379 | $GroupBoxMainOutput.Location = '13, 89' 380 | $GroupBoxMainOutput.Name = 'GroupBoxMainOutput' 381 | $GroupBoxMainOutput.Size = '609, 199' 382 | $GroupBoxMainOutput.TabIndex = 3 383 | $GroupBoxMainOutput.TabStop = $False 384 | $GroupBoxMainOutput.Text = 'Output' 385 | # 386 | # RichTextBoxMainOutput 387 | # 388 | $RichTextBoxMainOutput.Anchor = 'Top, Bottom, Left, Right' 389 | $RichTextBoxMainOutput.Font = 'Consolas, 8.25pt' 390 | $RichTextBoxMainOutput.Location = '7, 19' 391 | $RichTextBoxMainOutput.Name = 'RichTextBoxMainOutput' 392 | $RichTextBoxMainOutput.ScrollBars = 'ForcedVertical' 393 | $RichTextBoxMainOutput.Size = '596, 174' 394 | $RichTextBoxMainOutput.TabIndex = 0 395 | $RichTextBoxMainOutput.Text = '' 396 | $RichTextBoxMainOutput.add_TextChanged($RichTextBoxMainOutput_TextChanged) 397 | # 398 | # GroupBoxMainUnlockAccount 399 | # 400 | $GroupBoxMainUnlockAccount.Controls.Add($ButtonMainUnlockAccountUnlockAccount) 401 | $GroupBoxMainUnlockAccount.Controls.Add($ButtonMainUnlockAccountQueryLockStatus) 402 | $GroupBoxMainUnlockAccount.Location = '320, 28' 403 | $GroupBoxMainUnlockAccount.Name = 'GroupBoxMainUnlockAccount' 404 | $GroupBoxMainUnlockAccount.Size = '302, 54' 405 | $GroupBoxMainUnlockAccount.TabIndex = 2 406 | $GroupBoxMainUnlockAccount.TabStop = $False 407 | $GroupBoxMainUnlockAccount.Text = 'Unlock Account' 408 | # 409 | # ButtonMainUnlockAccountUnlockAccount 410 | # 411 | $ButtonMainUnlockAccountUnlockAccount.Location = '154, 20' 412 | $ButtonMainUnlockAccountUnlockAccount.Name = 'ButtonMainUnlockAccountUnlockAccount' 413 | $ButtonMainUnlockAccountUnlockAccount.Size = '142, 23' 414 | $ButtonMainUnlockAccountUnlockAccount.TabIndex = 1 415 | $ButtonMainUnlockAccountUnlockAccount.Text = 'Unlock Account' 416 | $ButtonMainUnlockAccountUnlockAccount.UseVisualStyleBackColor = $True 417 | $ButtonMainUnlockAccountUnlockAccount.add_Click($ButtonMainUnlockAccountUnlockAccount_Click) 418 | # 419 | # ButtonMainUnlockAccountQueryLockStatus 420 | # 421 | $ButtonMainUnlockAccountQueryLockStatus.Location = '7, 20' 422 | $ButtonMainUnlockAccountQueryLockStatus.Name = 'ButtonMainUnlockAccountQueryLockStatus' 423 | $ButtonMainUnlockAccountQueryLockStatus.Size = '141, 23' 424 | $ButtonMainUnlockAccountQueryLockStatus.TabIndex = 0 425 | $ButtonMainUnlockAccountQueryLockStatus.Text = 'Query Lock Status' 426 | $ButtonMainUnlockAccountQueryLockStatus.UseVisualStyleBackColor = $True 427 | $ButtonMainUnlockAccountQueryLockStatus.add_Click($ButtonMainUnlockAccountQueryLockStatus_Click) 428 | # 429 | # GroupBoxMainUserName 430 | # 431 | $GroupBoxMainUserName.Controls.Add($TextBoxMainUserName) 432 | $GroupBoxMainUserName.Location = '13, 28' 433 | $GroupBoxMainUserName.Name = 'GroupBoxMainUserName' 434 | $GroupBoxMainUserName.Size = '300, 54' 435 | $GroupBoxMainUserName.TabIndex = 1 436 | $GroupBoxMainUserName.TabStop = $False 437 | $GroupBoxMainUserName.Text = 'UserName (SamAccountName)' 438 | # 439 | # TextBoxMainUserName 440 | # 441 | $TextBoxMainUserName.Font = 'Consolas, 8.25pt' 442 | $TextBoxMainUserName.Location = '7, 20' 443 | $TextBoxMainUserName.Name = 'TextBoxMainUserName' 444 | $TextBoxMainUserName.Size = '287, 20' 445 | $TextBoxMainUserName.TabIndex = 0 446 | # 447 | # MenuStripMain 448 | # 449 | [void]$MenuStripMain.Items.Add($ToolStripMenuItemMainFile) 450 | $MenuStripMain.Location = '0, 0' 451 | $MenuStripMain.Name = 'MenuStripMain' 452 | $MenuStripMain.Size = '633, 24' 453 | $MenuStripMain.TabIndex = 0 454 | $MenuStripMain.Text = 'MenuStripMain' 455 | # 456 | # ToolStripMenuItemMainFile 457 | # 458 | [void]$ToolStripMenuItemMainFile.DropDownItems.Add($ToolStripMenuItemMainFileLog) 459 | [void]$ToolStripMenuItemMainFile.DropDownItems.Add($ToolStripMenuItemMainFileAbout) 460 | [void]$ToolStripMenuItemMainFile.DropDownItems.Add($ToolStripMenuItemMainFileExit) 461 | $ToolStripMenuItemMainFile.Name = 'ToolStripMenuItemMainFile' 462 | $ToolStripMenuItemMainFile.Size = '37, 20' 463 | $ToolStripMenuItemMainFile.Text = 'File' 464 | # 465 | # ToolStripMenuItemMainFileLog 466 | # 467 | $ToolStripMenuItemMainFileLog.Name = 'ToolStripMenuItemMainFileLog' 468 | $ToolStripMenuItemMainFileLog.Size = '107, 22' 469 | $ToolStripMenuItemMainFileLog.Text = 'Log' 470 | $ToolStripMenuItemMainFileLog.add_Click($ToolStripMenuItemMainFileLog_Click) 471 | # 472 | # ToolStripMenuItemMainFileAbout 473 | # 474 | $ToolStripMenuItemMainFileAbout.Name = 'ToolStripMenuItemMainFileAbout' 475 | $ToolStripMenuItemMainFileAbout.Size = '107, 22' 476 | $ToolStripMenuItemMainFileAbout.Text = 'About' 477 | $ToolStripMenuItemMainFileAbout.add_Click($ToolStripMenuItemMainFileAbout_Click) 478 | # 479 | # ToolStripMenuItemMainFileExit 480 | # 481 | $ToolStripMenuItemMainFileExit.Name = 'ToolStripMenuItemMainFileExit' 482 | $ToolStripMenuItemMainFileExit.Size = '152, 22' 483 | $ToolStripMenuItemMainFileExit.Text = 'Exit' 484 | $ToolStripMenuItemMainFileExit.add_Click($ToolStripMenuItemMainFileExit_Click) 485 | $MenuStripMain.ResumeLayout() 486 | $GroupBoxMainUserName.ResumeLayout() 487 | $GroupBoxMainUnlockAccount.ResumeLayout() 488 | $GroupBoxMainOutput.ResumeLayout() 489 | $FormMain.ResumeLayout() 490 | #endregion Generated Form Code 491 | 492 | #---------------------------------------------- 493 | 494 | #Save the initial state of the form 495 | $InitialFormWindowState = $FormMain.WindowState 496 | #Init the OnLoad event to correct the initial state of the form 497 | $FormMain.add_Load($Form_StateCorrection_Load) 498 | #Clean up the control events 499 | $FormMain.add_FormClosed($Form_Cleanup_FormClosed) 500 | #Store the control values when form is closing 501 | $FormMain.add_Closing($Form_StoreValues_Closing) 502 | #Show the Form 503 | return $FormMain.ShowDialog() 504 | 505 | } 506 | #endregion Source: MainForm.psf 507 | 508 | #region Source: Globals.ps1 509 | #################################################################################################### 510 | ### Begin: Custom functions ######################################################################## 511 | #################################################################################################### 512 | 513 | #region function Add-SSAOutput 514 | function Add-SSAOutput 515 | { 516 | [CmdletBinding()] 517 | Param 518 | ( 519 | [Parameter( 520 | Mandatory = $true 521 | ) 522 | ] 523 | $OutputText 524 | ) 525 | Begin 526 | { 527 | } 528 | Process 529 | { 530 | $OutputDate = Get-Date -UFormat "%Y-%m-%d" 531 | $OutputTime = Get-Date -UFormat "%H:%M:%S" 532 | $RichTextBoxMainOutput.Text += "[$OutputDate][$OutputTime] $OutputText`n" 533 | Add-Content -Path $SSALogFile -Value "[$OutputDate][$OutputTime] $OutputText`n" 534 | } 535 | End 536 | { 537 | } 538 | } 539 | #endregion 540 | 541 | #region function Import-SSAActiveDirectoryModule 542 | function Import-SSAActiveDirectoryModule 543 | { 544 | [CmdletBinding()] 545 | Param 546 | ( 547 | ) 548 | Begin 549 | { 550 | } 551 | Process 552 | { 553 | Add-SSAOutput -OutputText "Loading ActiveDirectory PowerShell module." 554 | if ((Get-Module -name "ActiveDirectory") -eq $null) 555 | { 556 | Add-SSAOutput -OutputText "ActiveDirectory PowerShell module is currently not loaded." 557 | if (Get-Module -ListAvailable | Where-Object { $_.name -eq "ActiveDirectory" }) 558 | { 559 | Add-SSAOutput -OutputText "ActiveDirectory PowerShell module is available, importing module." 560 | Import-Module -Name "ActiveDirectory" 561 | if ((Get-Module -name "ActiveDirectory") -eq $null) 562 | { 563 | Add-SSAOutput -OutputText "ActiveDirectory PowerShell module could not be loaded." 564 | $global:SSAActiveDirectoryModuleLoaded = $false 565 | } 566 | else 567 | { 568 | Add-SSAOutput -OutputText "ActiveDirectory PowerShell module has been loaded." 569 | $global:SSAActiveDirectoryModuleLoaded = $true 570 | } 571 | } 572 | else 573 | { 574 | Add-SSAOutput -OutputText "ActiveDirectory PowerShell module is not available on this computer, attempting to import it from a Domain Controller." 575 | try 576 | { 577 | $DomainDNSName = (Get-WmiObject -Class WIN32_ComputerSystem -ErrorAction Stop).Domain 578 | $DomainNetBiosName = (Get-WmiObject Win32_NTDomain -Filter "DnsForestName = '$((Get-WmiObject Win32_ComputerSystem).Domain)'" -ErrorAction Stop).DomainName 579 | $DomainControllerName = ((Get-WmiObject -Class WIN32_NTDomain -Filter "DomainName = '$DomainNetBiosName'" -ErrorAction Stop).DomainControllerName) -replace "\\", "" 580 | $DomainController = "$DomainControllerName.$DomainDNSName" 581 | $DomainControllerSession = New-PSSession -Computername $DomainController -ErrorAction Stop 582 | Invoke-Command -Command { Import-Module -Name "ActiveDirectory" } -Session $DomainControllerSession -ErrorAction Stop 583 | $ImportSession = Import-PSSession -Session $DomainControllerSession -Module ActiveDirectory -AllowClobber -ErrorAction Stop 584 | if ($ImportSession.Name) 585 | { 586 | Add-SSAOutput -OutputText "ActiveDirectory PowerShell module has been imported from Domain Controller $DomainController." 587 | $global:SSAActiveDirectoryModuleLoaded = $true 588 | } 589 | } 590 | catch 591 | { 592 | Add-SSAOutput -OutputText "ActiveDirectory PowerShell module could not be imported. Possible reasons are: This workstation is not joined to the Active Directory domain, PowerShell remoting towards the Domain Controller does not work or is not setup, the current user does not have appropriate rights to open a PowerShell session to the Domain Controller." 593 | $global:SSAActiveDirectoryModuleLoaded = $false 594 | } 595 | } 596 | } 597 | else 598 | { 599 | Add-SSAOutput -OutputText "ActiveDirectory PowerShell module is already loaded." 600 | $global:SSAActiveDirectoryModuleLoaded = $true 601 | } 602 | } 603 | End 604 | { 605 | } 606 | } 607 | #endregion 608 | 609 | #region function Get-SSAUserName 610 | function Get-SSAUserName 611 | { 612 | [CmdletBinding()] 613 | Param 614 | ( 615 | ) 616 | Begin 617 | { 618 | } 619 | Process 620 | { 621 | $global:SSAUserName = $TextBoxMainUserName.text 622 | } 623 | End 624 | { 625 | } 626 | } 627 | #endregion 628 | 629 | #################################################################################################### 630 | ### End: Custom functions ########################################################################## 631 | #################################################################################################### 632 | 633 | #endregion Source: Globals.ps1 634 | 635 | #Start the application 636 | Main ($CommandLine) 637 | -------------------------------------------------------------------------------- /Scripts/GUI/TOOL/RandomPasswordGenerator.ps1: -------------------------------------------------------------------------------- 1 | #------------------------------------------------------------------------ 2 | # Source File Information (DO NOT MODIFY) 3 | # Source ID: a33f0f3b-dbbe-4c28-b992-c8c1b6224eb7 4 | # Source File: RandomPasswordGenerator.psproj 5 | #------------------------------------------------------------------------ 6 | #region Project Recovery Data (DO NOT MODIFY) 7 | <#RecoveryData: 8 | EAIAAB+LCAAAAAAABACNkl1LwzAUhu8H+w+l9136MXSDNBdubnihjjm8lZP2VCJpUpJU3b83ta10 9 | COLlk5z3eckh9IiFfkdz3oIDNp8FAT0Y/YaF+waPz2is0Ioli4SSEYa7nZB4t2WQZVVcZTwqOcdo 10 | WaSriK/XaVSsioRfpekS+TUlw/AQHVpO5wZZTMkUR7mWpa8LyLTNDjBgcMQKDaoCH6DGPAyDm1bI 11 | Mg/jkD05MK5tFo21ffnf0Q1IGd2DUDtt6pfGVlPXeO5l1b9le6k5SK9KJqpgo+saVHn76VB1u8zD 12 | k2kxZP209Q3JRUMP/bt/9tTToxGvQoHsBrpedvRiXR/A2g9tyj0qNOC08c7G5yj5FZjPKLn4AV+3 13 | V6rrEAIAAA==#> 14 | #endregion 15 | <# 16 | .NOTES 17 | -------------------------------------------------------------------------------- 18 | Code generated by: SAPIEN Technologies, Inc., PowerShell Studio 2016 v5.2.120 19 | Generated on: 2016-05-26 18:10 20 | Generated by: ibelmans 21 | -------------------------------------------------------------------------------- 22 | .DESCRIPTION 23 | Script generated by PowerShell Studio 2016 24 | #> 25 | 26 | 27 | #region Source: Startup.pss 28 | #region File Recovery Data (DO NOT MODIFY) 29 | <#RecoveryData: 30 | SwQAAB+LCAAAAAAABAC9lEtLAzEQgO+C/yH0vOzD7boWsgtS6UXQ4kr1mk1nS2geZZK07L93W0sV 31 | PYiFhlwyEzIfH8MMfQFutoD9A3OMDBcrjK5GN6P6+ooQ+oxiJTSTMyHhiSmoG8fQ+U28sZYmv14P 32 | f+6tBdVKAfYQf2X6WlluUIo2IosjaRyn+xORqZfOI1QavEMmIzL3Qw3+CP2rWYOu2rJkBS9us0k+ 33 | hvRuQpNT1Z+UprcOVAhG/Cb00uxsPDOobBDivk9hQMh2Qq/OYaV5V3Rll2XLImU5+5v1rmQYJ4HA 34 | ncG+AdwKDme17N92U4MQRO9oNUczqF3A7RR+zjZNvi+P+gNBqg7+SwQAAA==#> 35 | #endregion 36 | #---------------------------------------------- 37 | #region Import Assemblies 38 | #---------------------------------------------- 39 | [void][Reflection.Assembly]::Load('System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089') 40 | [void][Reflection.Assembly]::Load('System.Data, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089') 41 | [void][Reflection.Assembly]::Load('System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a') 42 | [void][Reflection.Assembly]::Load('System.DirectoryServices, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a') 43 | [void][Reflection.Assembly]::Load('System.ServiceProcess, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a') 44 | #endregion Import Assemblies 45 | 46 | #################################################################################################### 47 | ### Begin: Script information ###################################################################### 48 | #################################################################################################### 49 | 50 | <# 51 | .SYNOPSIS 52 | PowerShell GUI script to generate random passwords. 53 | .DESCRIPTION 54 | PowerShell GUI script to generate random passwords. 55 | .NOTES 56 | Author : Ingvald Belmans 57 | Website : http://www.supersysadmin.com 58 | Version : 1.0 59 | Changelog: 60 | - 1.0 (2016-05-26) Initial version. 61 | .LINK 62 | http://www.supersysadmin.com 63 | #> 64 | 65 | #################################################################################################### 66 | ### End: Script information ######################################################################## 67 | #################################################################################################### 68 | 69 | #################################################################################################### 70 | ### Begin: Main function ########################################################################### 71 | #################################################################################################### 72 | 73 | #region function Main 74 | function Main 75 | { 76 | <# 77 | .SYNOPSIS 78 | The Main function starts the project application. 79 | 80 | .PARAMETER Commandline 81 | $Commandline contains the complete argument string passed to the script packager executable. 82 | 83 | .NOTES 84 | Use this function to initialize your script and to call GUI forms. 85 | 86 | .NOTES 87 | To get the console output in the Packager (Forms Engine) use: 88 | $ConsoleOutput (Type: System.Collections.ArrayList) 89 | #> 90 | Param 91 | ( 92 | [String]$Commandline 93 | ) 94 | if ((Call-MainForm_psf) -eq 'OK') 95 | { 96 | } 97 | $global:ExitCode = 0 #Set the exit code for the Packager 98 | } 99 | #endregion 100 | 101 | #################################################################################################### 102 | ### End: Main function ############################################################################# 103 | #################################################################################################### 104 | #endregion Source: Startup.pss 105 | 106 | #region Source: MainForm.psf 107 | function Call-MainForm_psf 108 | { 109 | #region File Recovery Data (DO NOT MODIFY) 110 | <#RecoveryData: 111 | BSoAAB+LCAAAAAAABADtmm1P4zgQx9+fdN/ByukkTipt00cqleqgLKvVwi6iwK7uDXLTKfXhxpHj 112 | AN1Pf3YeStskjdM2va20QkKEeDx/z/w8duJ0b8FiL8BnF1hgJP9wCbNPjZrR+/03hLpfOXkiNqaX 113 | hMIXPIXeNSb2JePTsuOOu5XY7cBo+C9YAomZA6fGYOYKmJa/EXvEXt2ysg1+l1DSrRJ6CDU0ylX1 114 | U0J9jwqPw6kNnuCYltCNN6TE+gyzO/YM9umw3cZNq9kyO/UGVE86BrKllFND9afkGsiaEDrisqnR 115 | Z7bgjLrB8KTWG84c4GIW2vQpAVsMyA8weq1mo4RqrUa3EjVKMVJOrsH2BoITJ+pZNruFMUivFkTt 116 | ojaBqkrUXWb/xCZTbxqqasuQ1Kv1TCuVD6MXBSGz+UBgLm6YS4QMvtHryzAAH1gcINv2Dt6E0bvF 117 | Mo/TG+y6r4yPPoINHAvG0YtZrsa7+PAiPYT2VwyP3qU+qstuxW8Qtc5G6iNnnnPO3grHKnKkpH71 118 | hOOJdYDFg3VmWxPGjd4dc0ronAnB5FS4grEooVvyNBGxUMW7uGIWDtJkdkzJ6ImGTYBDXLyGaQBe 119 | oymDVqs1NQzu8PCTPYI3aaTXeiCYnDiXmLqgY+Djli4/G5ZbYk1UL/vgZcGXLjI7gSbeyaV0JGc2 120 | s11GsRxix9Gze8etXUJmS8smwC1x7Fr2svIwSs8xd/3CYMFIJkQQC1M98wDZuhRcS6iV66GNV6t0 121 | ChfuJxotljll0Z9g+wlGKaF5XGiyXAFV/wHX81Vj+TIb+nNPYmMXznvgRo2pzxzZVi6psuJgPspX 122 | JhdqXF0msZ6UlGToUgVolzqzrapqEjbp0Gi19pFRqpBgSOkaauq6d+GBuB6mAzGjcI6t5z6jfkHg 123 | XmLJXOROOrKe18Tl0W+wsuL+/HiFOwyIdhxb8VXdhK9VBYUCVtMGLJKFcujaLWCrgdkNYf/PFs9R 124 | lLhbwbXh/izwnA8qs5Vvg2YWuEFL15+d6ys8BFp4on0vC7GWSy/Hlnzwycj3uoy3TnJuktJF5Njq 125 | tNspBSXv7jx11cqnShmdUfIkA3JNRiMKarOahMJyFdBi44s3BU6se+eCvRa/4Cx52zUrEpVODlSy 126 | teRAptlS615OZJJWoXj7B0w9VZESa9EGGe9PwHreR+X3HQ2X6u/AAYtgul2S60mRSMtyuogc2TXr 127 | HZlezRm+dhebVhFCTejozxL6G/1RQuVy+S8t+9ybjQNDRk7T4QZ1we9JPRumhCHFYiDkTiukBpL2 128 | ellwVreEMxxu4XDq1Z4AzlATOqoed35BqbJ0xV6B97ELB4Jle0sq5+MtnMukPXQal74qpGShI3z8 129 | 4xeaKlX3jnNQaDa2RHM+3sLRzPMq01cVonl2/M9e0Mz/EmB+iFY4qCvHdXme/z9JXcvgqv+sG9Yd 130 | YzRwJr2qxsUNb0FWwiFlTIh/4ksovB9YBolT9xbSmvlS4H0GSdH6b9uWsqD9LiQ4u9U8fVozV5Jn 131 | ylRqcpWmeOVfAnr5IpvtPUKQme2Uo94LeakePlcI/0n51qf7bMjUqVxlgehlwA99gB/eSPr4ND8m 132 | SO08++sCf1YGx3GanxMk9HvA8ynga7Po+raaITarKsbxJ6XkGKf0nPBuf724+Pv9A06VP1M2y5Qy 133 | 1U1Us5YjUckd58mT6iErTWeuC1MZPHAjD+F/Zr2pazFOyXAHCehW5r2ueglSvg8fO8cq26P6wm4/ 134 | jjh+JfbTJr6q9XFz3B6b5qhZxXWc7ev7lO5nTIRLTBmfDYC/EAs2Slnu0fUZh70MLxyVnOByaAWM 135 | bX4ZzO1uZfGzz95/pIxiVQUqAAA=#> 136 | #endregion 137 | #---------------------------------------------- 138 | #region Import the Assemblies 139 | #---------------------------------------------- 140 | [void][reflection.assembly]::Load('System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089') 141 | [void][reflection.assembly]::Load('System.Data, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089') 142 | [void][reflection.assembly]::Load('System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a') 143 | [void][reflection.assembly]::Load('System.DirectoryServices, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a') 144 | [void][reflection.assembly]::Load('System.ServiceProcess, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a') 145 | [void][reflection.assembly]::Load('System.Design, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a') 146 | #endregion Import Assemblies 147 | 148 | #---------------------------------------------- 149 | #region Generated Form Objects 150 | #---------------------------------------------- 151 | [System.Windows.Forms.Application]::EnableVisualStyles() 152 | $FormMain = New-Object 'System.Windows.Forms.Form' 153 | $GroupBoxMainOutput = New-Object 'System.Windows.Forms.GroupBox' 154 | $RichTextBoxMainOutput = New-Object 'System.Windows.Forms.RichTextBox' 155 | $ButtonMainCopyToClipBoard = New-Object 'System.Windows.Forms.Button' 156 | $ButtonMainGeneratePassword = New-Object 'System.Windows.Forms.Button' 157 | $GroupBoxMainOptions = New-Object 'System.Windows.Forms.GroupBox' 158 | $LabelMainOptionsCharacters = New-Object 'System.Windows.Forms.Label' 159 | $NumericUpDownMainOptionsCharacters = New-Object 'System.Windows.Forms.NumericUpDown' 160 | $CheckboxMainOptionsSpecial = New-Object 'System.Windows.Forms.CheckBox' 161 | $CheckboxMainOptionsNumbers = New-Object 'System.Windows.Forms.CheckBox' 162 | $CheckboxMainOptionsLowerCase = New-Object 'System.Windows.Forms.CheckBox' 163 | $CheckboxMainOptionsUpperCase = New-Object 'System.Windows.Forms.CheckBox' 164 | $MenuStripMain = New-Object 'System.Windows.Forms.MenuStrip' 165 | $ToolStripMenuItemMainFile = New-Object 'System.Windows.Forms.ToolStripMenuItem' 166 | $ToolStripMenuItemMainFileAbout = New-Object 'System.Windows.Forms.ToolStripMenuItem' 167 | $ToolStripMenuItemMainFileExit = New-Object 'System.Windows.Forms.ToolStripMenuItem' 168 | $InitialFormWindowState = New-Object 'System.Windows.Forms.FormWindowState' 169 | #endregion Generated Form Objects 170 | 171 | #---------------------------------------------- 172 | # User Generated Script 173 | #---------------------------------------------- 174 | #################################################################################################### 175 | ### Begin: Main form ############################################################################### 176 | #################################################################################################### 177 | 178 | $FormMain_Load = 179 | { 180 | } 181 | 182 | $ToolStripMenuItemMainFileAbout_Click = 183 | { 184 | Start-Process -FilePath "http://supersysadmin.com/200/powershell-gui-script-generate-random-passwords" 185 | } 186 | 187 | $ToolStripMenuItemMainFileExit_Click = 188 | { 189 | $FormMain.Close() 190 | } 191 | 192 | $ButtonMainGeneratePassword_Click = 193 | { 194 | $NumericUpDownMainOptionsCharactersValue = $NumericUpDownMainOptionsCharacters.Text 195 | if ($CheckboxMainOptionsUpperCase.Checked -eq $True) 196 | { 197 | $CheckboxMainOptionsUpperCaseStatus = $True 198 | } 199 | else 200 | { 201 | $CheckboxMainOptionsUpperCaseStatus = $False 202 | } 203 | if ($CheckboxMainOptionsLowerCase.Checked -eq $True) 204 | { 205 | $CheckboxMainOptionsLowerCaseStatus = $True 206 | } 207 | else 208 | { 209 | $CheckboxMainOptionsLowerCaseStatus = $False 210 | } 211 | if ($CheckboxMainOptionsNumbers.Checked -eq $True) 212 | { 213 | $CheckboxMainOptionsNumbersStatus = $True 214 | } 215 | else 216 | { 217 | $CheckboxMainOptionsNumbersStatus = $False 218 | } 219 | if ($CheckboxMainOptionsSpecial.Checked -eq $True) 220 | { 221 | $CheckboxMainOptionsSpecialStatus = $True 222 | } 223 | else 224 | { 225 | $CheckboxMainOptionsSpecialStatus = $False 226 | } 227 | $Global:NewPassword = New-SSARandomPassword -UpperCaseCharacters $CheckboxMainOptionsUpperCaseStatus -LowerCaseCharacters $CheckboxMainOptionsLowerCaseStatus -NumberCharacters $CheckboxMainOptionsNumbersStatus -SpecialCharacters $CheckboxMainOptionsSpecialStatus -CharacterCount $NumericUpDownMainOptionsCharactersValue 228 | Add-SSAOutput -OutputText $NewPassword 229 | } 230 | 231 | $ButtonMainCopyToClipBoard_Click = 232 | { 233 | $NewPassword | Set-Clipboard 234 | } 235 | 236 | $RichTextBoxMainOutput_TextChanged = 237 | { 238 | $RichTextBoxMainOutput.SelectionStart = $RichTextBoxMainOutput.Text.Length 239 | $RichTextBoxMainOutput.ScrollToCaret() 240 | } 241 | 242 | #################################################################################################### 243 | ### End: Main form ################################################################################# 244 | #################################################################################################### 245 | # --End User Generated Script-- 246 | #---------------------------------------------- 247 | #region Generated Events 248 | #---------------------------------------------- 249 | 250 | $Form_StateCorrection_Load= 251 | { 252 | #Correct the initial state of the form to prevent the .Net maximized form issue 253 | $FormMain.WindowState = $InitialFormWindowState 254 | } 255 | 256 | $Form_StoreValues_Closing= 257 | { 258 | #Store the control values 259 | $script:MainForm_RichTextBoxMainOutput = $RichTextBoxMainOutput.Text 260 | $script:MainForm_NumericUpDownMainOptionsCharacters = $NumericUpDownMainOptionsCharacters.Value 261 | $script:MainForm_CheckboxMainOptionsSpecial = $CheckboxMainOptionsSpecial.Checked 262 | $script:MainForm_CheckboxMainOptionsNumbers = $CheckboxMainOptionsNumbers.Checked 263 | $script:MainForm_CheckboxMainOptionsLowerCase = $CheckboxMainOptionsLowerCase.Checked 264 | $script:MainForm_CheckboxMainOptionsUpperCase = $CheckboxMainOptionsUpperCase.Checked 265 | } 266 | 267 | 268 | $Form_Cleanup_FormClosed= 269 | { 270 | #Remove all event handlers from the controls 271 | try 272 | { 273 | $RichTextBoxMainOutput.remove_TextChanged($RichTextBoxMainOutput_TextChanged) 274 | $ButtonMainCopyToClipBoard.remove_Click($ButtonMainCopyToClipBoard_Click) 275 | $ButtonMainGeneratePassword.remove_Click($ButtonMainGeneratePassword_Click) 276 | $FormMain.remove_Load($FormMain_Load) 277 | $ToolStripMenuItemMainFileAbout.remove_Click($ToolStripMenuItemMainFileAbout_Click) 278 | $ToolStripMenuItemMainFileExit.remove_Click($ToolStripMenuItemMainFileExit_Click) 279 | $FormMain.remove_Load($Form_StateCorrection_Load) 280 | $FormMain.remove_Closing($Form_StoreValues_Closing) 281 | $FormMain.remove_FormClosed($Form_Cleanup_FormClosed) 282 | } 283 | catch [Exception] 284 | { } 285 | } 286 | #endregion Generated Events 287 | 288 | #---------------------------------------------- 289 | #region Generated Form Code 290 | #---------------------------------------------- 291 | $FormMain.SuspendLayout() 292 | $GroupBoxMainOutput.SuspendLayout() 293 | $GroupBoxMainOptions.SuspendLayout() 294 | $NumericUpDownMainOptionsCharacters.BeginInit() 295 | $MenuStripMain.SuspendLayout() 296 | # 297 | # FormMain 298 | # 299 | $FormMain.Controls.Add($GroupBoxMainOutput) 300 | $FormMain.Controls.Add($ButtonMainCopyToClipBoard) 301 | $FormMain.Controls.Add($ButtonMainGeneratePassword) 302 | $FormMain.Controls.Add($GroupBoxMainOptions) 303 | $FormMain.Controls.Add($MenuStripMain) 304 | $FormMain.ClientSize = '654, 264' 305 | $FormMain.MainMenuStrip = $MenuStripMain 306 | $FormMain.MinimumSize = '670, 303' 307 | $FormMain.Name = 'FormMain' 308 | $FormMain.StartPosition = 'CenterScreen' 309 | $FormMain.Text = 'RandomPasswordGenerator v1.0' 310 | $FormMain.add_Load($FormMain_Load) 311 | # 312 | # GroupBoxMainOutput 313 | # 314 | $GroupBoxMainOutput.Controls.Add($RichTextBoxMainOutput) 315 | $GroupBoxMainOutput.Anchor = 'Top, Bottom, Left, Right' 316 | $GroupBoxMainOutput.Location = '191, 28' 317 | $GroupBoxMainOutput.Name = 'GroupBoxMainOutput' 318 | $GroupBoxMainOutput.Size = '450, 225' 319 | $GroupBoxMainOutput.TabIndex = 4 320 | $GroupBoxMainOutput.TabStop = $False 321 | $GroupBoxMainOutput.Text = 'Output' 322 | # 323 | # RichTextBoxMainOutput 324 | # 325 | $RichTextBoxMainOutput.Anchor = 'Top, Bottom, Left, Right' 326 | $RichTextBoxMainOutput.Font = 'Consolas, 9pt' 327 | $RichTextBoxMainOutput.Location = '7, 16' 328 | $RichTextBoxMainOutput.Name = 'RichTextBoxMainOutput' 329 | $RichTextBoxMainOutput.ScrollBars = 'ForcedVertical' 330 | $RichTextBoxMainOutput.Size = '437, 203' 331 | $RichTextBoxMainOutput.TabIndex = 0 332 | $RichTextBoxMainOutput.Text = '' 333 | $RichTextBoxMainOutput.add_TextChanged($RichTextBoxMainOutput_TextChanged) 334 | # 335 | # ButtonMainCopyToClipBoard 336 | # 337 | $ButtonMainCopyToClipBoard.Location = '13, 230' 338 | $ButtonMainCopyToClipBoard.Name = 'ButtonMainCopyToClipBoard' 339 | $ButtonMainCopyToClipBoard.Size = '171, 23' 340 | $ButtonMainCopyToClipBoard.TabIndex = 3 341 | $ButtonMainCopyToClipBoard.Text = 'Copy to Clipboard' 342 | $ButtonMainCopyToClipBoard.UseVisualStyleBackColor = $True 343 | $ButtonMainCopyToClipBoard.add_Click($ButtonMainCopyToClipBoard_Click) 344 | # 345 | # ButtonMainGeneratePassword 346 | # 347 | $ButtonMainGeneratePassword.Location = '13, 200' 348 | $ButtonMainGeneratePassword.Name = 'ButtonMainGeneratePassword' 349 | $ButtonMainGeneratePassword.Size = '171, 23' 350 | $ButtonMainGeneratePassword.TabIndex = 2 351 | $ButtonMainGeneratePassword.Text = 'Generate Password' 352 | $ButtonMainGeneratePassword.UseVisualStyleBackColor = $True 353 | $ButtonMainGeneratePassword.add_Click($ButtonMainGeneratePassword_Click) 354 | # 355 | # GroupBoxMainOptions 356 | # 357 | $GroupBoxMainOptions.Controls.Add($LabelMainOptionsCharacters) 358 | $GroupBoxMainOptions.Controls.Add($NumericUpDownMainOptionsCharacters) 359 | $GroupBoxMainOptions.Controls.Add($CheckboxMainOptionsSpecial) 360 | $GroupBoxMainOptions.Controls.Add($CheckboxMainOptionsNumbers) 361 | $GroupBoxMainOptions.Controls.Add($CheckboxMainOptionsLowerCase) 362 | $GroupBoxMainOptions.Controls.Add($CheckboxMainOptionsUpperCase) 363 | $GroupBoxMainOptions.Location = '13, 28' 364 | $GroupBoxMainOptions.Name = 'GroupBoxMainOptions' 365 | $GroupBoxMainOptions.Size = '171, 165' 366 | $GroupBoxMainOptions.TabIndex = 1 367 | $GroupBoxMainOptions.TabStop = $False 368 | $GroupBoxMainOptions.Text = 'Options' 369 | # 370 | # LabelMainOptionsCharacters 371 | # 372 | $LabelMainOptionsCharacters.Location = '68, 16' 373 | $LabelMainOptionsCharacters.Name = 'LabelMainOptionsCharacters' 374 | $LabelMainOptionsCharacters.Size = '77, 23' 375 | $LabelMainOptionsCharacters.TabIndex = 4 376 | $LabelMainOptionsCharacters.Text = 'Characters' 377 | $LabelMainOptionsCharacters.TextAlign = 'MiddleLeft' 378 | # 379 | # NumericUpDownMainOptionsCharacters 380 | # 381 | $NumericUpDownMainOptionsCharacters.Location = '6, 19' 382 | $NumericUpDownMainOptionsCharacters.Name = 'NumericUpDownMainOptionsCharacters' 383 | $NumericUpDownMainOptionsCharacters.Size = '56, 20' 384 | $NumericUpDownMainOptionsCharacters.TabIndex = 2 385 | $NumericUpDownMainOptionsCharacters.Value = 15 386 | # 387 | # CheckboxMainOptionsSpecial 388 | # 389 | $CheckboxMainOptionsSpecial.Location = '6, 135' 390 | $CheckboxMainOptionsSpecial.Name = 'CheckboxMainOptionsSpecial' 391 | $CheckboxMainOptionsSpecial.Size = '139, 24' 392 | $CheckboxMainOptionsSpecial.TabIndex = 3 393 | $CheckboxMainOptionsSpecial.Text = 'Special (%, @ #, ...)' 394 | $CheckboxMainOptionsSpecial.UseVisualStyleBackColor = $True 395 | # 396 | # CheckboxMainOptionsNumbers 397 | # 398 | $CheckboxMainOptionsNumbers.Checked = $True 399 | $CheckboxMainOptionsNumbers.CheckState = 'Checked' 400 | $CheckboxMainOptionsNumbers.Location = '6, 105' 401 | $CheckboxMainOptionsNumbers.Name = 'CheckboxMainOptionsNumbers' 402 | $CheckboxMainOptionsNumbers.Size = '139, 24' 403 | $CheckboxMainOptionsNumbers.TabIndex = 2 404 | $CheckboxMainOptionsNumbers.Text = 'Numbers (0-9)' 405 | $CheckboxMainOptionsNumbers.UseVisualStyleBackColor = $True 406 | # 407 | # CheckboxMainOptionsLowerCase 408 | # 409 | $CheckboxMainOptionsLowerCase.Checked = $True 410 | $CheckboxMainOptionsLowerCase.CheckState = 'Checked' 411 | $CheckboxMainOptionsLowerCase.Location = '6, 75' 412 | $CheckboxMainOptionsLowerCase.Name = 'CheckboxMainOptionsLowerCase' 413 | $CheckboxMainOptionsLowerCase.Size = '139, 24' 414 | $CheckboxMainOptionsLowerCase.TabIndex = 1 415 | $CheckboxMainOptionsLowerCase.Text = 'Lower Case (a-z)' 416 | $CheckboxMainOptionsLowerCase.UseVisualStyleBackColor = $True 417 | # 418 | # CheckboxMainOptionsUpperCase 419 | # 420 | $CheckboxMainOptionsUpperCase.Checked = $True 421 | $CheckboxMainOptionsUpperCase.CheckState = 'Checked' 422 | $CheckboxMainOptionsUpperCase.Location = '6, 45' 423 | $CheckboxMainOptionsUpperCase.Name = 'CheckboxMainOptionsUpperCase' 424 | $CheckboxMainOptionsUpperCase.Size = '139, 24' 425 | $CheckboxMainOptionsUpperCase.TabIndex = 0 426 | $CheckboxMainOptionsUpperCase.Text = 'Upper Case (A-Z)' 427 | $CheckboxMainOptionsUpperCase.UseVisualStyleBackColor = $True 428 | # 429 | # MenuStripMain 430 | # 431 | [void]$MenuStripMain.Items.Add($ToolStripMenuItemMainFile) 432 | $MenuStripMain.Location = '0, 0' 433 | $MenuStripMain.Name = 'MenuStripMain' 434 | $MenuStripMain.Size = '654, 24' 435 | $MenuStripMain.TabIndex = 0 436 | $MenuStripMain.Text = 'menustrip1' 437 | # 438 | # ToolStripMenuItemMainFile 439 | # 440 | [void]$ToolStripMenuItemMainFile.DropDownItems.Add($ToolStripMenuItemMainFileAbout) 441 | [void]$ToolStripMenuItemMainFile.DropDownItems.Add($ToolStripMenuItemMainFileExit) 442 | $ToolStripMenuItemMainFile.Name = 'ToolStripMenuItemMainFile' 443 | $ToolStripMenuItemMainFile.Size = '37, 20' 444 | $ToolStripMenuItemMainFile.Text = 'File' 445 | # 446 | # ToolStripMenuItemMainFileAbout 447 | # 448 | $ToolStripMenuItemMainFileAbout.Name = 'ToolStripMenuItemMainFileAbout' 449 | $ToolStripMenuItemMainFileAbout.Size = '107, 22' 450 | $ToolStripMenuItemMainFileAbout.Text = 'About' 451 | $ToolStripMenuItemMainFileAbout.add_Click($ToolStripMenuItemMainFileAbout_Click) 452 | # 453 | # ToolStripMenuItemMainFileExit 454 | # 455 | $ToolStripMenuItemMainFileExit.Name = 'ToolStripMenuItemMainFileExit' 456 | $ToolStripMenuItemMainFileExit.Size = '152, 22' 457 | $ToolStripMenuItemMainFileExit.Text = 'Exit' 458 | $ToolStripMenuItemMainFileExit.add_Click($ToolStripMenuItemMainFileExit_Click) 459 | $MenuStripMain.ResumeLayout() 460 | $NumericUpDownMainOptionsCharacters.EndInit() 461 | $GroupBoxMainOptions.ResumeLayout() 462 | $GroupBoxMainOutput.ResumeLayout() 463 | $FormMain.ResumeLayout() 464 | #endregion Generated Form Code 465 | 466 | #---------------------------------------------- 467 | 468 | #Save the initial state of the form 469 | $InitialFormWindowState = $FormMain.WindowState 470 | #Init the OnLoad event to correct the initial state of the form 471 | $FormMain.add_Load($Form_StateCorrection_Load) 472 | #Clean up the control events 473 | $FormMain.add_FormClosed($Form_Cleanup_FormClosed) 474 | #Store the control values when form is closing 475 | $FormMain.add_Closing($Form_StoreValues_Closing) 476 | #Show the Form 477 | return $FormMain.ShowDialog() 478 | 479 | } 480 | #endregion Source: MainForm.psf 481 | 482 | #region Source: Globals.ps1 483 | #################################################################################################### 484 | ### Begin: Custom functions ######################################################################## 485 | #################################################################################################### 486 | 487 | #region function New-SSARandomPassword 488 | function New-SSARandomPassword 489 | { 490 | [CmdletBinding()] 491 | Param 492 | ( 493 | [Parameter(Mandatory = $True)] 494 | [bool]$UpperCaseCharacters, 495 | [Parameter(Mandatory = $True)] 496 | [bool]$LowerCaseCharacters, 497 | [Parameter(Mandatory = $True)] 498 | [bool]$NumberCharacters, 499 | [Parameter(Mandatory = $True)] 500 | [bool]$SpecialCharacters, 501 | [Parameter(Mandatory = $True)] 502 | [int]$CharacterCount 503 | ) 504 | Begin 505 | { 506 | } 507 | Process 508 | { 509 | if ($UpperCaseCharacters -eq $True) 510 | { 511 | $UpperCaseCharacterArray = @("A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z") 512 | } 513 | else 514 | { 515 | $UpperCaseCharacterArray = @() 516 | } 517 | if ($LowerCaseCharacters -eq $True) 518 | { 519 | $LowerCaseCharacterArray = @("a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z") 520 | } 521 | else 522 | { 523 | $LowerCaseCharacterArray = @() 524 | } 525 | if ($NumberCharacters -eq $True) 526 | { 527 | $NumberCharacterArray = @(0, 1, 2, 3, 4, 5, 6, 7, 8, 9) 528 | } 529 | else 530 | { 531 | $NumberCharacterArray = @() 532 | } 533 | if ($SpecialCharacters -eq $True) 534 | { 535 | $SpecialCharacterArray = @("&", "@", "#", "§", "!", "$", "*", "%", "?") 536 | } 537 | else 538 | { 539 | $SpecialCharacterArray = @() 540 | } 541 | $RandomPasswordArray = $UpperCaseCharacterArray + $LowerCaseCharacterArray + $NumberCharacterArray + $SpecialCharacterArray 542 | $RandomPassword = $RandomPasswordArray | Get-Random -Count $CharacterCount 543 | $RandomPassword -join "" | Write-Output 544 | } 545 | End 546 | { 547 | } 548 | } 549 | #endregion 550 | 551 | #region function Add-SSAOutput 552 | function Add-SSAOutput 553 | { 554 | [CmdletBinding()] 555 | Param 556 | ( 557 | [Parameter(Mandatory = $True)] 558 | $OutputText 559 | ) 560 | Begin 561 | { 562 | } 563 | Process 564 | { 565 | $RichTextBoxMainOutput.Text += "$OutputText`n" 566 | } 567 | End 568 | { 569 | } 570 | } 571 | #endregion 572 | 573 | #################################################################################################### 574 | ### End: Custom functions ########################################################################## 575 | #################################################################################################### 576 | #endregion Source: Globals.ps1 577 | 578 | #Start the application 579 | Main ($CommandLine) 580 | --------------------------------------------------------------------------------