locked
Don't do this RRS feed

  • General discussion

  • That would be something like this

    [CmdletBinding()]
        param(
            [Parameter(Position=0,Mandatory=$false,ValueFromPipeline=$true)][string]$OUName="Test",
    		[Parameter(Position=0,Mandatory=$false,ValueFromPipeline=$true)][int]$RandomPwd=20
    	)
    
    #Clean Up VariableS
    $CleanUpVar=@()
    $CleanUpGlobal=@()
    
    
    #GLOBALs 
    $global:ScriptLocation = $(get-location).Path
    $global:DefaultLog = "$global:ScriptLocation\RandomResetPwd.log"
    $CleanUpGlobal+="ScriptLocation"
    $CleanUpGlobal+="DefaultLog"	
    	
    	
    function Write-Log{
        [CmdletBinding()]
        #[Alias('wl')]
        [OutputType([int])]
        Param(
                # The string to be written to the log.
                [Parameter(Mandatory=$true, ValueFromPipelineByPropertyName=$true, Position=0)] [ValidateNotNullOrEmpty()] [Alias("LogContent")] [string]$Message,
                # The path to the log file.
                [Parameter(Mandatory=$false, ValueFromPipelineByPropertyName=$true,Position=1)] [Alias('LogPath')] [string]$Path=$global:DefaultLog,
                [Parameter(Mandatory=$false, ValueFromPipelineByPropertyName=$true,Position=2)] [ValidateSet("Error","Warn","Info","Load","Execute")] [string]$Level="Info",
                [Parameter(Mandatory=$false)] [switch]$NoClobber
        )
    
         Process{
            
            if ((Test-Path $Path) -AND $NoClobber) {
                Write-Warning "Log file $Path already exists, and you specified NoClobber. Either delete the file or specify a different name."
                Return
                }
    
            # If attempting to write to a log file in a folder/path that doesn't exist
            # to create the file include path.
            elseif (!(Test-Path $Path)) {
                Write-Verbose "Creating $Path."
                $NewLogFile = New-Item $Path -Force -ItemType File
                }
    
            else {
                # Nothing to see here yet.
                }
    
            # Now do the logging and additional output based on $Level
            switch ($Level) {
                'Error' {
                    Write-Warning $Message
                    Write-Output "$(Get-Date -Format "yyyy-MM-dd HH:mm:ss") ERROR: `t $Message" | Out-File -FilePath $Path -Append
                    }
                'Warn' {
                    Write-Warning $Message
                    Write-Output "$(Get-Date -Format "yyyy-MM-dd HH:mm:ss") WARNING: `t $Message" | Out-File -FilePath $Path -Append
                    }
                'Info' {
                    Write-Host $Message -ForegroundColor Green
                    Write-Verbose $Message
                    Write-Output "$(Get-Date -Format "yyyy-MM-dd HH:mm:ss") INFO: `t $Message" | Out-File -FilePath $Path -Append
                    }
                'Load' {
                    Write-Host $Message -ForegroundColor Magenta
                    Write-Verbose $Message
                    Write-Output "$(Get-Date -Format "yyyy-MM-dd HH:mm:ss") LOAD: `t $Message" | Out-File -FilePath $Path -Append
                    }
                'Execute' {
                    Write-Host $Message -ForegroundColor Green
                    Write-Verbose $Message
                    Write-Output "$(Get-Date -Format "yyyy-MM-dd HH:mm:ss") EXEC: `t $Message" | Out-File -FilePath $Path -Append
                    }
                }
        }
    }	
    function Get-DistinguishedName{
        [CmdletBinding(DefaultParameterSetName="OU" )]
        param(
            [Parameter(Position=0,Mandatory=$true,ValueFromPipeline=$true,ParameterSetName="OU")]$OUName,
            [Parameter(Position=1,Mandatory=$true,ValueFromPipeline=$true,ParameterSetName="Other")]$UserName,
            [Parameter(Position=2,Mandatory=$true,ValueFromPipeline=$true,ParameterSetName="Other")][switch]$User
    
    
        )
        BEGIN{ }
        PROCESS{
            if($User){
                $getCN= Get-ADUser $UserName
            }
            else{
                $GetOUinAD = Get-ADOrganizationalUnit -Filter {Name -like $OUName}
            }
        }
        END{
            if($User){
                return $getCN.DistinguishedName
            }
            else{
                return $GetOUinAD.DistinguishedName
            }
        }
    }
    
    
    
    Write-Log -Level Info -Message "######################   * Start Script *   ######################"
    #Load AD module
    if( (Get-Command Get-ADUser).count -lt 1 ){
        try{
            Write-Log -Level Load -Message "Loading AD PS Module"
            Import-Module ActiveDirectory -Cmdlet New-ADUser,Get-ADUser,Set-ADUser
        }
        catch{
            $ErrorMessage = $_.Exception.Message
            Write-Log -Level Error -Message "There's no ActiveDirectory Module installed on the local computer, please use a computer with AD module installed ``n`r$ErrorMessage"
            exit(-1)
        }
    }
    else{
        Write-Log -Level Info -Message "The Active Directory Module is already loaded"
    }
    
    #Find OU by name
    $OuDn = Get-DistinguishedName -OUName $ou
    #Get all users in OU
    $AllIUsers = Get-ADUser -SearchBase "$OuDn" -Filter * | Select Name,SamAccountName
    
    #check number of users that will get his password changed
    $usersInOU = $AllIUsers.Count
    
    if($RandomPwd -gt $usersInOU){
        Write-log -level Error -Message "The number of users can't be greather than the users in the OU"
        Write-Error "The number of users can't be greather than the users in the OU"
    }
    else{
        $rdn = New-Object System.Random
        if($AllIUsers.count -gt 0){
    
            
            for($i=1; $i-le $RandomPwd;$i++){
                #new pwd
                $GetNewPwd = [System.Web.Security.Membership]::GeneratePassword(12,0)
                $EncryptedPassword = ConvertTo-SecureString $($GetNewPwd) -AsPlainText -Force
    
                #select user
                $user = [math]::Floor($rdn.NextDouble() * $usersInOU)
                $SelectedUser = $AllIUsers[$user]
                $UserDN = Get-DistinguishedName $SelectedUser.SamAccountName -user
    
                try{
                    Write-Log -Level Execute -Message "Changing password for the user $($SelectedUser.Name) for $GetNewPwd"
                    Set-ADAccountPassword "$UserDN" -reset -NewPassword $EncryptedPassword
                }
                catch{
                    try{
                        Write-Log -Level Warn -Message "Changing password for the user $($SelectedUser.Name) for $GetNewPwd ""Forced"""
                        Set-ADAccountPassword "$UserDN" -reset -NewPassword $EncryptedPassword -force
                    }
                    catch{
                        Write-Log -Level Error -Message "$_.Exception.Message"
                        break;
                    }
                    
                }
    
            }
        }
    }
    
    Write-Log -Level Info -Message "######################   * Stript Ended *   ######################"

    The users are taken by random so it can get changed twice the same user

    You need to set the OUName to one that already exists

    and set the number of users. (if the number of users that you pick to change randomly the users is bigger than the users in the OU you will get an error)


    • Edited by j0rt3g4 Monday, August 21, 2017 7:15 AM
    • Split by Bill_Stewart Monday, October 2, 2017 7:11 PM User should not be doing this
    Monday, August 21, 2017 7:14 AM