Thursday, May 30, 2013

Need to store Error prompts ?

You must have heard or read of using Start-Transcript and Stop Transcript to capture your entire PowerShell session. But if you want to capture only the output and error generated by a script, execute your scripts in below format.

PS> powershell.exe –noprofile –file c:\temp\Script.ps1 > C:\Temp\Log.txt

C:\Temp\Log.txt stores output of your script and the errors generated. This is useful when executing scripts for multiple computers.

Powershell – Bulk User Password Resets

This PowerShell script is used to reset Password for bulk users in a domain. This will prompt to change the password at logon.


1. Save the below script as SetBulkPassword.ps1 under c:\temp.

# import the AD module
if (-not (Get-Module ActiveDirectory)){
    Import-Module ActiveDirectory -ErrorAction Stop           
# set new default password
$password = ConvertTo-SecureString -AsPlainText "Password01" -Force 
# get list of account names (1 per line)
$list = Get-Content -Path c:\Temp\users.txt
# loop through the list
ForEach ($u in $list) {
    if ( -not (Get-ADUser -LDAPFilter "(sAMAccountName=$u)")) {
        Write-Host "Can't find $u"
    else {
        $user = Get-ADUser -Identity $u
        $user | Set-ADAccountPassword -NewPassword $password -Reset
        $user | Set-AdUser -ChangePasswordAtLogon $true
        Write-Output "changed password for $u" | Out-File -append c:\ temp\ResetPwdLog.txt

2. Create a file users.txt under c:\temp and store the usernames for which the password is required to be reset. The usernames should be the domain login IDs.

3. Open PowerShell with admin privileges and set the execution policy to unrestricted.

4. Execute the script in below format in order to log the error generated.

   powershell.exe -noprofile -file c:\temp\SetBulkPassword.ps1 > C:\temp\ErrorLog.txt

5. Once execution is complete, two Log files will be generated under C:\temp i.e ResetPwdLog.txt and Errorlog.txt

ResetPwdLog.txt : Will log the details of the users for which password reset has been completed successfully.
ErrorLog.txt : This will store the errors generated while script execution.

Hope it helps :)