Archivo

Archivo para la categoría ‘powershell’

Script: inventario donde se relaciona usuario con equipo.

miércoles, 27 de marzo de 2013 Sin comentarios

 

Un problema común y fácilmente solucionable en todas los dominios, es el de asociar equipos con usuario.

Para tener un inventario y registro de usuarios que han pasado por cada uno de los equipos, hice un script bastante simple, el cual deja en una carpeta oculta en la red un registro con cierta información, como es: Usuario,dominio, nombre de equipo, fecha e ip. en un archivo de texto separado por comas.

$Date = Get-Date -format MM-dd-yyyy
$Time =     "{0:h:mm:ss tt zzz}" -f (get-date) #finalmente no se guarda para que funcione la búsqueda de duplicados.

$computer=get-content env:computername
$user= [System.Security.Principal.WindowsIdentity]::GetCurrent().Name
$Netip = Get-WmiObject -Class Win32_NetworkAdapterConfiguration -Filter IPEnabled=TRUE -computername localhost

add-content \\servidor\share$\Repositorio\infoequipos.txt -value ($user + "," + $computer + "," + $date + "," + $netip.ipaddress)

Saludos.

Categories: powershell Tags:

Script que permite limpiar o subir fotografía a AD.

martes, 26 de marzo de 2013 Sin comentarios

 

Hola.

Os cuelgo a continuación un Script que he terminado y que permite al usuario subir o limpiar su foto del directorio activo, para que luego se alimente, ya sabéis, Exchange, Lync, etc.

Diréis, ¿Por qué no lo haces en C# y lo compilas?, pues porque lo he ido haciendo en mis ratos libres y como muchas otras cosas, nació para algo diferente. Pero me gusta porque el usuario lo puede lanzar con unas simples instrucciones (botón derecho, ejecutar con poweshell) y al contrario de algunas aplicaciones, no tiene por qué, tener derechos de administrador local para instalarse nada. Sonrisa

Como es común en estas cosas, solo tenéis que localizar y adaptar esta línea de aquí:

$root = [ADSI]’GC://dc=dominio,dc=local’ #Inyecta el dominio con el que trabajar

Se que es mejorable,  lo se Guiño.

También tiene varias funciones que os pueden servir de utilidad.

#——————————————————
#Script encargado de guardar o limpiar fotografía en AD del campo Thumbnailphoto

#Autor: Miguel Hernández

#——————————————————

[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Drawing")
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")

#——————————————————————————-
#Funciones
#——————————————————————————-

#Toma usuario y lo devuelve con valor $X0
function tomausuario
{

    $objForm0 = New-Object System.Windows.Forms.Form
    $objForm0.Text = "Fotografía en Directorio Activo"
    $objForm0.Size = New-Object System.Drawing.Size(300,120)
    $objForm0.StartPosition = "CenterScreen"

    $objForm0.KeyPreview = $True
    $objForm0.Add_KeyDown({if ($_.KeyCode -eq "Enter")
        {$x0=$objTextBox0.Text;$objForm0.Close()}})    #toma el valor X0
    $objForm0.Add_KeyDown({if ($_.KeyCode -eq "Escape")
        {$objForm0.Close()}})

    $objLabel0 = New-Object System.Windows.Forms.Label
    $objLabel0.Location = New-Object System.Drawing.Size(10,10)
    $objLabel0.Size = New-Object System.Drawing.Size(280,20)
    $objLabel0.Text = "Usuario:"
    $objForm0.Controls.Add($objLabel0)

    $objTextBox0 = New-Object System.Windows.Forms.TextBox
    $objTextBox0.Location = New-Object System.Drawing.Size(10,30)
    $objTextBox0.Size = New-Object System.Drawing.Size(260,20)
    $objForm0.Controls.Add($objTextBox0)

    $OKButton0 = New-Object System.Windows.Forms.Button
    $OKButton0.Location = New-Object System.Drawing.Size(110,60)
    $OKButton0.Size = New-Object System.Drawing.Size(75,23)
    $OKButton0.Text = "OK"
    $OKButton0.Add_Click({$x=$objTextBox0.Text;$objForm0.Close()})
    $objForm0.Controls.Add($OKButton0)

    $objForm.Topmost = $True

    $objForm0.Add_Shown({$objForm0.Activate()})
    [void] $objForm0.ShowDialog()

return $x0

}

#———————————————————-
#Función resultado
#———————————————————-

#Abre form con el valor $valor escrito.

function resultado
{

    $objForm0 = New-Object System.Windows.Forms.Form
    $objForm0.Text = "Resultado"
    $objForm0.Size = New-Object System.Drawing.Size(400,90)
    $objForm0.StartPosition = "CenterScreen"

    $objLabel0 = New-Object System.Windows.Forms.Label
    $objLabel0.Location = New-Object System.Drawing.Size(10,20)
    $objLabel0.Size = New-Object System.Drawing.Size(380,20)
    $objLabel0.Text = $valor
    $objForm0.Controls.Add($objLabel0)

       $objForm.Topmost = $True

    $objForm0.Add_Shown({$objForm0.Activate()})
    [void] $objForm0.ShowDialog()
}

#————————————————————-
#Función donde se abre ventana donde elegir fotografía
#————————————————————-

function Select-FileDialog
    {
        param([string]$Title,[string]$Directory,[string]$Filter="All Files (*.*)|*.*")
        [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms") | Out-Null
        $objForm = New-Object System.Windows.Forms.OpenFileDialog
        $objForm.InitialDirectory = $Directory
        $objForm.Filter = $Filter
        $objForm.Title = $Title
        $objForm.ShowHelp = $true
        $Show = $objForm.ShowDialog()

        If ($Show -eq "OK")
        {
            Return $objForm.FileName
        }
        Else
        {
            $valor = "Operación cancelada por el usuario."
            resultado $valor
        }
    }

#——————————————————
#Empieza el script
#——————————————————

#Ventana Form donde se pregunta la acción a realizar

$objForm = New-Object System.Windows.Forms.Form
$objForm.Text = "Fotografía en Directorio Activo"
$objForm.Size = New-Object System.Drawing.Size(300,200)
$objForm.StartPosition = "CenterScreen"

$objForm.KeyPreview = $True
$objForm.Add_KeyDown({if ($_.KeyCode -eq "Enter")
    {$x=$objTextBox.Text;$objForm.Close()}})
$objForm.Add_KeyDown({if ($_.KeyCode -eq "Escape")
    {$objForm.Close()}})

$OKButton = New-Object System.Windows.Forms.Button
$OKButton.Location = New-Object System.Drawing.Size(75,130)
$OKButton.Size = New-Object System.Drawing.Size(75,23)
$OKButton.Text = "OK"
$OKButton.Add_Click({$x=$objTextBox.Text;$objForm.Close()})
$objForm.Controls.Add($OKButton)

$objLabel0 = New-Object System.Windows.Forms.Label
$objLabel0.Location = New-Object System.Drawing.Size(10,10)
$objLabel0.Size = New-Object System.Drawing.Size(280,20)
$objLabel0.Text = "1. Limpiar fotografía actual"
$objForm.Controls.Add($objLabel0)

$objLabel1 = New-Object System.Windows.Forms.Label
$objLabel1.Location = New-Object System.Drawing.Size(10,30)
$objLabel1.Size = New-Object System.Drawing.Size(280,20)
$objLabel1.Text = "2. Cambiar fotografía"
$objForm.Controls.Add($objLabel1)

$CancelButton = New-Object System.Windows.Forms.Button
$CancelButton.Location = New-Object System.Drawing.Size(150,130)
$CancelButton.Size = New-Object System.Drawing.Size(75,23)
$CancelButton.Text = "Cancelar"
$CancelButton.Add_Click({$objForm.Close()})
$objForm.Controls.Add($CancelButton)

$objLabel = New-Object System.Windows.Forms.Label
$objLabel.Location = New-Object System.Drawing.Size(10,70)
$objLabel.Size = New-Object System.Drawing.Size(280,20)
$objLabel.Text = "Seleccionar acción:"
$objForm.Controls.Add($objLabel)

$objTextBox = New-Object System.Windows.Forms.TextBox
$objTextBox.Location = New-Object System.Drawing.Size(10,90)
$objTextBox.Size = New-Object System.Drawing.Size(260,20)
$objForm.Controls.Add($objTextBox)

$objForm.Topmost = $True

$objForm.Add_Shown({$objForm.Activate()})
[void] $objForm.ShowDialog()

#Devuelve el valor $X con 1 o 2 = 1: Limpiar fotografía / 2: Cambiar fotografía

$SAMName = tomausuario  #Pregunta el usuario

    $root = [ADSI]’GC://dc=dominio,dc=local’  #Inyecta el dominio con el que trabajar
    $searcher = new-object System.DirectoryServices.DirectorySearcher($root)
    $searcher.filter = "(&(objectClass=user)(sAMAccountName=$SAMName))"
    $user = $searcher.findall()
    $userdn = $user[0].path
    $userdn = $userdn.trim("GC")
    $userdn = "LDAP" + $userdn
     
      
IF ($x -EQ "1") {

    try
    {
        $user = [ADSI]($userdn)
        $user.Properties["thumbnailPhoto"].Clear()
        $user.CommitChanges()
        $valor = "La fotografía ha sido borrada del servidor"
        resultado $valor
    }
    catch
    {
        $valor = "La fotografía no ha podido ser borrada del servidor"
        resultado $valor
    }
       
}

IF ($x -EQ "2") {
  
    try
    {
        $photo = Select-FileDialog -Title "Selecciona una fotografía (ext.jpg o .png)" -Directory "%userprofile%" -Filter "JPG Images (*.jpg)|*.jpg|PNG Images (*.png)|*.png"
        [byte[]]$file = Get-Content $photo -Encoding Byte
        $user = [ADSI]($userdn)
       
        # Limpiar foto anterior
        $user.Properties["thumbnailPhoto"].Clear()

        # Guardar fotografía
        $user.Properties["thumbnailPhoto"].Add($file)
        $user.CommitChanges()
        $valor = "La fotografía ha sido guardada del servidor"
        resultado $valor
    }
    catch
    {
        $valor = "La fotografía no ha sido guardada en el servidor"
        resultado $valor
    }      
}

Categories: Directorio Activo, Exchange, lync, powershell Tags:

>Windows PowerShell V2 – pre-realease

domingo, 4 de mayo de 2008 Sin comentarios

>El link es este.

Lo podeis leer en la descarga, pero destaco especialmente:

This software is a pre-release version and should not be deployed in a production environment. It will not work the way a final version of the software does. Features will change before final release.

The Windows PowerShell V2 remoting features work correctly only on Windows Vista with Service Pack 1 (SP1) and on Windows Server 2008.

Selected New Features in Windows PowerShell V2 CTP2 (Please refer to Release Notes and Help topics for more details)
PowerShell Remoting
Graphical PowerShell
ScriptCmdlets
Modules
Transactions
Eventing
Restricted Runspaces
RunspacePools
Background Jobs
Data Language
Script Internationalization
Script Debugging
51 New Cmdlets
Parser Tokenizer API
New PowerShell Hosting APIs
Metadata APIs for Command and Parameters

Categories: powershell Tags: