0

The PowerShell script functions fine if I run it line by line but when attempting to run the script as one the search for users does not come up in time for the next question. Please let me know on how I can force the third line of the script to come up as requested instead way later.

$name = Read-Host "What is the user's first name or letter?"

$list = Get-ADUser -Filter * | ? {$_.SamAccountName -match $name} | select SamAccountName | sort SamAccountName
$list


$DisableUser = Read-Host "Copy and paste the user here"
$t = $DisableUser
$year = Read-Host "Please input the year the user should be disabled, in this format (YYYY)"
$month = Read-Host "Please input the month the user should be disabled, in this format (MM)"
$day = Read-Host "Please input the day the user should be disabled, in this format (DD)"
$date = "$month/$day/$year"


$hour = Read-Host "Please input the hour of the day the user should be disabled, in this format (HH)"
$minute = Read-Host "Please input the minute the user should be disabled, in this format (MM)"
$seconds = Read-Host "Please input the second the user should be disabled, in this format (SS)"
$ampm = Read-Host "AM or PM?"
$Time = "${hour}:${minute}:${seconds} ${ampm}"


$dandt = "$date $Time"
$dandt

Write-host "$t will be disabled on this date, $dandt"

$answer = Read-Host "Is this correct? Please type Yes or No"
$l = $answer
    If ($l -like "y*")
    {Set-ADAccountExpiration $t -DateTime $dandt}
    ELSE { "Exiting"; Return}
2
  • First name in active directory is GivenName not SamaccountName. It looks like your search may be wrong. Commented Apr 26, 2018 at 17:23
  • Also, another tip. You might want to add your search into the -Filter param. This will help with performance. Currently you are pulling your whole directory then filtering. Commented Apr 26, 2018 at 17:26

1 Answer 1

2

You're combining output streams. Read-Host and Write-Host write directly to the console, while $list and $dandt standing by themselves output to standard output. They're desynchronized because they're different output streams. The solution is basically to force everything through one stream. Since you're using Read-Host, that means the console stream.

Change this:

$list

To one of these:

$list | Format-Table -AutoSize | Out-String | Write-Host
$list | Format-List | Out-String | Write-Host

And this:

$dandt

To this:

Write-Host $dandt

That said, this is not at all how I'd write something like this. I'd rather use ADUC/ADAC than this.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.