If (-not ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")) {
    if ($elevated) {
        write-host "Intenté elevar el proceso y no funcionó!!!" -ForegroundColor red 
	Exit
    }
    else {
        Start-Process powershell.exe -Verb RunAs -ArgumentList ('-noprofile -noexit -file "{0}" -elevated' -f ($myinvocation.MyCommand.Definition))    
	Exit
    }

}
$DirectorioScript = [System.IO.Path]::GetDirectoryName($myInvocation.MyCommand.Definition)
$Password = ConvertTo-SecureString -AsPlainText -Force -String Jimmyhendrix1991
$Usuario = 'GESTask'

try {
    Import-Module Microsoft.Powershell.LocalAccounts
}
catch{} 

try {
    import-module activedirectory
    $Dominio = "S"
}
catch{
    $Dominio = "N" 
}

if ($Dominio -eq 'S') {  
try {
    $tmp = Get-ADUser -Filter ("SamAccountName -eq '" + $Usuario + "'")
}
catch {
        $Dominio = "N"
}
}
       if ($Dominio -eq 'N') {  
    try {
    $tmp = Get-LocalUser -Name $Usuario  }
    catch {}

               }
if ($tmp ) {
    Write-Host ('El usuario ' + $Usuario + ' existe') -ForegroundColor DarkGreen
}
else {
    Write-Host ('El usuario ' + $Usuario + ' NO EXISTE') -ForegroundColor Red
    $Crear = Read-Host -Prompt ('Desea crear el usuario ' + $Usuario + ' ? (S/n)'    )
    if ($Crear -eq 'S') {
        try {                               
            if ($Dominio -eq 'S') {  
                New-ADUser -Name $Usuario -Description 'Usuario de automatización del sistema GES' -Enabled $true -AccountPassword $PASSWORD
                try {
                    Add-ADGroupMember -Identity 'Administrators' -Members $Usuario    
                }
                catch {
                    try { 
                        Add-ADGroupMember -Identity 'Administradores' -Members $Usuario 
                    }
                    catch {
                        Write-Host $Error[0] 
                    }                   
                }
                
            }
            else {
                New-LocalUser  -Name $Usuario -Description 'Usuario de automatización del sistema GES' -Password $PASSWORD -PasswordNeverExpires 
                try {
                    Add-LocalGroupMember  -Group 'Administrators' -Member $Usuario    
                }
                catch {
                    try {
                        Add-LocalGroupMember  -Group 'Administradores' -Member $Usuario    
                    }
                    catch {
                        Write-Host $Error[0] 
                    }
                    
                }
                
            }
            Write-Host ('El usuario ' + $Usuario + ' ha sido creado') -ForegroundColor DarkGreen
        }
        catch {
            Write-Host $Error[0] 
            Write-Host ('Error al crear el usuario ' + $Usuario ) -ForegroundColor Red
        }
    }
}

$PathGES = ${Env:ProgramFiles(x86)} + '\Sistema\GES'
$PathGESTask = ${Env:ProgramFiles(x86)} + '\Sistema\GESTask'

if ((Test-Path $PathGESTask) -eq $true) {
    Write-Host ('La carpeta ' + $PathGESTask + ' existe')  -ForegroundColor DarkGreen
}
else {
    Write-Host ('La carpeta ' + $PathGESTask + ' NO EXISTE') -ForegroundColor Red

    $Crear = Read-Host -Prompt 'Desea crearla? (S/n)'    
    if ($Crear -eq 'S') {
        Copy-Item -Path $PathGES -Destination $PathGESTask -Recurse
	   
        $lasacls = Get-Acl $PathGES
        set-acl $PathGESTask -AclObject $lasacls
        
        Expand-Archive -Path ($DirectorioScript+"\GESTask.zip") -DestinationPath $PathGESTask
        #add-content -Path ($PathGESTask+"\ges.cfg") -Value 'SEC_GUARDAR_CLAVE=2'
		New-Item ($PathGESTask+"\Log") -itemType Directory
        Write-Host ('La carpeta ' + $PathGESTask + ' ha sido creada')  -ForegroundColor DarkGreen
    }
}
$Nombre=''
$Promm = 'Ingrese el nombre de la tarea GESTASK_* (GESTask_Comandos)'
if (!($Nombre = Read-Host $Promm)) { $Nombre = ('Comandos') }


$Promm = 'Ingrese el archivo a ejecutar (GESTask_' + $Nombre + '.cmd)'
$Archivo = ''
if (!($Archivo = Read-Host $Promm)) { $Archivo = ('GESTask_' + $Nombre + '.cmd') }

$Hora=[string](get-random -max 24)
$min=[string](get-random -max 60)
$Horario2=$Hora.padleft(2,'0')+":"+$Min.padleft(2,'0')
if (!($Horario = Read-Host -Prompt ('Ingrese el horario a ejecutarse ej: 23:30 o 06:30 ('+$horario2+')' ) )) {$Horario=$Horario2}



if (!($Repeticion = Read-Host -Prompt 'cada cuántas horas repite la ejecución ? (2)' )){$Repeticion=2}
$Trigger = New-ScheduledTaskTrigger -Daily -At $Horario

if ($Repeticion) {
    if ($Repeticion -ge 1) {
        $Trigger2 = New-ScheduledTaskTrigger -Once -At $Horario -RepetitionInterval (New-TimeSpan -hour $Repeticion) 
        $Trigger.Repetition=$Trigger2.Repetition
    }
}

$Action = New-ScheduledTaskAction -Execute ($PathGESTask + '\' + $Archivo) -WorkingDirectory $PathGESTask
$TKName = 'Solinges\' + $Nombre
$Descripcion = 'Tarea programada generada por la consola'



try {
    Register-ScheduledTask -Action $Action -TaskName $TKName -trigger $Trigger -Description $Descripcion -User $Usuario -Password Jimmyhendrix1991
    Write-Host ('Tarea ' + $TKName + ' creada!!!' ) -ForegroundColor DarkGreen
    $Ejecutar = Read-Host -Prompt 'Desea ejecutarla? (S/n)'  
    if ($Ejecutar -eq 'S') { 
        Start-ScheduledTask -TaskName $TKName 
        Get-ScheduledTask | Where-Object State -eq running 
    }
}
catch {
    Write-Host $Error[0]  -ForegroundColor Red
    Write-Host ('Error al crear la tarea ' + $TKName ) -ForegroundColor Red
}

   
Timeout /T 10

function FunctionName {
    param ( 
        $accountToAdd 
    )
    $sidstr = $null
    try {
        $ntprincipal = new-object System.Security.Principal.NTAccount "$accountToAdd"
        $sid = $ntprincipal.Translate([System.Security.Principal.SecurityIdentifier])
        $sidstr = $sid.Value.ToString()
    }
    catch {
        $sidstr = $null
    }
    Write-Host "Account: $($accountToAdd)" -ForegroundColor DarkCyan
    if ( [string]::IsNullOrEmpty($sidstr) ) {
        Write-Host "Account not found!" -ForegroundColor Red
        exit -1
    }
    Write-Host "Account SID: $($sidstr)" -ForegroundColor DarkCyan
    $tmp = ""
    $tmp = [System.IO.Path]::GetTempFileName()
    Write-Host "Export current Local Security Policy" -ForegroundColor DarkCyan
    secedit.exe /export /cfg "$($tmp)" 
    $c = ""
    $c = Get-Content -Path $tmp
    $currentSetting = ""
    foreach ($s in $c) {
        if ( $s -like "SeBatchLogonRight*") {
            $x = $s.split("=", [System.StringSplitOptions]::RemoveEmptyEntries)
            $currentSetting = $x[1].Trim()
        }
    }
    if ( $currentSetting -notlike "*$($sidstr)*" ) {
        Write-Host "Modify Setting ""Log on as a Batch Job""" -ForegroundColor DarkCyan
	
        if ( [string]::IsNullOrEmpty($currentSetting) ) {
            $currentSetting = "*$($sidstr)"
        }
        else {
            $currentSetting = "*$($sidstr),$($currentSetting)"
        }
	
        Write-Host "$currentSetting"
	
        $outfile = @"
[Unicode]
Unicode=yes
[Version]
signature="`$CHICAGO`$"
Revision=1
[Privilege Rights]
SeBatchLogonRight = $($currentSetting)
"@
	
        $tmp2 = ""
        $tmp2 = [System.IO.Path]::GetTempFileName()
	
	
        Write-Host "Import new settings to Local Security Policy" -ForegroundColor DarkCyan
        $outfile | Set-Content -Path $tmp2 -Encoding Unicode -Force
        #notepad.exe $tmp2
        Push-Location (Split-Path $tmp2)
	
        try {
            secedit.exe /configure /db "secedit.sdb" /cfg "$($tmp2)" /areas USER_RIGHTS 
            #write-host "secedit.exe /configure /db ""secedit.sdb"" /cfg ""$($tmp2)"" /areas USER_RIGHTS "
        }
        finally {	
            Pop-Location
        }
    }
    else {
        Write-Host "NO ACTIONS REQUIRED! Account already in ""Log on as a Batch Job""" -ForegroundColor DarkCyan
    }
    Write-Host "Done." -ForegroundColor DarkCyan
}
 