Break script if the condition match with text file - powershell

I am trying to create a script for checking the password for zip file. The passwords is stored in a text file. The script is working fine but I want to stop the script where the password is matched or can I export the csv file. can anyone help me with this
$passfile = Get-Content "C:\Users\parveen.kumar\Downloads\passwords.txt"
$7ZipexePath = "C:\Program Files\7-Zip\7z.exe"
$zipFile = "C:\users\parveen.kumar\Downloads\just.zip"
foreach ($password in $passwords)
{
Write-Host $password
& $7ZipexePath "t" $zipFile "-p$passfile"
if (-Not $?)
{
Write-Host $password "This is incorrect password."
} else {
Write-Host $password "This is the correct password." -ForegroundColor Red
}
}

$passfile = Get-Content "C:\Users\parveen.kumar\Downloads\passwords.txt"
$7ZipexePath = "C:\Program Files\7-Zip\7z.exe"
$zipFile = "C:\users\parveen.kumar\Downloads\just.zip"
foreach ($password in $passwords)
{
Write-Host $password
& $7ZipexePath "t" $zipFile "-p$passfile"
if (-Not $?)
{
Write-Host $password "This is incorrect password."
} else {
Write-Host $password "This is the correct password." -ForegroundColor Red;Break
}
}

Related

Add User Active Directory with password and compare with AD Password Complexity

I'm trying to use a script to create User account on my AD.(Newbie)
I use this kind of powershell code:
Import-Module ActiveDirectory
#Intro
$date = Get-Date -Format "dd-MM-yyyy"
Echo "The $date - Adding new user"
#GET NAME and SURNAME :
$name = Read-Host "Enter the NAME of the user, please ?"
$surname = Read-Host "Enter the SURNAME of the user, please?"
#Username
$login = ($surname).Substring(0, 1).ToLower() + $name.Substring(0, 2).ToLower()
#Password requirement
Write-Verbose -Message "The password must contains : 8 char. with 1 maj. , 1 min. et 1 number or 1 char special." -Verbose
$password = Read-Host "Enter the password"
#Verify login does not exist
Echo "Wait a seconds..."
if (Get-ADUser -Filter { SamAccountName -eq $login }) {
Write-Warning "User Already Exist! please Try again..."
.\new_user.ps1
}
else {
#User Creation With File Folder
try {
New-ADUser -Name "$name $surname" -GivenName $name -Surname $surname -SamAccountName $login -UserPrincipalName $login#contonso.com -AccountPassword (ConvertTo-SecureString -AsPlainText $password -Force) -PasswordNeverExpires $true -CannotChangePassword $True -Enabled $true -path “OU=User, DC=Contonso, DC=com”
Write-Verbose -Message "The user account $login has been created and is active. Send an email with these credential" -Verbose
}
catch {
$_ | Out-File -FilePath C:\LOGS\EU-$login-$date.txt
Write-Warning "Sorry. An error as occured creating the user account. Thanks to try again."
}
try {
New-Item -Path \\FILESERVER\D$\Share\4.Users -Name "$login" -ItemType Directory
Write-Verbose -Message "The file folder of $login is now available." -Verbose
}
catch {
$_ | Out-File -FilePath C:\LOGS\ER-$login-$date.txt
Write-Warning "Sorry. An error as occurred while creating the folder, please contact the IT Team.Thanks"
}
}
If i put example "apple" as a password, the code will continue creating the account with the password but the account is disable and on my log i will have "Password does not fit with Active Directory complexity (set on GPO).
So i know there is a cmd: "Get-ADDefaultDomainPasswordPolicy" how to use it to compare my password with this ?
I found some function on internet but they use password policy directly on the powershell script.
In my case i want to compare directly with the ADDefaultDomainPassword Policy.
Any Idea? Thanks a lot
To test if a password would pass the complexity rules, you can use below function:
function Test-DomainPassword {
# see: https://learn.microsoft.com/en-us/windows/security/threat-protection/security-policy-settings/password-must-meet-complexity-requirements
[CmdletBinding()]
Param (
[Parameter(Mandatory = $true, ValueFromPipeline = $true, Position = 0)]
[ValidateNotNullOrEmpty()]
[string]$Password,
[string]$SamAccountName = $null,
[string]$DisplayName = $null
)
$PasswordPolicy = Get-ADDefaultDomainPasswordPolicy -ErrorAction SilentlyContinue
if ($Password.Length -lt $PasswordPolicy.MinPasswordLength) {
Write-Verbose "Password '$Password' is too short. Minimal length is $($PasswordPolicy.MinPasswordLength)"
return $false
}
if (($SamAccountName) -and ($Password -match [regex]::Escape($SamAccountName))) {
Write-Verbose "The password '$Password' includes the users SamAccountName"
return $false
}
if ($DisplayName) {
# The displayName is parsed for delimiters: commas, periods, dashes or hyphens, underscores, spaces, pound signs, and tabs.
# If any of these delimiters are found, the displayName is split and all parsed sections (tokens) are confirmed not to be
# included in the password.
# Tokens that are shorter than three characters are ignored, and substrings of the tokens aren't checked.
$tokens = $DisplayName -split '[-,._ #\t]'
foreach ($token in $tokens) {
if (($token) -and ($token.Length -ge 3) -and ($Password -match [regex]::Escape($token))) {
Write-Verbose "The password '$Password' includes (part of) the users DisplayName"
return $false
}
}
}
if ($PasswordPolicy.ComplexityEnabled) {
# see: https://learn.microsoft.com/en-us/previous-versions/windows/it-pro/windows-2000-server/bb726984(v=technet.10)?redirectedfrom=MSDN
# chapter 'Passwords Must Meet Complexity Requirements':
# Passwords must use three of the four available character types:
# lowercase letters, uppercase letters, numbers, and symbols.
$failures = #()
# check for presence of
# - Uppercase: A through Z, with diacritic marks, Greek and Cyrillic characters
if ($Password -cnotmatch "[A-Z\p{Lu}\s]") {
$failures += "- The password is missing Uppercase characters"
}
# - Lowercase: a through z, sharp-s, with diacritic marks, Greek and Cyrillic characters
if ($Password -cnotmatch "[a-z\p{Ll}\s]") {
$failures += "- The password is missing Lowercase characters"
}
# - Base 10 digits (0 through 9)
if ($Password -notmatch "[\d]") {
$failures += "- The password is missing digits (0-9)"
}
# - Nonalphanumeric characters: ~!##$%^&*_-+=`|\(){}[]:;"'<>,.?/
if ($Password -notmatch "[^\w]") {
$failures += "- The password is missing Nonalphanumeric characters: ~!##$%^&*_-+=`|\(){}[]:;`"'<>,.?/"
}
# test if we have more than 1 mismatch (password needs at least 3 out of 4 to be OK)
if ($failures.Count -gt 1) {
Write-Verbose "The password '$Password' failed because:`r`n{0}" -f ($failures -join "`r`n")
return $false
}
}
$true
}
Use it like this:
# both parameters -SamAccountName and -DisplayName are optional
$displayName = '{0} {1}' -f $firstname, $surname
if (Test-DomainPassword -Password $password -SamAccountName $login -DisplayName $displayName -Verbose) {
# the password is OK, create the new user here:
$userParams = #{
SamAccountName = $login
GivenName = $firstname
Surname = $surname
DisplayName = $displayName
UserPrincipalName = '{0}#contonso.com'-f $login
AccountPassword = ConvertTo-SecureString -String $password -AsPlainText -force
PasswordNeverExpires = $true
CannotChangePassword = $true
Path = 'OU=User,DC=Contonso,DC=com'
Enabled = $true
# etcetera
}
New-ADUser #userParams
}
else {
Write-Warning "User $login NOT created because the password did not pass the test"
}

Convert DOC with macro to DOTM

I am trying to convert DOC files with macros to DOTM with macros. My code changes the files but after the marco section is totally broken. When I convert it manually my macro code stays.
My code is:
function ReleaseRef ($ref) {
if($ref){
([System.Runtime.InteropServices.Marshal]::ReleaseComObject(
[System.__ComObject]$ref) -gt 0)
[System.GC]::Collect()
[System.GC]::WaitForPendingFinalizers()
}
}
function Convert-DOC{
Param(
[Parameter(Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[string]$filepath,
[Parameter(Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[string]$filefilter
)
try {
$files = Get-ChildItem $filepath -Include "$filefilter" -recurse -ErrorAction SilentlyContinue | Where-Object { ($_.PSIsContainer -eq $false) -and ( $_.Extension -like "$filefilter") }
$totalfiles = $files.Count
[int]$currentfile = 0
Write-Host "converting files... [$totalfiles]"
#word object********************************
#load dotnet assembly
Add-Type -AssemblyName Microsoft.Office.Interop.Word
#create word object
$word = New-Object -ComObject Word.Application -Verbose:$false
$word.visible = $true
$word.DisplayAlerts = [Microsoft.Office.InterOp.Word.WdAlertLevel]::wdAlertsNone
foreach ($file in $files) {
#Current file number
[int]$currentfile = [int]$currentfile + 1
#Check for password
$catch = $false
try {
#open file
Write-Host $file
$worddoc = $word.Documents.Open($file.FullName, $null, $null, $null, "")
} catch {
#if error, file has password
Write-Host "$file is protected by Password, skipping..." -ForegroundColor Yellow
$catch = $true
continue
}
if ($catch -eq $false) {
try {
#**********convert file**********
write-host "converting " $file.fullname "file $currentfile of $totalfiles" -ForegroundColor DarkGreen
#check for links
if([IO.Path]::GetExtension($file) -eq ".doc"){
#check for macros in in file
if ($worddoc.HasVBProject) {
$doFixedFormat = [Microsoft.Office.Interop.Word.WdSaveFormat]::wdFormatXMLDocumentMacroEnabled
$newfile = ($file.fullname).substring(0, ($file.FullName).lastindexOf("."))
$newfile += ".docm"
} else {
$doFixedFormat = [Microsoft.Office.Interop.Word.XlFileFormat]::wdFormatXMLDocument
$newfile = ($file.fullname).substring(0, ($file.FullName).lastindexOf("."))
$newfile += ".docx"
}
}
#save file
if(Test-Path $newfile){
Write-host "$newfile already exists" -ForegroundColor Yellow
} else {
$worddoc.SaveAs($newfile, $doFixedFormat )
}
#close file
$worddoc.close()
Write-Host "done" -ForegroundColor DarkGreen
#**********Garbage Collector**********
$gc_int++
if([int]$gc_int -gt 5){
Write-Host 'Run Garbage Collector' -ForegroundColor DarkBlue -BackgroundColor White
[System.GC]::Collect()
[System.GC]::WaitForPendingFinalizers()
[int]$gc_int = 0
}
} catch {
$formatstring = "{0} : {1}`n{2}`n" +
" + CategoryInfo : {3}`n" +
" + FullyQualifiedErrorId : {4}`n" +
" + Filename : {5}`n"
$fields = $_.InvocationInfo.MyCommand.Name,
$_.ErrorDetails.Message,
$_.InvocationInfo.PositionMessage,
$_.CategoryInfo.ToString(),
$_.FullyQualifiedErrorId,
$file.fullname
Write-Host -Foreground Red -Background Black ($formatstring -f $fields)
"$fields" | Out-File ($scriptpath + '\error_convert.log') -Append
}
}
}
} finally {
#**********clean-up************
Write-Host ""
Write-Host "Cleaning Up" -ForegroundColor DarkMagenta
Write-Host "Quiting Word"
$word.Quit()
Write-Host "Garbage Collector"
[gc]::collect()
[gc]::WaitForPendingFinalizers()
Write-Host "Release Com Object Workbook"
$a = ReleaseRef($worddoc)
Write-Host "Release Com Object Word"
$a = ReleaseRef($word)
Write-Host "Finishing Clean-Up"
}
}
Convert-DOC -filepath "C:\_testmacro\" -filefilter "*.doc"
What I do is, checking if the file has a VB part and is so setting the extension:
[Microsoft.Office.Interop.Word.WdSaveFormat]::wdFormatXMLDocumentMacroEnabled
and then save it:
$worddoc.SaveAs($newfile, $doFixedFormat)
A similar function with XLS and XLAM works fine
Edit:
seems like I was missing a $worddoc.Convert() but now struggling with checkin/checkout
As my edit stated, I missed the convert command:
$worddoc.Convert()
$worddoc.SaveAs($newfile, $doFixedFormat)
before saving

Deleting Multiple Local Users

This is my first post in the community even though I was reading it for many years. The truth is that I just started scripting so I am very new to it. So I am trying to make a script that searches for a few specific local users and deletes them if it finds them.
Clear-Host
$ErrorActionPreference = 'Stop'
$VerbosePreference = 'Continue'
$USERNAME = "test1"
$ObjLocalUser = $null
try {
Write-Verbose "Searching for $($USERNAME) in LocalUser DataBase"
$ObjLocalUser = Get-LocalUser $USERNAME
Write-Verbose "User $($USERNAME) was found"
}
catch [Microsoft.PowerShell.Commands.UserNotFoundException] {
"User $($USERNAME) not was found" | Write-Warning
}
catch {
"An unspecifed error occured" | Write-Error
Exit # Stop Powershell!
}
if ($ObjLocalUser) {
Write-Verbose "Deleting User $($USERNAME)" #(Example)
$password = ConvertTo-SecureString -String "password" -AsPlainText -Force
$op = Get-LocalUser | Where-Object {$_.Name -eq $USERNAME}
if ($op)
{
Remove-LocalUser ($op) | Out-Null
}
}
This is what I have up to now. It seems to work good with one username but when I try to add more than one usernames in the variable it doesn't work. Can you please help?
So I found the solution to my question and it was pretty simple. That's the final code.
Clear-Host
$ErrorActionPreference = 'Stop'
$VerbosePreference = 'Continue'
$USERNAMES = #("test1","test2","test3","test14","testpass")
foreach ($username in $USERNAMES) {
$ObjLocalUser = $null
try {
Write-Verbose "Searching for $($username) in LocalUser DataBase"
$ObjLocalUser = Get-LocalUser $username
Write-Verbose "User $($username) was found"
}
catch [Microsoft.PowerShell.Commands.UserNotFoundException] {
"User $($username) was not found" | Write-Warning
}
catch {
"An unspecifed error occured" | Write-Error
Exit # Stop Powershell!
}
if ($ObjLocalUser) {
Write-Verbose "Deleting User $($username)" #(Example)
$password = ConvertTo-SecureString -String "password" -AsPlainText -Force
$op = Get-LocalUser | Where-Object {$_.Name -eq $username}
if ($op)
{
Remove-LocalUser ($op) | Out-Null
}
}
}

Remote Computer File Transfer PowerShell script does not do logging correctly

This is my remote computer file transfer PowerShell script:
#--------------------------------------------------------[Initialisations]-------------------------------------------------------
#Clears the contents of the DNS client cache
Clear-DnsClientCache
#Loading script configuration
$configuration = Get-Content '.\Resources\Remote Computer File Transfer Configuration.cfg' | Select-Object | ConvertFrom-StringData
#Initializing report file
New-Item -Path $configuration.ReportFile -ItemType File
$fileList = Get-Content -Path $configuration.FileList
$computerList = Get-Content -Path $configuration.ComputerList
#Initializing file counters
$successfulTransfers = 0
$failedTransfers = 0
#---------------------------------------------------------[Functions]----------------------------------------------------------
function Write-Log
{
param
(
[Parameter(Position = 0, Mandatory = $false)]
[String]
$OperationSuccessful,
[Parameter(Position = 1, Mandatory = $false)]
[String]
$Message,
[Parameter(Position = 2, Mandatory = $false)]
[String]
$LogSeparator
)
if($null -eq $LogSeparator)
{
$timestamp = Get-Date -Format "yyyy.MM.dd. HH:mm:ss:fff"
$logEntry = $timestamp + " - " + $Message
}
else
{
$logEntry = $LogSeparator
}
if($OperationSuccessful -eq "Successful")
{
Write-Host $logEntry -ForegroundColor Green -BackgroundColor Black
}
elseif($OperationSuccessful -eq "Failed")
{
Write-Host $logEntry -ForegroundColor Red -BackgroundColor Black
}
elseif($OperationSuccessful -eq "Partial")
{
Write-Host $logEntry -ForegroundColor Blue -BackgroundColor Black
}
else
{
Write-Host $logEntry -ForegroundColor Yellow -BackgroundColor Black
}
Add-content -Path $configuration.LogFile -Value $logEntry
Add-content -Path $configuration.ReportFile -Value $logEntry
}
function Send-Report
{
param
(
[Parameter(Position = 0, Mandatory = $true)]
[string]
$FinalMessage
)
if($configuration.SendReport -eq "true")
{
$body = $configuration.Body + "`n" + $FinalMessage
Send-MailMessage -SmtpServer $configuration.SmtpServer `
-Port $configuration.Port `
-To $configuration.To `
-From $configuration.From `
-Subject $configuration.Subject `
-Body $body `
-Attachments $configuration.ReportFile
Remove-Item -Path $configuration.ReportFile
}
}
#---------------------------------------------------------[Execution]----------------------------------------------------------
Write-Log -LogSeparator $configuration.LogTitle
Write-Log -LogSeparator $configuration.LogSeparator
#Get credential from user input
$credential = Get-Credential
$message = "User " + $credential.UserName + " entered credentials"
Write-Log -Message $message
foreach($file in $fileList)
{
if((Test-Path -Path $file) -eq $true)
{
$message = "Successfully checked " + $file + " file - ready for transfer."
Write-Log -OperationSuccessful "Successful" -Message $message
}
else
{
$message = "Failed to access " + $file + " file. It does not exist."
Write-Log -OperationSuccessful "Failed" -Message $message
$message = "Script stopped - MISSING FILE ERROR"
Write-Log -OperationSuccessful "Failed" -Message $message
Write-Log -Message $configuration.LogSeparator
Send-Report -FinalMessage $message
Exit
}
}
$message = "Successfully accessed all files - ready for transfer"
Write-Log -OperationSuccessful "Successful" -Message $message
#Start file transfer
Write-Log -Message "Started file transfer"
foreach($computer in $computerList)
{
#Mapping network drive
if((Test-Connection -TargetName $computer -Quiet -Count 1) -eq $true)
{
$message = "Successfully accessed " + $computer + " remote computer"
Write-Log -OperationSuccessful "Successful"-Message $message
#Network path creation to D partition on the remote computer
$partition = "\D$"
$networkPath = "\\" + $computer + $partition
#Try to create network drive to D partition on the remote computer
if(New-PSDrive -Name "T" -PSProvider "FileSystem" -Root $networkPath -Credential $credential)
{
$message = "Successfully mapped network drive to D partition on the " + $computer + " remote computer"
Write-Log -OperationSuccessful "Successful" -Message $message
$driveMappingSuccessful = $true
}
else
{
$message = "Failed to map network drive to D partition on the " + $computer + " remote computer"
Write-Log -OperationSuccessful "Failed" -Message $message
#Network path creation to C partition on the remote computer
$partition = "\C$"
$networkPath = "\\" + $computer + $partition
#Try to create network drive to C partition on the remote computer
if(New-PSDrive -Name "T" -PSProvider "FileSystem" -Root $networkPath -Credential $credential)
{
$message = "Successfully mapped network drive to C partition on the " + $computer + " remote computer"
Write-Log -OperationSuccessful "Successful" -Message $message
$driveMappingSuccessful = $true
}
else
{
$message = "Failed to map network drive to C partition on the " + $computer + " remote computer - Credential not valid"
Write-Log -OperationSuccessful "Failed" -Message $message
$driveMappingSuccessful = $false
}
}
}
else
{
$message = "Failed to access " + $computer + " remote computer - OFFLINE"
Write-Log -OperationSuccessful "Failed" -Message $message
$driveMappingSuccessful = $false
}
if($driveMappingSuccessful)
{
$path = "T:\" + $configuration.TransferFolder
if((Test-Path $path) -eq $true)
{
$message = "Successfully accessed " + $path + " folder"
Write-Log -OperationSuccessful "Successful" -Message $message
$deployingFolderSuccessful = $true
}
else
{
$message = "Failed to access " + $path + " folder - MISSING FOLDER ERROR"
Write-Log -OperationSuccessful "Failed" -Message $message
try
{
New-Item -Path $path -ItemType "Directory"
}
catch
{
Write-Log -OperationSuccessful "Failed" -LogSeparator $_.Exception
}
if((Test-Path $path) -eq $true)
{
$message = "Successfully created " + $path + " folder"
Write-Log -OperationSuccessful "Successful" -Message $message
$deployingFolderSuccessful = $true
}
else
{
$message = "Failed to create " + $path + " folder"
Write-Log -OperationSuccessful "Failed" -Message $message
$deployingFolderSuccessful = $false
}
}
if($deployingFolderSuccessful)
{
$fileList = Get-Content -Path $configuration.FileList
foreach($file in $fileList)
{
#File name extraction from file full path
$fileName = Split-Path $file -leaf
try
{
Copy-Item -Path $file -Destination $path -Force
}
catch
{
Write-Log -OperationSuccessful "Failed" -LogSeparator $_.Exception
}
$transferDestination = Join-Path -Path $path -ChildPath $file
if(Test-Path -Path $transferDestination)
{
$message = "Successfully transferred " + $fileName + " file to " + $transferDestination + " folder"
Write-Log -OperationSuccessful "Successful" -Message $message
$successfulTransfers ++
}
else
{
$message = "Failed to transfer " + $fileName + " file to " + $path + " folder"
Write-Log -OperationSuccessful "Failed" -Message $message
$failedTransfers ++
}
}
}
else
{
$message = "Canceld file transfer to " + $computer + " remote computer"
Write-Log -OperationSuccessful "Failed" -Message $message
}
}
else
{
$message = "Canceld file transfer to " + $computer + " remote computer"
Write-Log -OperationSuccessful "Failed" -Message $message
}
#Network drive removal
if($driveMappingSuccessful)
{
Remove-PSDrive -Name "T"
}
}
$message = "Completed Remote Computer File Transfer PowerShell Script"
Write-Log -Message $message
if($successfulTransfers -gt 0)
{
$message = "Successfully transferred " + $successfulTransfers + " files to " + $Destination + " folder"
Write-Log -OperationSuccessful "Successful" -Message $message
}
if($failedTransfers -gt 0)
{
$message = "Failed to transfer " + $failedTransfers + " files to " + $Destination + " folder"
Write-Log -OperationSuccessful "Failed" -Message $message
}
if(($successfulTransfers -gt 0 ) -and ($failedTransfers -eq 0))
{
$message = "Successfully transferred all files to " + $Destination + " folder"
Write-Log -OperationSuccessful "Successful" -Message $message
}
elseif(($successfulTransfers -gt 0 ) -and ($failedTransfers -gt 0))
{
$message = "Successfully transferred some files to " + $Destination + " folder with some failed"
Write-Log -OperationSuccessful "Partial" -Message $message
}
elseif(($successfulTransfers -eq 0 ) -and ($failedTransfers -gt 0))
{
$message = "Failed to transfer any file to " + $Destination + " folder"
Write-Log -OperationSuccessful "Failed" -Message $message
}
Write-Log -Message $configuration.LogSeparator
#Sends email with detailed report and deletes temporary report log file
Send-Report -FinalMessage $message
This is .cfg file:
LogTitle = *********************************************** Remote Computer File Transfer PowerShell Script Log ************************************************
LogSeparator = ******************************************************************************************************************************************************
SendReport = true
LogFile = .\\Resources\\Remote Computer File Transfer Log.log
ReportFile = .\\Resources\\Report.log
FileList = .\\Resources\\File-Paths.txt
ComputerList = .\\Resources\\Computer-List.txt
TransferFolder = _INSTALL
SmtpServer = smtp.mail.com
Port = 25
To = sistem.administrators#company.com
From = powershell#company.com
Subject = Remote Computer File Transfer Report
Body = This is an automated message sent from PowerShell script. Remote Computer File Transfer PowerShell Script has finished executing.
Something is wrong with logging. It must be a problem with Write-Log function. The script actually does the job but nothing is written on the console by Write-Log function, and it just writes this in the picture and I can't figure out why.
Grateful in advance!
As commenten, the if($null -eq $LogSeparator) test will never succeed, because if not given, the parameter $LogSeparator will be an empty string, not $null.
The function you have would work if you change that to if(!$LogSeparator) or if([string]::IsNullOrWhiteSpace($LogSeparator))
The function could be simplified by using a parameter that validates to a certain set of possible values. Extra advantage is that you get autocompletion in the editor aswell so you don't have to worry about sending a parameter value with a typo.
Something like this perhaps:
function Write-Log {
param (
[Parameter(Position = 0, Mandatory = $false)]
[ValidateSet('Success', 'Fail', 'Partial', 'None')]
[String]$OperationResult = 'None',
[Parameter(Position = 1, Mandatory = $false)]
[String]$Message
)
$timestamp = Get-Date -Format "yyyy.MM.dd. HH:mm:ss:fff"
$logEntry = $timestamp + " - " + $Message
switch ($OperationResult) {
'Success' { $fg = 'Green'; $bg = 'Black'; break }
'Fail' { $fg = 'Red'; $bg = 'Black'; break }
'Partial' { $fg = 'Blue'; $bg = 'Black'; break } # Cyan would be easier to read I think
default { $logEntry = $Message
$fg = 'Yellow'; $bg = 'Black' }
}
Write-Host $logEntry -ForegroundColor $fg -BackgroundColor $bg
Add-content -Path $configuration.LogFile -Value $logEntry
Add-content -Path $configuration.ReportFile -Value $logEntry
}
Testing:
Write-Log -Message $configuration.LogTitle
Write-Log -Message $configuration.LogSeparator
$message = "Successfully checked file - ready for transfer."
Write-Log -OperationResult Success -Message $message
$message = "Script stopped - MISSING FILE ERROR"
Write-Log -OperationResult Fail -Message $message
$message = "Script did not complete"
Write-Log -OperationResult Partial -Message $message
Write-Log -Message $configuration.LogSeparator
Result in console:
*********************************************** Remote Computer File Transfer PowerShell Script Log ************************************************
******************************************************************************************************************************************************
2020.07.30. 21:34:53:959 - Successfully checked file - ready for transfer.
2020.07.30. 21:34:53:959 - Script stopped - MISSING FILE ERROR
2020.07.30. 21:34:53:959 - Script did not complete
******************************************************************************************************************************************************

Powershell: Fix My Loop Logic

I am trying to get the logic straightened out for a loop that I need to continue to prompt a user to enter a valid UNC path. I have it set to test the path and output to the console that the path is invalid. But, after that, it moves back to my prompt for choice. I want it to instead, ask the user to enter another valid path before moving on to the next step. Here is my loop:
do{
Write-Host ""
$pathPrompt = Write-Host "Please enter path to file/folder:" -ForegroundColor Cyan;
$path = Read-Host;
$test = Test-Path $path
if($test -eq $false){
Write-Host "ERROR! Invalid Path!" -ForegroundColor Red
}
}until($test -eq $true){
Write-Host ""
Write-Host "Getting ACL on"$path -ForegroundColor Green
Get-NTFSAccess -Path $path
}
What am I missing or not doing right here?
Sounds like you want to reuse your validation test. You could put it in a function for reuse:
Function Get-ValidPath {
do {
Write-Host "`r`nPlease enter path to file/folder:" -ForegroundColor Cyan
$path = Read-Host
$test = Test-Path $path
if ($test -eq $false) {
Write-Host "ERROR! Invalid Path!" -ForegroundColor Red
}
} until ($test -eq $true)
$path
}
$validatedpath1 = Get-ValidPath
Write-Host "`r`nGetting ACL on $validatedpath1" -ForegroundColor Green
Get-NTFSAccess -Path $validatedpath1
$validatedpath2 = Get-ValidPath