This question already has answers here:
What is the difference between combining paths in those 2 ways?
(2 answers)
Closed 6 years ago.
I'm running into a small problem where I have to require the user to NOT put a backslash "\" in the folder name because it removes the server name when I combine $Server and $Parent... How do I prevent that from happening? I'd rather not restrict my user from adding that backslash...
Also, I've been trying to prevent c:, d:, e:, etc. drives from being used in $Parent, but even if I use -in or -contains it still allows the c:\xxxx or d:\xxxx to be entered. How do I prevent that?
# File share server name
$Server = Read-Host -prompt "Verify Server Server Name (ie ECCOFS01)"
If ([string]::IsNullOrWhiteSpace($Server)) {
Write-Host "You entered $Server which is an incorrect value: This Script is now Exiting." -Foreground "White" -Background "Red"
Exit
}
else {
Write-Host "You Entered $Server" -Foreground "Black" -Background "Yellow"
}
# Parent folder setup
$Parent = Read-Host -prompt "Enter full parent path that will contain the new folder(ie. Groups\ECCO IT) - Do NOT start with \. Please use correct spelling and capitalization (ie. Parent Folder Name). "
If ([string]::IsNullOrWhiteSpace($Parent) -or ($Parent -eq "c:") -or ($Parent -eq "d:")) {
Write-Host "You entered $Parent which is an incorrect value: This Script is now Exiting." -Foreground "White" -Background "Red"
Exit
}
else {
Write-Host "You Entered $Parent" -Foreground "Black" -Background "Yellow"
}
$ServerParentShare = "\\"+[IO.Path]::Combine($Server,$Parent)
# New Folder Name
$Name = Read-Host -prompt "Enter New Folder Name. Please use correct spelling and capitalization (ie. New Test Folder)"
If ([string]::IsNullOrWhiteSpace($Name)) {
Write-Host "You entered $Name which is an incorrect value: This Script is now Exiting." -Foreground "White" -Background "Red"
Exit
}
else {
Write-Host "You Entered $Name." -Foreground "Black" -Background "Yellow"
}
$Path = [IO.Path]::Combine($ServerParentShare,$Name)
Write-Host = "New Folder Path = $Path" -Foreground "Black" -Background "Yellow"
# Choose parent OU
$Country = Read-Host -prompt "Enter the Country OU that the Security Group will reside in (i.e. Global, Americas, Europe, Asia Pacific)"
If ([string]::IsNullOrWhiteSpace($Country)) {
Write-Host "You entered $Country which is an incorrect value: This Script is now Exiting." -Foreground "White" -Background "Red"
Exit
}
else {
Write-Host "---------------------VERIFY ENTRY---------------------" -Foreground "Black" -Background "Yellow"
Write-Host "OU = $Country, New share location = $Path" -Foreground "Black" -Background "Yellow"
}
# Option to continue or cancel the script
$Continue = Read-Host -prompt "Does this look correct? Y or N?"
If (($Continue -eq "N") -or ($Continue -eq "No")) {
Write-Host "Please Start over. This Script is now Exiting." -Foreground "White" -Background "Red"
Exit
}
else {
Write-Host "Make sure to verify all folders and and AD Groups once complete." -Foreground "Yellow" -Background "Black"
}
I have to require the user to NOT put a backslash "\" in the folder name
insert this line after line 12:
$parent = $parent -replace '^\\',''
if $parent contains a backslash at position 0, it will replace it with an empty string. if not, it has no effect.
PS C:\> '\a\b' -replace '^\\',''
a\b
PS C:\> 'a\b' -replace '^\\',''
a\b
PS C:\>
technically this doesn't prevent the user from putting a backslash in the folder name, but if he/she does, it will remove it, which has a similar effect.
I've been trying to prevent c:, d:, e:, etc. drives from being used in
$Parent, but even if I use -in or -contains it still allows
-in and -contains operate on collections, not a single object (like $parent). for $parent, you probably want to use -like or -match. you can check for a drive letter-formatted path like this:
($parent -like '?:*')
or you can just look for a colon in the path
($parent -like '*:*')
you can use either of those conditionals in a while loop, forcing the user to keep inputting until he/she inputs the format you want. or you can just exit if the input is invalid. put it all together, for example:
do{
$parent = read-host -prompt 'Enter full parent path'
$parent = $parent -replace '^\\',''
}while($parent -like '*:*')
Related
I am trying to customize my PS Prompt in Windows 10 by adding the Azure Account ID. However, it is not working as expected.
Output of Azure Account ID, results in the following:
[0.04 sec] > (Get-AzContext).Account.Id
david.maryo#jd.com
I want the my result 'Account.Id' from the above command should be displayed in my PS Prompt. But it is not displaying the necessary results. Please refer the below screenshot for information.
Screenshot of the Current PS Prompt:
Microsoft.PowerShell_profile.ps1
function prompt {
#Assign Windows Title Text
$host.ui.RawUI.WindowTitle = "Current Folder: $pwd"
#Configure current user, current folder and date outputs
$CmdPromptCurrentFolder = Split-Path -Path $pwd -Leaf
$CmdPromptUser = [Security.Principal.WindowsIdentity]::GetCurrent();
$Date = Get-Date -Format 'dddd hh:mm:ss tt'
# Test for Admin / Elevated
$IsAdmin = (New-Object Security.Principal.WindowsPrincipal ([Security.Principal.WindowsIdentity]::GetCurrent())).IsInRole([Security.Principal.WindowsBuiltinRole]::Administrator)
#Calculate execution time of last cmd and convert to milliseconds, seconds or minutes
$LastCommand = Get-History -Count 1
if ($lastCommand) { $RunTime = ($lastCommand.EndExecutionTime - $lastCommand.StartExecutionTime).TotalSeconds }
if ($RunTime -ge 60) {
$ts = [timespan]::fromseconds($RunTime)
$min, $sec = ($ts.ToString("mm\:ss")).Split(":")
$ElapsedTime = -join ($min, " min ", $sec, " sec")
}
else {
$ElapsedTime = [math]::Round(($RunTime), 2)
$ElapsedTime = -join (($ElapsedTime.ToString()), " sec")
}
#Decorate the CMD Prompt
Write-Host ""
Write-Host "Azure: (Get-AzContext).Account.Id"
Write-host ($(if ($IsAdmin) { 'Elevated ' } else { '' })) -BackgroundColor DarkRed -ForegroundColor White -NoNewline
Write-Host " USER:$($CmdPromptUser.Name.split("\")[1]) " -BackgroundColor DarkBlue -ForegroundColor White -NoNewline
If ($CmdPromptCurrentFolder -like "*:*")
{Write-Host " $CmdPromptCurrentFolder " -ForegroundColor White -BackgroundColor DarkGray -NoNewline}
else {Write-Host ".\$CmdPromptCurrentFolder\ " -ForegroundColor White -BackgroundColor DarkGray -NoNewline}
Write-Host " $date " -ForegroundColor White
Write-Host "[$elapsedTime] " -NoNewline -ForegroundColor Green
return "> "
} #end prompt function
Tomalak is hinting at the problem in a comment (and shows an alternative solution), but let me spell it out:
In order:
to embed the output from an expression or command - (Get-AzContext).Account.Id, in your case - inside "..." , an expandable (double-quoted) string,
you need to enclose it in $(...), the subexpression operator:
Write-Host "Azure: $((Get-AzContext).Account.Id)"
See this answer for a comprehensive overview of PowerShell's expandable strings (string interpolation).
In general, only the following characters are metacharacters inside "..." - all others are treated as literals (which explains why you saw verbatim (Get-AzContext).Account.Id) in your prompt string):
` (backtick) PowerShell's escape character - see the conceptual about_Special_Characters help topic.
If doubled, also ": "" escapes a single " and is equivalent to `"
$, the start of a variable reference (e.g., $HOME) or subexpression ($(...), as above).
For the sake of completeness, here are alternative solutions:
# String concatenation - the expression must be enclosed in (...)
Write-Host ('Azure: ' + (Get-AzContext).Account.Id)
# The -f (string-formatting operator)
Write-Host ('Azure: {0}' -f (Get-AzContext).Account.Id)
# Tomalak's alternative, which relies on Write-Host space-concatenating
# its individual arguments.
# Note how a single expression can act as a command argument as-is.
Write-Host 'Azure:' (Get-AzContext).Account.Id
I am attempting to prompt a user for input and then validate if the users input matches one of two different options, and will exit if a correct input was not given.
In the example, I am asking the user to enter 'BOB' or 'TOM' as valid inputs, however when I run this code I will always get the message 'Server type not entered correctly', even when I enter BOB as an input for the prompt.
$ServerType = Read-Host -Prompt 'Enter Server Type (BOB or TOM)'
If ($ServerType -ne "BOB" -Or $ServerType -ne "TOM")
{
Write-Host -NoNewLine 'Server type not entered correctly'
}
I have also tried
If (($ServerType -ne "BOB") -or ($ServerType -ne "TOM"))
{
Write-Host -NoNewLine 'Server type not entered correctly'
}
However, when I only test for one value it works:
If ($ServerType -ne "BOB")
{
Write-Host -NoNewLine 'Server type not entered correctly'
}
Any ideas why I might be getting this?
As in my comment, the logical operator in this case should be -and but allow me to give you 2 examples where your validation could be improved.
First one is using the -match \ -notmatch comparison operators, which allows the use of regex:
$ServerType = Read-Host -Prompt 'Enter Server Type (BOB or TOM)'
if($ServerType -notmatch '^(bob|tom)$')
{
Write-Host -NoNewLine 'Server type not entered correctly'
}
Second one, is using a ValidateSet attribute:
try
{
[validateset('bob','tom')]
$ServerType = Read-Host -Prompt 'Enter Server Type (BOB or TOM)'
}
catch
{
Write-Host -NoNewLine 'Server type not entered correctly'
}
I am working on a PS script to generate .xml representations of a huge number of Crystal Reports (Windows 7). In this script, I create an object representing all the files that need to be parsed, then loop over them, calling an .exe on them one-by-one. Occasionally, this .exe crashes. This is fine because it's pretty rare and the reports that can't be processed can be flagged and reviewed manually. The problem is that I have thousands of .rpt files to process, and when the .exe crashes, Windows pops up a dialog asking to debug or continue.
Things I have tried in order to solve the issue:
HKEY_CURRENT_USER\Software\Microsoft\Windows\Windows Error Reporting\DebugApplications: I put my exe name here and set the value to 0 (don't debug)
HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\Windows Error Reporting\DebugApplications: same as above
Set the loop that calls the exe to SilentlyContinue
Turn off error reporting as follows: Control Panel > Action Center > Change Action Center Settings > Problem Reporting Settings > Change report settings for all users > "Never Check for Solutions" > OK > OK (This only disables the "Windows can check online..." dialog)
Still, I'm getting the popup. There is another reg key, which disables the "Program has stopped working" UI entirely, but I don't want to do that because as a developer of other applications, I need to know when things crash. I just want to exclude this script or the exe it calls from showing the UI.
If I can do that, then the script can run unattended.
The .exe that misbehaves is the latest binary release from here: https://github.com/ajryan/RptToXml and seems to fail when it encounters a null byte in the report file.
Here is my code:
[xml]$MainConfigFile = Get-Content "settings.config.xml"
[xml]$SSRSConfigFile = Get-Content "ssrs.config.xml"
[xml]$CrystalConfigFile = Get-Content "crystal.config.xml"
# create settings objects from xml objects
$MainSettings = #{
OutputPath = $MainConfigFile.Settings.OutputPath
SearchString = $MainConfigFile.Settings.SearchString
ParseCrystal = $MainConfigFile.Settings.ParseCrystal
ParseSSRS = $MainConfigFile.Settings.ParseSSRS
}
$CrystalSettings = #{
InputFolderPath = $CrystalConfigFile.CrystalSettings.InputFolderPath
ContinueOnError = $CrystalConfigFile.CrystalSettings.ContinueOnError
}
$RsSettings = #{
ReportServerUri = $SSRSConfigFile.RsSettings.ReportServerUri
RsVersion = $SSRSConfigFile.RsSettings.RsVersion
}
Clear
Write-Host "Ensure these settings are correct before you proceed:" -ForegroundColor Yellow
Write-Host ""
Write-Host "Main Settings" -ForegroundColor Green
$MainSettings
Write-Host ""
Write-Host "Crystal Settings" -ForegroundColor Green
$CrystalSettings
Write-Host ""
Write-Host "SSRS Settings" -ForegroundColor Green
$RsSettings
Write-Host ""
# user must confirm
[string]$SettingsOK=(Read-Host "[Y] to proceed, [N] to quit:")
if ($SettingsOK -ne "Y") {exit}
Write-Host ""
Write-Host "______________________________________"
Clear
# is the output path syntax valid?
if (!(Test-Path -Path $MainSettings.OutputPath -IsValid)) {
Write-Host -ForegroundColor Green "Output path syntax is invalid:" $MainSettings.OutputPath
exit
} else {
Write-Host -ForegroundColor Green "Output path syntax is correct:" $MainSettings.OutputPath
}
# does the output path exist?
if (!(Test-Path -Path $MainSettings.OutputPath)) {
Write-Host -ForegroundColor Yellow "Output path does not exist:" $MainSettings.OutputPath
[string]$CreateOutputPathOK=(Read-Host "[Y] to create the directory, [N] to quit.")
if ($CreateOutputPathOK -ne "Y") {exit} else {New-Item -Path $MainSettings.OutputPath -ItemType Directory}
} else {
Write-Host -ForegroundColor Green "Output path already exists:" $MainSettings.OutputPath
}
Write-Host ""
Write-Host "______________________________________"
Clear
# get all .rpt files in the input folder, recursively
$CrystalFiles=Get-ChildItem -Path $CrystalSettings.InputFolderPath -Include "*.rpt" -Recurse
Write-Host ""
# count files first and ask the user if they want to see the output, otherwise proceed
Write-Host -ForegroundColor Yellow $CrystalFiles.Count ".rpt files were found in" $CrystalSettings.InputFolderPath
[string]$ShowFilesOK=(Read-Host "[Enter] to proceed, [Y] to view the list of files in the directory, [N] to quit.")
if ($ShowFilesOK -eq "Y") {
Clear
# loop through the collection of files and display the file path of each one
$CrystalFiles | ForEach-Object -Process {$_.FullName.TrimStart($CrystalSettings.InputFolderPath)}
Write-Host "______________________________________"
# user must confirm
Write-Host ""
Write-Host -ForegroundColor Yellow "The above .rpt files were found in" $CrystalSettings.InputFolderPath
} elseif ($ShowFilesOK -eq "N") {exit}
Write-Host ""
[string]$ProcessingOK=(Read-Host "[Y] to proceed with .rpt file processing, [N] to quit:")
if ($ProcessingOK -ne "Y") {exit}
Write-Host ""
Write-Host "______________________________________"
Clear
# create a dir inside the output path to hold this run's output
Write-Host -ForegroundColor Green "Creating folder to hold this run's output..."
$RunDir = (New-Item -Path $MainSettings.OutputPath -Name "$(Get-Date -f yyyy-mm-dd__hh_mm_ss)" -ItemType Directory)
$RunDir.FullName
# use .NET ArrayList because immutable PS arrays are very slow
$Success = New-Object System.Collections.ArrayList
$Failure = New-Object System.Collections.ArrayList
#loop through the collection again, this time processing each file and dumping the output to the output dir
$CrystalFiles | ForEach-Object -ErrorAction SilentlyContinue -Process {
$RelativePathName = $_.FullName.TrimStart($CrystalSettings.InputFolderPath)
$XmlFileName = "$RunDir\$RelativePathName.xml"
# force-create the file to ensure the parent folder exists, otherwise RptToXML will crash trying to write the file
New-Item -Path $XmlFileName -Force
# then simply delete the empty file
Remove-Item -Path $XmlFileName
Write-Host -ForegroundColor Green "Processing file" $RelativePathName
CMD /c .\RptToXML\RptToXml.exe $_.FullName $RunDir\$($_.FullName.TrimStart($CrystalSettings.InputFolderPath)).xml
if ($LASTEXITCODE -eq 0) {
Write-Host "Success" $Success.Add($RelativePathName)} else {Write-Host "Failure" $Failure.Add($RelativePathName)}
}
$Success | Export-CSV "$RunDir\CrystalSuccess.txt"
$Failure | Export-CSV "$RunDir\CrystalFailure.txt"
I hate to do this, answering my own question, but I've found a workaround for now.
Before the loop:
# Disable WER temporarily
Set-ItemProperty "HKCU:\Software\Microsoft\Windows\Windows Error Reporting" -Name DontShowUI -Value 1
After the loop:
# Reset the WER UI reg key
Set-ItemProperty "HKCU:\Software\Microsoft\Windows\Windows Error Reporting" -Name DontShowUI -Value 0
This will be improved by calling this script from another script:
Get the current value of the key(s) to be modified
Change them
Call the script which returns control to the caller even if it crashes
Return the reg keys to their original value
I need to edit a script. There is a service that is on two Windows Server 2008 R2. They are load balanced. I need it so when I run the script that starts the service on the primary server and the secondary, so before it even start the service on both servers, the goes out and checks to ensure the primary server is up and running, then continues on as normal to start the services on both servers.
# Start Appian
function StartAppian {
$APNSVC = Get-Service -Name $AppianService
if (!$APNSVC) {
Write-Host "Appian Service does not exist"
return
}
# Check to see if Appian's service is already started
if ($APNSVC.Status -eq "Running") {
if ($LB) {
if ($MULEAPNSVC.Status -eq "Running") {
Write-Host "Appian Service on the Load Balanced Server already is started!" -ForegroundColor Yellow
return
}
}
Write-Host "Appian Service already is started!" -ForegroundColor Yellow
Read-Host "Press any key to return"
return
}
# Check if DEV's Process Design has a writing_*.kdb file and delete it
if ($Server -eq "DEV") {
#gw1
if (Test-Path $APPIAN_HOME\server\process\design\gw1\writing_*.kdb) {
Write-Host "Removing writing_*.kdb from GW1" -ForegroundColor Yellow
Remove-Item $APPIAN_HOME\server\process\design\gw1\writing_*.kdb
}
#gw2
if (Test-Path $APPIAN_HOME\server\process\design\gw2\writing_*.kdb) {
Write-Host "Removing writing_*.kdb from GW2" -ForegroundColor Yellow
Remove-Item $APPIAN_HOME\server\process\design\gw2\writing_*.kdb
}
}
Write-Host "Starting Appian"
# Place the name of the service here to start for Appian
Start-Service $AppianService
Notify("StartAppian")
if ($LB) {
(Get-Service $MULEAPNSVC.Name -ComputerName $MULE).Start()
Write-Host "Starting Mule's Appian" -ForegroundColor Magenta
}
cmd.exe "/C $APPIAN_HOME\server\_scripts\diagnostic\checkengine.bat -s > $logdir\Startup.log"
# These lines check the Startup log for fatals and errors at the beginning
$fatals = Select-String FATAL $logdir\Startup.log
$errs = Select-String ERROR $logdir\Startup.log
# Check for errors and fatals again
$fatals = Select-String FATAL $logdir\Startup.log
$errs = Select-String ERROR $logdir\Startup.log
Write-Host "Still warnings or Errors in CE" -ForegroundColor Yellow
# Increment times
$times = $times + 1
# If times > threshold, email out error message
if ($times -gt $threshold) {
SendAlert("There is a problem with Appian - It won't start")
Write-Host "There was a problem with Appian..it took too long to start - emailing alert" -ForegroundColor Red
Read-Host "Press any key to exit"
}
}
Write-Host "Appian Started" -ForegroundColor Green
Read-Host "Press any key to return"
}
You can do that with a simple Test-Connection at the start of the script.
if ($ping = Test-Connection -ComputerName PrimaryServerName -Quiet) {
Write-Host "Host avalible"
}
else {
Write-Host "Host unavalible"
Exit
}
any other suggestions?
if (Test-Connection ServerName -Count 1 -Quiet) {
Write-Host "Host avalible"
}
else {
Write-Host "Host unavalible"
Exit
}
this doesnt work. I want it to test the if the server is up or not, if its not, exit the script, if it is, continue on with the script. When testing this on ISE it work, but when i launch the script it doesn't
Is there a windows command that will allow me to verify a domain account/password?
You could use the command RUNAS, it is not technically a commandline to validate credentials, but it CAN be used for that.
runas /noprofile /user:mycomputer\administrator "notepad"
If it fails it returns:
RUNAS ERROR: Unable to run - notepad
1326: Logon failure: unknown user name or bad password.
RUNAS works great on a local system.
To verify credentials on a remote computer, I use the PSExec tool from SysInternals. I specify the username, then it prompts me for the password. Here is an example of what my command looks like:
psexec \\RemoteComputer -u DOMAIN\USER cmd.exe
If I enter the correct password, I'll be greeted with a command prompt. If I enter the wrong password, I get this:
PsExec could not start cmd.exe on RemoteComputer:
The user name or password is incorrect.
You can use this powershell script which does some extra testing (domain reachable, user name exists, account enabled, account unlocked).
Got this script from this post. Put this in a notepad, save as .ps1 and execute. It will prompt for credentials and provide feedback. Worked perfectly for my needs.
<#
.SYNOPSIS
Test domain username/password combination are correct
.DESCRIPTION
This script will check if the password for a given username is correct. If the authentication failed using the provided Domain\Username and Password.
The script will do some checks and provide some clues why the authentication failed.
The checks are:
* Domain is reachable.
* User Name exists in the domain.
* The account is Enabled.
* The account is Unlocked.
.EXAMPLE
.\Test-UserCredentials.ps1
or
Right click the script and select "Run with PowerShell"
.Notes
Created by: Ibrahim Soliman
Version: 1.6 (Enhanced error handling, and authentication failure root cause analysis.)
#>
#Import Active Directory Module
Import-Module Activedirectory
#Clear User Info Function
Function ClearUserInfo
{
$Cred = $Null
$DomainNetBIOS = $Null
$UserName = $Null
$Password = $Null
}
#Rerun The Script Function
Function Rerun
{
$Title = "Test Another Credentials?"
$Message = "Do you want to Test Another Credentials?"
$Yes = New-Object System.Management.Automation.Host.ChoiceDescription "&Yes", "Test Another Credentials."
$No = New-Object System.Management.Automation.Host.ChoiceDescription "&No", "End Script."
$Options = [System.Management.Automation.Host.ChoiceDescription[]]($Yes, $No)
$Result = $host.ui.PromptForChoice($Title, $Message, $Options, 0)
Switch ($Result)
{
0 {TestUserCredentials}
1 {"End Script."}
}
}
#Test User Credentials Function
Function TestUserCredentials
{
ClearUserInfo
#Get user credentials
$Cred = Get-Credential -Message "Enter Your Credentials (Domain\Username)"
if ($Cred -eq $Null)
{
Write-Host "Please enter your username in the form of Domain\UserName and try again" -BackgroundColor Black -ForegroundColor Yellow
Rerun
Break
}
#Parse provided user credentials
$DomainNetBIOS = $Cred.username.Split("{\}")[0]
$UserName = $Cred.username.Split("{\}")[1]
$Password = $Cred.GetNetworkCredential().password
Write-Host "`n"
Write-Host "Checking Credentials for $DomainNetBIOS\$UserName" -BackgroundColor Black -ForegroundColor White
Write-Host "***************************************"
If ($DomainNetBIOS -eq $Null -or $UserName -eq $Null)
{
Write-Host "Please enter your username in the form of Domain\UserName and try again" -BackgroundColor Black -ForegroundColor Yellow
Rerun
Break
}
# Checks if the domain in question is reachable, and get the domain FQDN.
Try
{
$DomainFQDN = (Get-ADDomain $DomainNetBIOS).DNSRoot
}
Catch
{
Write-Host "Error: Domain was not found: " $_.Exception.Message -BackgroundColor Black -ForegroundColor Red
Write-Host "Please make sure the domain NetBios name is correct, and is reachable from this computer" -BackgroundColor Black -ForegroundColor Red
Rerun
Break
}
#Checks user credentials against the domain
$DomainObj = "LDAP://" + $DomainFQDN
$DomainBind = New-Object System.DirectoryServices.DirectoryEntry($DomainObj,$UserName,$Password)
$DomainName = $DomainBind.distinguishedName
If ($DomainName -eq $Null)
{
Write-Host "Domain $DomainFQDN was found: True" -BackgroundColor Black -ForegroundColor Green
$UserExist = Get-ADUser -Server $DomainFQDN -Properties LockedOut -Filter {sAMAccountName -eq $UserName}
If ($UserExist -eq $Null)
{
Write-Host "Error: Username $Username does not exist in $DomainFQDN Domain." -BackgroundColor Black -ForegroundColor Red
Rerun
Break
}
Else
{
Write-Host "User exists in the domain: True" -BackgroundColor Black -ForegroundColor Green
If ($UserExist.Enabled -eq "True")
{
Write-Host "User Enabled: "$UserExist.Enabled -BackgroundColor Black -ForegroundColor Green
}
Else
{
Write-Host "User Enabled: "$UserExist.Enabled -BackgroundColor Black -ForegroundColor RED
Write-Host "Enable the user account in Active Directory, Then check again" -BackgroundColor Black -ForegroundColor RED
Rerun
Break
}
If ($UserExist.LockedOut -eq "True")
{
Write-Host "User Locked: " $UserExist.LockedOut -BackgroundColor Black -ForegroundColor Red
Write-Host "Unlock the User Account in Active Directory, Then check again..." -BackgroundColor Black -ForegroundColor RED
Rerun
Break
}
Else
{
Write-Host "User Locked: " $UserExist.LockedOut -BackgroundColor Black -ForegroundColor Green
}
}
Write-Host "Authentication failed for $DomainNetBIOS\$UserName with the provided password." -BackgroundColor Black -ForegroundColor Red
Write-Host "Please confirm the password, and try again..." -BackgroundColor Black -ForegroundColor Red
Rerun
Break
}
Else
{
Write-Host "SUCCESS: The account $Username successfully authenticated against the domain: $DomainFQDN" -BackgroundColor Black -ForegroundColor Green
Rerun
Break
}
}
TestUserCredentials
ClearUserInfo