Power shell

 Script

#Comandos 


#New-ADUser = Crear usuarios

#Remove-ADUser = Borrar usuarios

#Get-ADUser = Listar/verificar usuario

#Set-ADUser = Modificar usuario

#Crear un usuario

New-ADUser Sole

#Borrar un usuario

Remove-ADUser Sole

#Crear un usuario con propiedades

New-ADUser -Name Sole -City Madrid -Company NoSoloHacking -Department Marketing -Description "Buena Gente" -DisplayName "Sole García" -EmailAddress sole@nosolohacking.info -Manager Carlos -Office "Edificio 1" -OfficePhone "+34 916524578" -Organization NoSoloHacking

#Mostrar un usuario

Get-ADUser -Identity sole

#Mostrar un usuario con todas alguna de propiedades

Get-ADUser -Identity sole -Properties description, city, department

#Mostrar un usuario con todas sus propiedades

Get-ADUser -Identity sole -Properties *

#Crear un usuario con propiedades y contrasena #ERROR

New-ADUser -Name Sole -AccountPassword 123456Aa -City Madrid -Company NoSoloHacking -Department Marketing -Description "Buena Gente" -DisplayName "Sole García" -EmailAddress sole@nosolohacking.info -Manager Carlos -Office "Edificio 1" -OfficePhone "+34 916524578" -Organization NoSoloHacking

#Crear usuario sin best practices

Remove-ADUser sole

New-ADUser sole -AccountPassword $(convertto-securestring "123456Aa" -AsPlainText -force)

Get-ADUser Sole

get-history

#Crear usuario con best practices

#Crear una variable para el usuario Password

$password = Read-host "Escribe una contrasena" -AsSecureString

#crear usuario con la nueva password de $password

Remove-ADUser -Identity sole

Get-ADUser sole

New-ADUser -Name Sole -City Madrid -Company NoSoloHacking -Department Marketing -Description "Buena Gente" -DisplayName "Sole García" -EmailAddress sole@nosolohacking.info -Manager Carlos -Office "Edificio 1" -OfficePhone "+34 916524578" -Organization NoSoloHacking -AccountPassword $password

Get-ADUser sole

Enable-ADAccount -Identity sole

#Modificar un usuario

Set-ADUser -Identity sole -Description "Smart"

Set-ADUser -Identity sole -Description "Smart" -city "London"

#Creación de usuarios en Bulk desde un csv

Import-Csv .\Usuarios.csv | Out-GridView

#Importar los usuarios y crearlos de manera automatizada y no muy elegante

Set-Location C:\Users\carlos\Desktop

Import-Csv .\Usuarios.csv | New-ADUser -AccountPassword $(convertto-securestring "PassW0rd!2325£" -AsPlainText -Force) -ChangePasswordAtLogon $true -Enabled $true -WhatIf

Import-Csv .\Usuarios.csv | New-ADUser -AccountPassword $(convertto-securestring "PassW0rd!2325£" -AsPlainText -Force) -ChangePasswordAtLogon $true -Enabled $true

#Borrado de usuarios en bulk

Import-Csv .\Usuarios.csv | ForEach-Object {Remove-ADUser -Identity $_.SamAccountname -Confirm: $false}

#Importar los usuarios y crearlos de manera automatizada y muy elegante

$password = Read-host "Escribe una contrasena" -AsSecureString

Set-Location C:\Users\carlos\Desktop

#Import-Csv .\Usuarios.csv | New-ADUser -AccountPassword $password -ChangePasswordAtLogon $true -Enabled $true -WhatIf

Import-Csv .\Usuarios.csv | New-ADUser -AccountPassword $password -ChangePasswordAtLogon $true -Enabled $true -Path "OU=Empleados,DC=nosolohacking,DC=info"

#Borrado Selectivo en Bulk

Get-ADUser -Filter 'description -eq "Sabio"' | Remove-ADUser -Confirm:$false

#Modificación en BULK

Get-ADUser -Filter 'description -eq "Sabio"' | set-ADUser -Description "Listo" -EmailAddress lalala@lololo.com -City "Los Angeles"

#Creación de PCs en Bulk

#Comandos a practicar

#New-ADcomputer = Crear un dispositivo

#Remove-ADcomputer = Borrar un dispositivo

#Get-ADcomputer = listar dispositivo

#set-ADcomputer = Modificar un dispositivo

#Importar los PCs y crearlos uno a uno

Import-Csv .\PCs.csv | New-adcomputer -whatif

Import-Csv .\PCs.csv | New-adcomputer

#Borrado de PCs en bulk

Import-Csv .\PCs.csv | ForEach-Object {Remove-adcomputer -Identity $_.SamAccountname -Confirm: $false}

#Borrado Selectivo en Bulk

Get-ADComputer -LDAPFilter "(description=*WindowsServer2019AD*)" | Remove-adcomputer -Confirm:$false -WhatIf

Get-ADComputer -LDAPFilter "(description=*WindowsServer2019AD*)" | Remove-adcomputer -Confirm:$false

#Modificación en BULK

Get-ADComputer -LDAPFilter "(description=*WindowsServer2019AD*)" | set-ADcomputer -Description "WS2019 AD"

#Admnistración de grupos en AD.

#Comandos a practicar

#New-ADGroup = Crear un grupo

#Remove-ADGroup = Borrar un grupo

#Add-ADGroupMember = Anadir miembros a un grupo

#remove-ADGroupMember = eliminar miembros de un grupo

#Get-ADGroupMember = listar miembros de un grupo

#Crear un grupo nuevo en el container por defecto (Users)

get-help New-ADGroup

New-ADGroup "Genios" -GroupCategory Security -GroupScope Global

#Crear un grupo nuevo en el container específico

New-ADGroup "Genios" -GroupCategory Security -GroupScope Global -Description "los mejores" -Path "OU=Empleados,DC=nosolohacking,DC=info"

New-ADGroup "torpes" -GroupCategory Security -GroupScope Global -Description "los lentos" -Path "OU=Empleados,DC=nosolohacking,DC=info"

#Borrar grupo

Remove-ADGroup -Identity "torpes" -WhatIf

Remove-ADGroup -Identity "torpes"

#Anadir un miembro al grupo

Add-ADGroupMember -Identity "Genios" -Members (Get-ADUser carlos) -WhatIf

Add-ADGroupMember -Identity "Genios" -Members (Get-ADUser carlos)

#Borrar un miembro al grupo

remove-ADGroupMember -Identity "Genios" -Members (Get-ADUser carlos) -WhatIf

remove-ADGroupMember -Identity "Genios" -Members (Get-ADUser carlos) -Confirm:$false

#Anadir en bulk usuarios a un grupo en base a un atributo

Add-ADGroupMember -Identity "Genios" -members ( Get-ADUser -Filter 'office -eq "Edificio1"')

#Borrar en bulk usuarios de un grupo en base a un atributo

remove-ADGroupMember -Identity "Genios" -members ( Get-ADUser -Filter 'office -eq "Edificio1"') -Confirm:$false

#Listar los miembros de un grupo de usuarios

Get-ADGroupMember "genios"

Get-ADGroupMember "genios" | Out-GridView

Get-ADGroupMember "genios" | Format-Table  name,samaccountname,objectclass

#Crear Variable del Dominio

$Dominio="DC=nosolohacking,DC=info"

$Dominio2="DC=pepe,DC=com"

#Crear OUs

New-ADOrganizationalUnit -name "Hackers" -Path $Dominio -ProtectedFromAccidentalDeletion:$false

New-ADOrganizationalUnit  -name "HelpDesk" -Path ("OU=Hackers,"+$Dominio)

#Obtener información de OUs

Get-ADOrganizationalUnit -Filter 'Name -like "*Hack*"'

#Borrar OUs

Remove-ADOrganizationalUnit -Identity "OU=Hackers,DC=nosolohacking,DC=info" -Confirm:$false

#Función que comprueba si existe la OU y la crea

function ExisteOU

{


   $NombreOU = $args[0]


   $Dominio = $args[1]


   $rutaOU = ("OU="+$NombreOU+","+$Dominio)


   if ([adsi]::Exists(("LDAP://" + $rutaOU)))


   {


      write-host ("La Unidad Organizativa " + $NombreOU + " ya existe.") -ForegroundColor Red


   }


   else


   {


      write-host ("Creando la OU "+$NombreOU+","+$Dominio) -ForegroundColor Green


      new-ADOrganizationalUnit -DisplayName $NombreOU -Name $NombreOU -path $Dominio


   }


}




#Llamada a la función

ExisteOU "Curso" $dominio

ExisteOU "Test" $dominio

ExisteOU "Mispe" ("OU=Test,"+$Dominio)

ExisteOU "Nivel2" ("OU=Mispe,OU=Test,"+$Dominio)

ExisteOU "Nivel3" ("OU=Nivel2,OU=Mispe,OU=Test,"+$Dominio)


#Comandos 

#search-adaccount = buscar un objeto

get-help Search-ADAccount

#Buscar objetos en AD

#Lista todos los objetos que estén deshabilitados

Search-ADAccount -AccountDisabled | FT Name,ObjectClass -A

##Lista todos los objetos del tipo Computer que estén deshabilitados

Search-ADAccount -AccountDisabled -computersOnly | FT Name,ObjectClass -A




##Lista todos los objetos del tipo Usuario que estén deshabilitados


Search-ADAccount -AccountDisabled -usersOnly | FT Name,ObjectClass -A

#Lista todos los objetos que hayan expirado

Search-ADAccount -AccountExpired | FT Name,ObjectClass -A

#Listar todos los objetos que van a expirar en 90 días

Search-ADAccount -AccountExpiring -TimeSpan 90.00:00:00 | FT Name,ObjectClass -A

##Listar todos los objetos que han estado inactivos los últimos 60 días

Search-ADAccount -AccountInactive -TimeSpan 60.00:00:00 | FT Name,ObjectClass -A

#Lista todos los objetos que tengan la password expirada

Search-ADAccount -PasswordExpired | FT Name,ObjectClass -A

##Lista todos los objetos con que nunca caduque la contrasena 

Search-ADAccount -PasswordNeverExpires | FT Name,ObjectClass -A 

#Lista todos los objetos que su cuenta esté bloqueada

Search-ADAccount -LockedOut | FT Name,ObjectClass -A

#Listar todos los objetos que van a expirar en una fecha en concreto

Search-ADAccount -AccountExpiring -DateTime "10/06/2029" | FT Name,ObjectClass -A

##Listar todos los objetos que están deshabilitados en un container específico en un server específico

Search-AdAccount -AccountDisabled -SearchBase "OU=Empleados,DC=nosolohacking,DC=info" -Server "AD" | FT Name,ObjectClass -A

Usuarios inactivos en AD

#Script para encontrar todos los usuarios inactivos en base a 4 criterios para elegir 1, dos acciones disponibles a elegir 1 y generación de un reporte.

Import-Module ActiveDirectory

# Selecciona los días de inactividad

$DaysInactive = 90

$InactiveDate = (Get-Date).Adddays(-($DaysInactive))

#-------------------------------

# Encontrar Usuarios inactivos

#-------------------------------

# A continuación 4 acciones para buscar usuarios inactivos. Selecciona la que sea más apropiada para ti o modfícala si lo necesitas.

# Obtén los usuarios que no se han logueado en los últimos XXXX días

$Users = Get-ADUser -Filter { LastLogonDate -lt $InactiveDate -and Enabled -eq $true } -Properties LastLogonDate | Select-Object @{ Name="Username"; Expression={$_.SamAccountName} }, Name, LastLogonDate, DistinguishedName

# Obtén los usuarios que no se han logueado en los últimos XXXX días y no son cuentas de servicios

$Users = Get-ADUser -Filter { LastLogonDate -lt $InactiveDate -and Enabled -eq $true -and SamAccountName -notlike "*svc*" } -Properties LastLogonDate | Select-Object @{ Name="Username"; Expression={$_.SamAccountName} }, Name, LastLogonDate, DistinguishedName

# Obtén los usuarios que no se han logueado nunca

$Users = Get-ADUser -Filter { LastLogonDate -notlike "*" -and Enabled -eq $true } -Properties LastLogonDate | Select-Object @{ Name="Username"; Expression={$_.SamAccountName} }, Name, LastLogonDate, DistinguishedName

# Automatizado incluyendo los que no se hanlogueado

$Users = Search-ADAccount -AccountInactive -DateTime $InactiveDate -UsersOnly | Select-Object @{ Name="Username"; Expression={$_.SamAccountName} }, Name, LastLogonDate, DistinguishedName

#-------------------------------

# Creación de reporte

#-------------------------------

# Exportarlo a CSV (Debéis tener creado el directorio c:\TEMP)

$Users | Export-Csv C:\Temp\InactiveUsers.csv -NoTypeInformation

#-------------------------------

# Administración de usuarios inactivos

#-------------------------------

# A continuación 2 acciones para buscar usuarios inactivos. Selecciona la que sea más apropiada para ti o modfícala si lo necesitas.

# Deshabilitar los usuarios inactivos

ForEach ($Item in $Users){

  $DistName = $Item.DistinguishedName

  Disable-ADAccount -Identity $DistName

  Get-ADUser -Filter { DistinguishedName -eq $DistName } | Select-Object @{ Name="Username"; Expression={$_.SamAccountName} }, Name, Enabled

}

# Borrado de usuarios inactivos

ForEach ($Item in $Users){

 Remove-ADUser -Identity $Item.DistinguishedName -Confirm:$false

  Write-Output "$($Item.Username) - Deleted"

}

PCs Inactivos en AD

#Script para encontrar todos los PCv inactivos en base a 3 criterios para elegir 1, dos acciones disponibles a elegir 1 y generación de un reporte.

Import-Module ActiveDirectory

# Selecciona los días de inactividad

$DaysInactive = 90

$InactiveDate = (Get-Date).Adddays(-($DaysInactive))

#-------------------------------

# Encontrar objetos de tipo PCs inactivos

#-A continuación 3 acciones para buscar PCs inactivos. Selecciona la que sea más apropiada para ti o modfícala si lo necesitas.

# Obtén los PCs que no se han logueado en los últimos XXXX días

$Computers = Get-ADComputer -Filter { LastLogonDate -lt $InactiveDate -and Enabled -eq $true } -Properties LastLogonDate | Select-Object Name, LastLogonDate, DistinguishedName

# Obtén los PCs que no se han logueado nunca

$Computers = Get-ADComputer -Filter { LastLogonDate -notlike "*" -and Enabled -eq $true } -Properties LastLogonDate | Select-Object Name, LastLogonDate, DistinguishedName

# Automatizado incluyendo los que no se hanlogueado

$Computers = Search-ADAccount -AccountInactive -DateTime $InactiveDate -ComputersOnly | Select-Object Name, LastLogonDate, Enabled, DistinguishedName

#-------------------------------

# Creación de reporte

#-------------------------------

# Exportarlo a CSV (Debéis tener creado el directorio c:\TEMP)

$Computers | Export-Csv C:\Temp\InactiveComputers.csv -NoTypeInformation

#-------------------------------

# Administración de usuarios inactivos

#-------------------------------

# A continuación 2 acciones para buscar usuarios inactivos. Selecciona la que sea más apropiada para ti o modfícala si lo necesitas.

# Deshabilitar los PCs inactivos

ForEach ($Item in $Computers){

  $DistName = $Item.DistinguishedName

  Set-ADComputer -Identity $DistName -Enabled $false

  Get-ADComputer -Filter { DistinguishedName -eq $DistName } | Select-Object Name, Enabled

}

# Borrado de PCs inactivos

ForEach ($Item in $Computers){

  Remove-ADComputer -Identity $Item.DistinguishedName -Confirm:$false

  Write-Output "$($Item.Name) - Deleted"

}

Averiguar el último login, fecha y DC de un usuario

Os dejo a continuación esta fantástica función que nos dice cual es el último timestamp del login de un usuario.


Para usarlo, copiar el código en ISE y llamar a la función.  Si queréis que sea permanente en vuestra navaja de utilidades, haced lo siguiente:

1) guardar el código con extensión .psm1

2) Crear una carpeta en "C:\Program Files\WindowsPowerShell\Modules" con el nombre Get-ADUserLastLogon y guardar el archivo ahí.

function Get-ADUserLastLogon { 

# .SYNOPSIS

# Get-ADUserLastLogon obtiene la información del último login de un usuario en Active directory.

 # .DESCRIPTION

# Cada controlador de dominio es consultado individualmente para calcular la fecha de último login.

 # .PARAMETER

# UserLogonName

# Proveer la cuenta de usuario (samaccountname).

 # .EXAMPLE

# Get-ADUserLastLogon -UserLogonName C.Melantuche

 [CmdletBinding()]

param

(

[Parameter(Mandatory=$true)]

$UserLogonName

)

$resultlogon=@()

Import-Module ActiveDirectory

$ds=dsquery user -samid $UserLogonName

If ($ds) {

$getdc=(Get-ADDomainController -Filter *).Name

foreach ($dc in $getdc) {

Try {

$user=Get-ADUser $UserLogonName -Server $dc -Properties lastlogon -ErrorAction Stop

$resultlogon+=New-Object -TypeName PSObject -Property ([ordered]@{

'User' = $user.Name

'DC' = $dc

'LastLogon' = [datetime]::FromFileTime($user.'lastLogon') 

}) 

}

Catch {

''

Write-Warning "No reports from $($dc)!" 

$resultlogon | Where-Object {$_.lastlogon -NotLike '*1601*'} | Sort-Object LastLogon -Descending | Select-Object -First 1 | Format-Table -AutoSize 

If (($resultlogon | Where-Object {$_.lastlogon -NotLike '*1601*'}) -EQ $null)

{

''

Write-Warning "No hay datos para $($user.name). Posible razón: Nunca se ha logueado en el dominio."

}

}

else 

{throw 'Usuario inexistente. Por favor compruebe el usuario.'}

}

Muestra la información de sesiones de uno o más PC/Servidores

Este escript lo he encontrado ne internet y es muy muy útil. Nos muestra los inicios y cierres de sesión de todos los usuarios por server/PC. Admite un servidor o más de uno. Lo único que tenéis que hacer es editar la línea 7, donde os detallo como poner más de un objeto de tipo dispositivo. Guardar el script como ps1 para ejecutarlo.

[CmdletBinding()]

param

(

    [Parameter()]

    [ValidateNotNullOrEmpty()]

    [string[]]$ComputerName = ($Env:COMPUTERNAME) #ejemplo string[]]$ComputerName = ($Env:COMPUTERNAME,"Server2","server1")

)

try {

    #region Defie all of the events to indicate session start or top

    $sessionEvents = @(

        @{ 'Label' = 'Logon'; 'EventType' = 'SessionStart'; 'LogName' = 'Security'; 'ID' = 4624 } ## Advanced Audit Policy --> Audit Logon

        @{ 'Label' = 'Logoff'; 'EventType' = 'SessionStop'; 'LogName' = 'Security'; 'ID' = 4647 } ## Advanced Audit Policy --> Audit Logoff

        @{ 'Label' = 'Startup'; 'EventType' = 'SessionStop'; 'LogName' = 'System'; 'ID' = 6005 }

        @{ 'Label' = 'RdpSessionReconnect'; 'EventType' = 'SessionStart'; 'LogName' = 'Security'; 'ID' = 4778 } ## Advanced Audit Policy --> Audit Other Logon/Logoff Events

        @{ 'Label' = 'RdpSessionDisconnect'; 'EventType' = 'SessionStop'; 'LogName' = 'Security'; 'ID' = 4779 } ## Advanced Audit Policy --> Audit Other Logon/Logoff Events

        @{ 'Label' = 'Locked'; 'EventType' = 'SessionStop'; 'LogName' = 'Security'; 'ID' = 4800 } ## Advanced Audit Policy --> Audit Other Logon/Logoff Events

        @{ 'Label' = 'Unlocked'; 'EventType' = 'SessionStart'; 'LogName' = 'Security'; 'ID' = 4801 } ## Advanced Audit Policy --> Audit Other Logon/Logoff Events

    )

        ## All of the IDs that designate when user activity starts

    $sessionStartIds = ($sessionEvents | where { $_.EventType -eq 'SessionStart' }).ID

    ## All of the IDs that designate when user activity stops

    $sessionStopIds = ($sessionEvents | where { $_.EventType -eq 'SessionStop' }).ID

    #endregion

    ## Define all of the log names we'll be querying


    $logNames = ($sessionEvents.LogName | select -Unique)

    ## Grab all of the interesting IDs we'll be looking for

    $ids = $sessionEvents.Id

    ## Build the insane XPath query for the security event log in order to query events as fast as possible

    $logonXPath = "Event[System[EventID=4624]] and Event[EventData[Data[@Name='TargetDomainName'] != 'Window Manager']] and Event[EventData[Data[@Name='TargetDomainName'] != 'NT AUTHORITY']] and (Event[EventData[Data[@Name='LogonType'] = '2']] or Event[EventData[Data[@Name='LogonType'] = '11']])"

    $otherXpath = 'Event[System[({0})]]' -f "EventID=$(($ids.where({ $_ -ne '4624' })) -join ' or EventID=')"

    $xPath = '({0}) or ({1})' -f $logonXPath, $otherXpath


    foreach ($computer in $ComputerName) {

        ## Query each computer's event logs using the Xpath filter

        $events = Get-WinEvent -ComputerName $computer -LogName $logNames -FilterXPath $xPath

        Write-Verbose -Message "Found [$($events.Count)] events to look through"

        ## Set up the output object

        $output = [ordered]@{

            'ComputerName'          = $computer

            'Username'              = $null

            'StartTime'             = $null

            'StartAction'           = $null

            'StopTime'              = $null

            'StopAction'            = $null

            'Session Active (Days)' = $null

            'Session Active (Min)'  = $null

        }

                ## Need current users because if no stop time, they're still probably logged in

        $getGiInstanceParams = @{

            ClassName = 'Win32_ComputerSystem'

        }

        if ($computer -ne $Env:COMPUTERNAME) {

           $getGimInstanceParams.ComputerName = $computer

        }

        $loggedInUsers = Get-CimInstance @getGimInstanceParams | Select-Object -ExpandProperty UserName | foreach { $_.split('\')[1] }

                ## Find all user start activity events and begin parsing

        $events.where({ $_.Id -in $sessionStartIds }).foreach({

                try {

                    $logonEvtId = $_.Id

                    $output.StartAction = $sessionEvents.where({ $_.ID -eq $logonEvtId }).Label

                    $xEvt = [xml]$_.ToXml()

                    ## Figure out the login session ID

                    $output.Username = ($xEvt.Event.EventData.Data | where { $_.Name -eq 'TargetUserName' }).'#text'

                    $logonId = ($xEvt.Event.EventData.Data | where { $_.Name -eq 'TargetLogonId' }).'#text'

                    if (-not $logonId) {

                        $logonId = ($xEvt.Event.EventData.Data | where { $_.Name -eq 'LogonId' }).'#text'

                    }

                    $output.StartTime = $_.TimeCreated

                          Write-Verbose -Message "New session start event found: event ID [$($logonEvtId)] username [$($output.Username)] logonID [$($logonId)] time [$($output.StartTime)]"

                    ## Try to match up the user activity end event with the start event we're processing

                    if (-not ($sessionEndEvent = $Events.where({ ## If a user activity end event could not be found, assume the user is still logged on

                                    $_.TimeCreated -gt $output.StartTime -and

                                    $_.ID -in $sessionStopIds -and

                                    (([xml]$_.ToXml()).Event.EventData.Data | where { $_.Name -eq 'TargetLogonId' }).'#text' -eq $logonId


                                })) | select -last 1) {

                        if ($output.UserName -in $loggedInUsers) {

                            $output.StopTime = Get-Date


                            $output.StopAction = 'Still logged in'

                        } else {

                            throw "Could not find a session end event for logon ID [$($logonId)]."

                        }

                    } else {

                        ## Capture the user activity end time

                        $output.StopTime = $sessionEndEvent.TimeCreated

                        Write-Verbose -Message "Session stop ID is [$($sessionEndEvent.Id)]"

                       $output.StopAction = $sessionEvents.where({ $_.ID -eq $sessionEndEvent.Id }).Label

                    }

                    $sessionTimespan = New-TimeSpan -Start $output.StartTime -End $output.StopTime

                    $output.'Session Active (Days)' = [math]::Round($sessionTimespan.TotalDays, 2)

                    $output.'Session Active (Min)'  = [math]::Round($sessionTimespan.TotalMinutes, 2)        

                    [pscustomobject]$output

                } catch {

                    Write-Warning -Message $_.Exception.Message

                }

            })

   }

} catch {

    $PSCmdlet.ThrowTerminatingError($_)

}

#Trabajar con la papelera de reciclaje

#Listar usuarios borrados

get-adobject -filter 'objectclass -eq "user" -AND IsDeleted -eq $True' -IncludeDeletedObjects -properties IsDeleted,LastKnownParent | Format-List Name,IsDeleted,LastKnownParent,DistinguishedName

#Listar equipos borrados

get-adobject -filter 'objectclass -eq "computer" -AND IsDeleted -eq $True' -IncludeDeletedObjects -properties IsDeleted,LastKnownParent | Format-List Name,IsDeleted,LastKnownParent,DistinguishedName

#Recuperar todos los usuarios borrados en la OU en la que estaban

get-adobject -filter 'objectclass -eq "user" -AND IsDeleted -eq $True' -IncludeDeletedObjects -properties IsDeleted,LastKnownParent | Restore-ADObject -WhatIf

#Recuperar todos los equipos borrados en la OU en la que estaban

get-adobject -filter 'objectclass -eq "computer" -AND IsDeleted -eq $True' -IncludeDeletedObjects -properties IsDeleted,LastKnownParent | Restore-ADObject

#Recuperar un objeto en otra OU

get-adobject -filter 'name -like "Sole*"' -IncludeDeletedObjects | Restore-ADObject –TargetPath "OU=Empleados,DC=nosolohacking,DC=info" -passthru





Entradas populares de este blog

Fwd: rev

¿Cómo funciona una estafa Port Out?

Cómo instalar OpenSSH en Windows Server 2016 1709