Archivi categoria: Script

Script per creare connessione VPN L2TP

VPN-L2TP Perdete troppo tempo a creare una connessione VPN L2TP per un vostro utente?  

Create uno script con Powerhell!

Ecco come fare:

Create uno script con powershell con i parametri indicati nelle prime righe e lanciatelo. Sarà aggiunta alle connessioni VPN dell’utente loggato una nuova voce. Inoltre sul desktop dell’utente sarà creato un documento temporaneo txt contenente username/password della connessione che l’utente potrà salvare in altro modo per poi cancellare il file.

Questa la connessione creata:

MyVPN

E questo lo script:

$ActionType="add" #add, remove, ?
$VPNname="My VPN"
$VPNserverIP="72.32.150.108"
$VPNusername="vpnuser"
$VPNpassword="VPNpass!"
$L2TPpsk="PsK-PaSsWoRd*!"
$NetworkIPandSubnet="192.168.10.0/24"


function ShowInputParameters {
write-host "+--------------- PARAMETERS -----------------+"
write-host  "| Action=$ActionType"(" "*(40-("Action").length-$ActionType.Length))"|"
write-host  "| Name=$VPNname"(" "*(40-("Name").length-$VPNname.Length))"|"
write-host  "| Server=$VPNserverIP"(" "*(40-("Server").length-$VPNserverIP.Length))"|"
write-host  "| Username=$VPNusername"(" "*(40-("Username").length-$VPNusername.Length))"|"
write-host  "| Password=$VPNpassword"(" "*(40-("Password").length-$VPNpassword.Length))"|"
write-host  "| PSK=$L2TPpsk"(" "*(40-("PSK").length-$L2TPpsk.Length))"|"
write-host  "| Network and Subnet=$NetworkIPandSubnet"(" "*(40-("Network and Subnet").length-$NetworkIPandSubnet.Length))"|"
write-host "+--------------------------------------------+"
Write-Host  "`n"
}


function ShowCurrentConfigOld {}
function ShowCurrentConfig {
write-host "`n`n### CURRENT CONFIGURATION ###"
Get-VpnConnection | Select-Object Name,ServerAddress,ConnectionStatus,SplitTunneling,AuthenticationMethod | Sort-Object Name | ft -AutoSize
write-host "`n"
}

    Switch ($ActionType)
    {
    "?" {
                write-host "HELP: Choose [add|remove|?] as ActionType`n"
                write-host "Example add:`n`t*VPN_name`t`t=`tMyVPN`n`t*VPN_server...`t=`t29.55.32.224`n`t*username`t`t=`tvpnuser`n`t*password`t`t=`tmypassword`n`t*Preshared_key`t=`tThePreSHAredKey1!`n`t*Network_and...`t=`t192.168.10.0/24`n`n"
                write-host "Example remove:`n`t*VPN_name`t`t=`tMyVPN`n`t VPN_server...`t=`tx`n`t username`t`t=`tx`n`t password`t`t=`tx`n`t Preshared_key`t=`tx`n`t*Network_and...`t=`t192.168.10.0/24`n`n`t* = mandatory`n"
                ShowCurrentConfig
                exit
                }
    "add" {
            ShowInputParameters
            ShowCurrentConfig
            ## Test if VPNcredentialsHelper module is present
            if (!(get-installedmodule VPNcredentialsHelper -ErrorAction SilentlyContinue)) {install-module VPNcredentialsHelper -Scope CurrentUser -Force -ErrorAction SilentlyContinue}
            ## Test if VPN connection exist
            if (Get-VpnConnection $VPNname -ErrorAction SilentlyContinue) {write-host "### ADDING NEW VPN ###`n`tError: the VPN `"$VPNname`" already exist";exit}
            try {
                write-host "`n### ADD NEW VPN ###"
                write-host "`tAdding new VPN connection $VPNname ..."
                Add-VpnConnection -Name $VPNname -ServerAddress $VPNserverIP -PassThru -TunnelType L2tp -L2tpPsk $L2TPpsk -AuthenticationMethod MSChapv2 -SplitTunneling -RememberCredential -Force -ErrorVariable $ErroreAddVPN | out-null
                write-host "`t>VPN added"
                write-host "`tAdding username/password for connection $VPNname ..."
                $resultaddcredential=Set-VpnConnectionUsernamePassword -connectionname $VPNname -username $VPNusername -password $VPNpassword
                if ($resultaddcredential) {
                    write-host "`t>added credential for user $VPNusername"
                    $DesktopLocation=(Get-ItemProperty -Path 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders').Desktop
                    $CredentialFilePath=$DesktopLocation+"\credenziali VPN "+$VPNname+".txt"
                    ("Username=$VPNusername","Password=$VPNpassword") | Out-File $CredentialFilePath -Force
                    } else {
                    write-host "`t>Cannot add credential for user $VPNusername"
                    }
                } 
            catch {if ($ErroreAddVPN) {write-host "`tERROR: "; write-host "`t------";write-host -nonewline "`t";$ErroreAddVPN}}
            finally { write-host "### END NEW VPN ###`n"}   
                     
            try {
                write-host "`n### ADD NEW ROUTE ###"
                write-host "`tAdding new route to $NetworkIP to connection $VPNname ..."
                Add-VpnConnectionRoute -ConnectionName $VPNname -DestinationPrefix $NetworkIPandSubnet –PassThru -ErrorVariable ErroreRoute | Out-Null
                write-host "`t>Route $NetworkIPandSubnet added"
            } 
            catch {if ($ErroreRoute) {write-host "`tERROR: "; write-host "`t------";write-host -nonewline "`t";$ErroreRoute}}
            finally { write-host "### END NEW ROUTE ###`n"}  
            ShowCurrentConfig
            }

    "remove" {
                ShowInputParameters
                ## Test if VPN connection exist 
                if ((Get-VpnConnection $VPNname -ErrorAction SilentlyContinue) -eq $null) 
                    {
                    write-host "### REMOVE VPN ###`n`tError: the VPN `"$VPNname`" not exist"
                    ShowCurrentConfig
                    exit
                    }
                rasdial $VPNname /DISCONNECT | Out-Null
                ShowCurrentConfig
            try {
                write-host "`n### REMOVE ROUTE ###"
                write-host "`tdeleting route to $NetworkIPandSubnet to connection $VPNname ..."
                remove-VpnConnectionRoute -ConnectionName $VPNname -DestinationPrefix $NetworkIPandSubnet -ErrorVariable ErroreremoveRoute
                write-host "`t>Route removed"
                } 
            catch {if ($ErroreremoveRoute) {write-host "`tERROR: "; write-host "`t------";write-host -nonewline "`t";$ErroreremoveRoute}}
            finally {write-host "### END REMOVE ROUTE ###`n"}  
            
            try {
                write-host "`n### REMOVE VPN ###"
                write-host "`tdeleting VPN connection $VPNname ..."
                remove-VpnConnection -Name $VPNname -Force -ErrorVariable ErroreremoveVPN
                write-host "`t>VPN removed"
                } 
            catch {if ($ErroreremoveVPN) {write-host "`tERROR: "; write-host "`t------";write-host -nonewline "`t";$ErroreremoveVPN}}
            finally {write-host "### END REMOVE VPN ###`n";ShowCurrentConfig} 
             }
    default {write-host "ERRORE: azione sconosciuta"}
    }

.

.

.

.

.

.

.

.

.

.

.

Pubblicità

Verificare le patch di vulnerabilità per Meltdown e Spectre (c.d. Speculation Control)

MeltdonSpectreVerify Microsoft ha messo a disposizione un modulo PowerShell per verificare le compatibilità delle patch di vulnerabilità: il c.d. Speculation Control. Ecco come installarlo

Il 3 gennaio 2018, Microsoft ha iniziato a pubblicare il suo Security Bulletin mensile in anticipo per alcune piattaforme a causa dei nuovi difetti di sicurezza della CPU, comunemente denominati “Meltdown” e “Spectre”. Nella KB4072699 Microsoft ha pubblicato le patch per la sicurezza e per la compatibilità col software anti-malware.

Microsoft ha riscontrato un problema di compatibilità con alcuni prodotti software antivirus. Il problema di compatibilità si verifica quando le applicazioni antivirus effettuano chiamate non supportate nella memoria del kernel di Windows.

Lo script powershell che segue abilita il comando  Get-SpeculationControlSettings che consente di verificare se sono stati applicate le patch per la vulnerabilita suddetta.

Ecco lo script:

$DownloadLink="https://gallery.technet.microsoft.com/scriptcenter/Speculation-Control-e36f0050/file/185444/1/SpeculationControl.zip"
$Filezip=$env:temp+"\SpeculationControl.zip"
$ModuliPS=$PSHome+"\Modules\"
$SCpath=$PSHome+"\Modules\SpeculationControl\"
$WebClient = New-Object System.Net.WebClient
$WebClient.DownloadFile($DownloadLink,$Filezip)
$shell = New-Object -COM Shell.Application
$target = $shell.NameSpace($ModuliPS)
$zip = $shell.NameSpace($Filezip)
$target.CopyHere($zip.Items(), 16)
cd $SCpath
$StatoIniziale=get-ExecutionPolicy
set-executionpolicy unrestricted -Force
import-module $SCpath\SpeculationControl.psm1
set-executionpolicy $StatoIniziale -Force
Get-SpeculationControlSettings

Questo il risultato quando nessuna patch è stata applicata:

Speculation control settings for CVE-2017-5715 [branch target injection]
For more information about the output below, please refer to https://support.mic
rosoft.com/en-in/help/4074629

Hardware support for branch target injection mitigation is present: False
Windows OS support for branch target injection mitigation is present: False
Windows OS support for branch target injection mitigation is enabled: False

Speculation control settings for CVE-2017-5754 [rogue data cache load]

Hardware requires kernel VA shadowing: True
Windows OS support for kernel VA shadow is present: False
Windows OS support for kernel VA shadow is enabled: False

Suggested actions

 * Install BIOS/firmware update provided by your device OEM that enables hardwar
e support for the branch target injection mitigation.
 * Install the latest available updates for Windows with support for speculation
 control mitigations.
 * Follow the guidance for enabling Windows Server support for speculation contr
ol mitigations described in https://support.microsoft.com/help/4072698


BTIHardwarePresent             : False
BTIWindowsSupportPresent       : False
BTIWindowsSupportEnabled       : False
BTIDisabledBySystemPolicy      : False
BTIDisabledByNoHardwareSupport : False
KVAShadowRequired              : True
KVAShadowWindowsSupportPresent : False
KVAShadowWindowsSupportEnabled : False
KVAShadowPcidEnabled           : False

Ulteriori informazioni sull’output potranno essere reperite qui

Informazioni sulle patch da applicare potranno essere reperite anche sul sito di OVH Francia o sul sito di Achab (che ringraziamo entrambi pubblicamente).

Inventario programmi installati sui PC di un dominio

Find username Vorreste conoscere tutti i programmi installati su ogni PC del vostro dominio ma non sapete fare?

Ecco come realizzare un file txt/csv leggibile da Excel per analizzare i programmi installati.

Ecco come fare:
Create il seguente file con estensione ps1:

$IPconnectedcomputers=Get-WmiObject -class Win32_ServerConnection -computername localhost -namespace root\CIMV2| where-object {$_.computername -like "*.*.*.*"} | 
select-object computername -unique

# o in alternativa se volete controllare solo determinati PC
# $IPconnectedcomputers = @("PC129","PC179","PC120","PC144","PC37","PC182","PC002","PC156","PC20")

$TimestampReport=get-date -Format yyyyMMdd
$ReportSavePath=[environment]::getfolderpath("mydocuments")+"\Report\"+$TimestampReport
new-item $ReportSavePath -type directory -erroraction silentlycontinue

foreach($ip in $IPconnectedcomputers){

if ((test-connection $ip.computername -Count 1 -erroraction silentlycontinue).statuscode -eq 0)
 {
 #$pc=($ip.computername).Insert(0, "\\")
 $pc=[System.Net.Dns]::GetHostEntry($ip.computername).HostName
 write-host Collegamento a $pc
 gwmi win32_product -ComputerName $pc -erroraction silentlycontinue | select-object vendor,caption,version,__SERVER|Export-Csv -NoTypeInformation -force 
"$ReportSavePath\$PC.txt"
 write-host Fine connessione con $pc
 }
else
 {
 write-host Collegamento a $ip IMPOSSIBILE!
 }
}

write-host Elaborazione terminata
write-host premi un tasto per continuare...
read-host

Lanciatelo ed otterete dopo qualche minuto (dipende dal numero dei PC/servers presenti nel dominio) questo risultato:

Report PC da script

 
 
 

 

Saranno elencati tutti i vendors dei programmi ed i relativi programmi e versioni installate.
In un prossimo post spiegherò anche come disinstallare da remoto, con Powershell, i programmi invididuati.

 
N.B.

E’ necessario che gli script Powershell siano resi eseguibili (di default lo sono solo quelli firmati).
Per bypassare il problema e rendere eseguibili anche quelli non firmati lanciate Powershell come amministratore (tenete premuto Ctrl-Shift mentre cliccate sul relativo collegamento) e scrivete:

Set-ExecutionPolicy -ExecutionPolicy bypass

Impostare da remoto IP dinamico sui client di un dominio

Remote enable DHCP client Vorreste impostare da remoto il client DHCP dei PC di un dominio?

Mettetevi sul vostro server e usate questi script!

Spesso mi capitano nuove aziende che adottano sui propri PC gli IP statici, e quindi ho creato questi script per evitare di passare per ogni computer e cambiare la configurazione della scheda di rete.
Ecco come fare…

Nel vostro server create, in una share condivisa raggiungibile da tutti i client di un dominio, il file AbilitaDHCP.vbs.
Lo script sarà eseguito da remoto su ogni PC tramite l’utility PSEXEC (quindi scaricate i e scompattate il file psexec.exe nella cartella c:\windows\system32 del server da cui lancerete gli script).
Ecco lo script VBS da creare e condividere:

strComputer = "."
Set objWMIService = GetObject(_
    "winmgmts:\\" & strComputer & "\root\cimv2")
Set colNetAdapters = objWMIService.ExecQuery _
    ("Select * from Win32_NetworkAdapterConfiguration " _
        & "where IPEnabled=TRUE")
 
For Each objNetAdapter In colNetAdapters
    errEnable = objNetAdapter.EnableDHCP()
    errEnable = objNetAdapter.SetDNSServerSearchOrder()
Next

Ora create lo script DHCP-DNS-auto-da-remoto.ps1 come di seguito indicato. Quando lo lancerete vi sarà chiesto di inserire il nome del PC;
lo script quindi verificherà su tutte le schede di rete abilitate del PC se il client DHCP è già attivo e poi chiederà se volete abilitarlo.

$PC = read-host "Inserire il nome del PC da controllare"
$test=Get-WmiObject win32_networkadapterconfiguration -computername $PC -erroraction silentlycontinue | where {($_.IPenabled)}
if ($test) {
	$test|ft ipaddress, dhcpenabled, dhcpserver ,DNSServerSearchOrder -AutoSize
	if ($test.dhcpenabled) {
		write-host "L'host"$PC "ha gia' il DHCP attivo"
	} 
	else {
		$Risposta = read-host "Vuoi abilitare DHCP/DNS automatici su"$PC"? (S/N)"
		if ($Risposta -eq "S") {
			psexec -accepteula \\$PC cscript /B /NoLogo \\server\condivisione\AbilitaDHCP.vbs
			psexec -accepteula \\$PC ipconfig /all
			read-host 
			}
	}
}
else {
	write-host Host $PC non raggiungibile
}

Loggare tutti gli accessi ad un dominio e reperire le informazioni del PC


Trace
Vorreste conoscere indirizzo IP, MAC, nome computer e sistema operativo di ogni PC nella rete?

Con lo script giusto eseguito durante il logon possiamo recuperare tutto ciò che ci serve!

Anzitutto bisognerà creare una nuova cartella in c:\windows\logs chiamata LogonLogs

Mkdir %WINDIR%\logs\LogonLogs

Create un file TraceLogon.bat in una cartella condivisa raggiungibile da qualsiasi PC nel dominio quindi modificate il file dello script di logon (dovrebbe essere nella cartella \\nomedominio\netlogon) ed aggiungete una riga che punti al file .bat.
Il file Tracelogon.bat conterrà i seguenti comandi:

@echo off
set GIORNOMESE=%date:~0,2%
SET FileDiLog=\\server\condivisione\\Logon-giorno%GIORNOMESE%.Log
set TAB=	
echo. >>%FileDiLog%

REM ========= VERIFICA TIPO OS ===============
FOR /F "TOKENS=1 DELIMS=." %%O IN ('wmic path Win32_OperatingSystem get version ^| FIND /i "."') DO SET TipoOS=%%O
FOR /F "TOKENS=1 DELIMS=" %%P IN ('wmic path Win32_OperatingSystem get caption ^| FIND /i "Windows"') DO SET DescrizioneOS=%%P

echo ================================= 
echo ================================= >>%FileDiLog%


REM ========= DATA ORA ===============
for /f "tokens=1-4 delims=/ " %%a in ('date /T') do set day=%%a
for /f "tokens=2 delims=/ " %%b in ('date /T') do set month=%%b
for /f "tokens=3 delims=/ " %%c in ('date /T') do set year=%%c
set TODAY=%day%-%month%-%year%
for /f "tokens=1 delims=: " %%h in ('time /T') do set hour=%%h
for /f "tokens=2 delims=: " %%m in ('time /T') do set minutes=%%m
set NOW=%hour% %minutes%
echo Ora%TAB%%TODAY% %NOW% 
echo Ora%TAB%%TODAY% %NOW%>>%FileDiLog%


REM ========= UTENTE, NOME COMPUTER ===============
echo Utente%TAB%%USERNAME%
echo Utente%TAB%%USERNAME%>>%FileDiLog%
echo PC%TAB%%COMPUTERNAME%
echo PC%TAB%%COMPUTERNAME%>>%FileDiLog%
echo OS%TAB%%DescrizioneOS%
echo OS%TAB%%DescrizioneOS% >>%FileDiLog%

REM ========= INDIRIZZO IP ===============
SET IPADDR=
SET OLDIPADDR=
setlocal ENABLEDELAYEDEXPANSION
if [%TipoOS%]==[5] (set COMANDONETSH1=netsh interface ip show address) ELSE (set COMANDONETSH1=netsh interface ipv4 show addresses) 
FOR /F "TOKENS=2* DELIMS= " %%A IN ('%COMANDONETSH1% ^| FIND /i "IP"') DO call :AggiungiIPADDR %%B
echo IP%TAB%%IPADDR%>>%FileDiLog%
endlocal
goto fine-ipaddr
:AggiungiIPADDR
set IP=%1
echo IP%TAB%!IP!
SET IPADDR=!IPADDR!!IP!%TAB%
goto :eof
:fine-ipaddr



REM ========= INDIRIZZI MAC ===============
setlocal ENABLEDELAYEDEXPANSION
FOR /F "TOKENS=1,2 DELIMS=:" %%A IN ('ipconfig /all ^| FIND /i "fisico"') DO call :AggiungiMAC "%%A" "%%B"
echo MAC%TAB%%ListaMAC%>>%FileDiLog%
endlocal
goto fine-MAC
:AggiungiMAC
if %2=="" (
set MAC=%1
set MAC=!MAC: =!
set MAC=!MAC:"=!
echo MAC%TAB%!MAC!
SET ListaMAC=!ListaMAC!!MAC!%TAB%
set MAC=
) else (
set MAC=%2
set MAC=!MAC: =!
set MAC=!MAC:"=!
echo MAC%TAB%!MAC!
SET ListaMAC=!ListaMAC!!MAC!%TAB%
set MAC=
)
goto :eof
:fine-MAC


REM ========= INDIRIZZO DNS ===============
SET IPADDR=
SET OLDIPADDR=
if [%TipoOS%]==[5] (set COMANDONETSH2=netsh interface ip show dns) ELSE (set COMANDONETSH2=netsh interface ipv4 show dnsserver) 
setlocal ENABLEDELAYEDEXPANSION
FOR /F "TOKENS=1,2 DELIMS=:" %%A IN ('%COMANDONETSH2% ^| FIND /i "."') DO call :AggiungiDNS "%%A" "%%B"
echo DNS%TAB%%ListaDNS%>>%FileDiLog%
endlocal
goto fine-DNS
:AggiungiDNS
if %2=="" (
set DNS=%1
set DNS=!DNS: =!
set DNS=!DNS:"=!
echo DNS%TAB%!DNS!
SET ListaDNS=!ListaDNS!!DNS!%TAB%
set DNS=
) else (
set DNS=%2
set DNS=!DNS: =!
set DNS=!DNS:"=!
echo DNS%TAB%!DNS!
SET ListaDNS=!ListaDNS!!DNS!%TAB%
set DNS=
)
goto :eof
:fine-DNS

Ecco un esempio delle informazioni che il batch recupera:

================================= 
Ora	19-03-2015 03 26
Utente	Pippo
PC	PC-20
OS	Microsoft Windows 7 Professional   
IP	192.168.143.48 	127.0.0.1	
MAC	C8-9C-DC-D0-6E-38	
DNS	192.168.143.9	192.168.143.10	

Create poi un file c:\Windows\System32\SpostaLogonLog.bat con il seguente contenuto:

@echo off
set CARTELLAORIGINE=c:\cartellacondivisa
set GIORNOMESE=%date:~0,2%
move /y %CARTELLAORIGINE%\Logon-Giorno*.log %WINDIR%\logs\LogonLogs
echo LOG DEGLI ACCESSI GIORNO %giornomese% > %CARTELLAORIGINE%\Logon-Giorno%giornomese%.log

Pianificate l’avvio del file SpostaLogonLog.bat (come amministratore) alle 0:00 ogni giorno.

Quindi potrete vedere nella cartella %WINDIR%\logs\LogonLogs tutti i files di log dell’ultimo mese.

Cambiare i permessi ai files con Powershell

Find username

Vorreste cambiare i permessi di una serie di files usando Powershell ma non sapete come fare?

Ecco la funzione per voi!

Mi è capitato che un virus cambiasse tutti i permessi dei files EXE nella cartella di Windows, con le conseguenze che potete immaginare.
Quindi ho creato questa funzione per Powershell che modifica i premessi di un file.

La sintassi è questa:

ImpostaAutorizzazioni -Percorso "percorso_del_file" -IdentitaDaAutorizzare "Utente_o_gruppo" -TipoAutorizzazione "Tipo_di_permesso"


Dove il tipo di permesso può essere: FullControl, ReadAndExecute, Read.

Ecco come realizzare la funzione in Powershell:

function ImpostaAutorizzazioni()
{
Param(
   [Parameter(Mandatory=$True,Position=1)]
   [string]$Percorso,
	
   [Parameter(Mandatory=$True,Position=2)]
   [string]$IdentitaDaAutorizzare,

   [Parameter(Mandatory=$True,Position=3)]
   [ValidateSet("FullControl", "ReadAndExecute", "Read")]
   [string]$TipoAutorizzazione

)


    $Acl = (Get-Item $Percorso).GetAccessControl('Access')
    Write-Host "Percorso:" $Percorso "Utente da autorizzare:" $IdentitaDaAutorizzare "Tipo autorizzazione:" $TipoAutorizzazione
    $RegolaAccesso = New-Object system.security.accesscontrol.filesystemaccessrule(
         $IdentitaDaAutorizzare,$TipoAutorizzazione,"Allow"
    )
    $Acl.SetAccessRule($RegolaAccesso)
    Write-Host $Acl
    $Acl | Set-Acl $Percorso
}

Esempi:
Per permettere all’utente TrustedInstaller il controllo completo del file attrib.exe:

ImpostaAutorizzazioni "C:\Windows\System32\attrib.exe" "NT SERVICE\TrustedInstaller" "FullControl"

Per permettere al gruppo di utenti NOMEDOMINIO\Domain Admins il permesso di lettura/scrittura del file attrib.exe:

ImpostaAutorizzazioni "C:\Windows\System32\attrib.exe" "NOMEDOMINIO\Domain Admins" "ReadAndExecute"

Per cambiare il permesso a tutti i files exe presenti nella cartella c:\programmi\adobe e relative sottocartelle ed assegnare a Everyone il controllo di sola lettura:

get-childitem "c:\programmi\adobe" -recurse -include *.exe | % {ImpostaAutorizzazioni $_.fullname "Everyone" "Read"}


P.S.

Per cambiare i permessi potrebbe essere necessario anche assumere la proprietà (ownership) del file.
In questo caso basterà usare il comando takeown /f nomefile

Lanciare un comando da remoto su ogni PC acceso in un dominio

remote command

Volete lanciare un comando remoto su ogni PC collegato al dominio mentre gli utenti sono connessi? Ad esempio volete inviare un messaggio alla console di ognuno o aggiornare le policies?

Powershell ci da una mano.

Ecco come fare:
Anzitutto è necessario scaricare dal sito di Microsoft il tool PSEXEC presente all’interno dei PsTools.
PsExec consente di lanciare un comando su un PC connesso alla rete senza che l’utente connesso alla console se ne renda conto. Una funzionalità veramente eccezionale di cui non possiamo che ringraziare il grande Mark Russinovich.
Dopo aver scaricato i PsTools vi consiglio di copiare il file psexec.exe nella cartella %windir%\system32.
Una volta che avremo a disposizione questo tool bisognerà capire quali PC sono collegati al nostro server; per questo useremo il comando net session.
Questo comando restituisce l’indirizzo IP di ogni PC connesso al nostro server. Il risultato del comando si presenta così:

C:\Users\Administrator>net session

Computer            Nome utente   Tipo client  In pausa da
------------------------------------------------------------------
\\192.168.143.35    utente1                    1 00.08.45
\\192.168.143.41    utente23                   4 00.01.22
\\192.168.143.42    utente12                   3 00.01.54
\\192.168.143.43    utente16                   6 01.46.35
\\192.168.143.44    utente43                   3 00.00.01
\\192.168.143.46    utente3                   63 00.00.03

Questo ci servirà a comprendere bene il comando che utilizzeremo in Powershell.
Esso infatti acquisisce tutti gli IP dal comando net session e li riutilizza per lanciare un comando dal prompt dei comandi in remoto.
Ecco il piccolo script da lanciare in powershell:

net session | ?{$_ -match '^\\\\\S*' }|% {$_.split(' ')[0]}| ForEach-Object -Process {psexec $_ cmd /c COMANDO}

Di seguito alcuni esempi pratici:

Aggiornare le group policies su tutti i PC:

net session | ?{$_ -match '^\\\\\S*' }|% {$_.split(' ')[0]}| ForEach-Object -Process {psexec $_ cmd /c echo n ^|gpupdate /force}

Inviare un messaggio alla console di tutti i PC connessi:

net session | ?{$_ -match '^\\\\\S*' }|% {$_.split(' ')[0]}| ForEach-Object -Process {psexec $_ cmd /c msg * Riavviare i PC}

Creare una determinata cartella in ogni PC connesso:

net session | ?{$_ -match '^\\\\\S*' }|% {$_.split(' ')[0]}| ForEach-Object -Process {psexec $_ cmd /c mkdir c:\PIPPO}

Script per aggiungere automaticamente una firma ad Outlook su Exchange 2010/2013

Find username

Vorreste creare una firma in Outlook automaticamente acquisendo le informazioni da Active directory?

Si può fare!


Normalmente in Active directory vengono salvate poche informazioni come nome e cognome, ma è possibile salvare molte più informazioni che possono essere utilizzate per creare automaticamente una firma completa senza che l’utente debba inserire alcuna informazione.
Grazie ad uno script vbs si potrà così creare un oggetto ADSystemInfo che raccoglie tutte le informazioni presenti in Active Directory e mostrarle nella firma. Nella figura qui di seguito potrete notare che è possibile estrarre qualsiasi attributo presente nell’utente da includere nella firma.

ADattributes

Nella seguente immagine troverete impostati i principali attributi utili nell’utilizzo della firma:

UserAD

Ecco un esempio già pronto ed il relativo codice:
Signature

On Error Resume Next 
Set objSysInfo = CreateObject("ADSystemInfo") 
strUser = objSysInfo.UserName 
Set objUser = GetObject("LDAP://" & strUser) 
strName = objUser.FullName 

strNome = objUser.Description 
strUfficio = objUser.physicalDeliveryOfficeName
strReparto = objUser.Department
strTitolo = objUser.Title
strSocieta = objUser.company 
strVia = objUser.streetAddress 
strLocalita = objUser.l
strTelefonoFisso = objUser.telephoneNumber 
strFax = objUser.FacsimileTelephoneNumber
strCellulare = objUser.Mobile
strProvincia = objUser.st
strEmail = objUser.mail

Set objWord = CreateObject("Word.Application") 
Set objDoc = objWord.Documents.Add() 
Set objSelection = objWord.Selection 
Set objEmailOptions = objWord.EmailOptions 
Set objSignatureObject = objEmailOptions.EmailSignature 
Set objSignatureEntries = objSignatureObject.EmailSignatureEntries 
Set objShape = objSelection.InLineShapes.AddPicture("\\NOMESERVER\CONDIVISIONE\logofirma.jpg") 

objSelection.TypeParagraph()
'objSelection.TypeText chr(11)
objSelection.Font.Size = "8" 
objSelection.Font.Name = "Verdana" 
objSelection.Font.Bold = true 
objSelection.TypeText strNome   
if not strTitolo="" then 
	objSelection.Font.Size = "6"  
	objSelection.Font.Bold = false 
	objSelection.Font.Italic = true 
	objSelection.TypeText Chr(11) & strTitolo 
end if
if not strUfficio="" then 
	objSelection.Font.Size = "6"  
	objSelection.Font.Bold = false 
	objSelection.Font.Italic = false 
	objSelection.TypeText Chr(11) & strUfficio 
end if
if not strReparto="" then 
	objSelection.Font.Size = "6"  
	objSelection.Font.Bold = false 
	objSelection.Font.Italic = false 
	objSelection.TypeText Chr(11) & strReparto 
end if 

objSelection.TypeParagraph() 


'objSelection.Style = "No Spacing" 
objSelection.Font.Italic = true 
objSelection.Font.Color = RGB(45,129,81)
objSelection.Font.Size = "8"   
objSelection.Font.Name = "Verdana" 
objSelection.Font.Bold = true 
objSelection.TypeText "NOMEAZIENDA" & Chr(11) 
objSelection.Font.Size = "6"  
objSelection.TypeText "INDIRIZZO" & Chr(11)
objSelection.TypeText "CAP LOCALITA (PROV)" & Chr(11)
objSelection.TypeText "Telefono: NUMERODITELEFONO" & Chr(11)
objSelection.TypeText "Fax: NUMERODIFAX"
if not strCellulare="" then objSelection.TypeText Chr(11) & "Mobile: " & strCellulare
objSelection.TypeText Chr(11) & "E-mail: " & strEmail 
objSelection.TypeParagraph() 

Set objSelection = objDoc.Range() 

objSignature = objSignatureEntries.Add("Firma con logo", objSelection) 
objSignatureObject.NewMessageSignature = "Firma con logo" 
objSignatureObject.ReplyMessageSignature = "Firma con logo" 
objDoc.Saved = True 
objWord.Quit 

Creare icone personalizzate sul desktop con uno script di logon


Find username

Vi piacerebbe far apparire le icone che volete sul desktop dei vostri client automaticamente?
Potete usare uno script di logon per automatizzare il processo.

Ecco il procedimento:

Bisognerà aggiungere una linea al vostro script di logon per lanciare un file .vbs
Questa la sintassi della riga da aggiungere:

%windir%\system32\cscript.exe \\NOMESERVER\NOMECONDIVISIONE\nomefilediscript.vbs

Poi provvediamo a creare il file di script vbs:

PER CREARE UN’ICONA CHE PUNTA AD UNA CARTELLA/FILE:

dim WshShell
dim oMyShortcut
dim strDesktop
set WshShell = CreateObject("Wscript.shell")
strDesktop = WshShell.SpecialFolders("Desktop")
set oMyShortcut = WshShell.CreateShortcut(strDesktop +"\società.lnk")
oMyShortcut.IconLocation ="%LOGONSERVER%\script\società.ico"
OMyShortcut.TargetPath ="%LOGONSERVER%\Società"
oMyShortCut.Hotkey ="ALT+CTRL+S"
oMyShortCut.Save

SE CI SONO ARGOMENTI DA LANCIARE:

dim WshShell
dim oMyShortcut
dim strDesktop
set WshShell = CreateObject("WScript.Shell")
strDesktop = WshShell.SpecialFolders("Desktop")
set oMyShortCut= WshShell.CreateShortcut(strDesktop+"\Trova contatti.lnk")
oMyShortCut.WindowStyle = 3 ''2=Minimized 3=Maximized 1=Normal 
oMyShortcut.IconLocation = "C:\Program Files\Windows Mail\wab.exe"
oMyShortCut.TargetPath ="C:\Program Files\Windows Mail\wab.exe"
oMyShortCut.Arguments = " /find"
oMyShortCut.WorkingDirectory ="c:\"
oMyShortCut.Save

PER CREARE COLLEGAMENTI A PAGINE HTML:

dim WshShell
dim oMyShortcut
dim strDesktop
Set WshShell = CreateObject("WScript.Shell")
strDesktop = WshShell.SpecialFolders("Desktop")
Set oUrlLink = WshShell.CreateShortcut(strDesktop+"\Sistemisti Senior Blog.URL")
oUrlLink.TargetPath ="https://sistemistisenior.wordpress.com"
oUrlLink.Save

ESEMPI DI TUTTI I CASI PRECEDENTI:

Dim WshShell
Dim oMyShortcut
Dim strDesktop
Dim netobj
Dim Username
Dim oMyShortcut2
Dim strDesktop2
Dim oMyShortcut3
Dim strDesktop3

Set WshShell = CreateObject("Wscript.shell")
strDesktop = WshShell.SpecialFolders("Desktop")

Set oMyShortcut = WshShell.CreateShortcut(strDesktop + "\Company.lnk")
oMyShortcut.IconLocation = "\\server-01\ClientApps\company.ico"
oMyShortcut.TargetPath = "\\server-01\Company"
oMyShortcut.Hotkey = "ALT+CTRL+S"
oMyShortcut.Save


Set netobj = CreateObject("Wscript.Network")
Username = netobj.Username
Set oMyShortcut2 = WshShell.CreateShortcut(strDesktop + "\" + Username + ".lnk")
oMyShortcut2.TargetPath = "\\server-01\users\" + Username + "\Documenti"
oMyShortcut2.Save

Set oMyShortcut3 = WshShell.CreateShortcut(strDesktop + "\Gestionale.lnk")
oMyShortcut3.IconLocation = "S:\GESTIONALE\GEST.ICO"
oMyShortcut3.TargetPath = "S:\GESTIONALE\GEST.EXE"
oMyShortcut3.Arguments = " /UTENTE VC1"
oMyShortcut3.WorkingDirectory = "S:\GESTIONALE"
oMyShortcut3.Save

Qualora voleste eliminare un link già presente, lo script andrebbe modificato anteponendo le seguenti righe:

IF objFSO.FileExists(strDesktop& "\nomecollegamento.lnk") THEN
	objFSO.DeleteFile(strDesktop& "\nomecollegamento.lnk")
End If

Come vedere rapidamente le dimensioni in GB delle cassetta postali di Exchange con la EMS

Find username Avete la necessità di controllare le dimensioni della casella postale di uno o più utenti in modo rapido nel vostro Exchange?

Potete usare la EMS (Exchange Management Shell)!

Ecco come fare:

$Totale=0;(get-mailbox)| where-object {$_.LinkedMasterAccount -ne "NT AUTHORITY\SELF"}| select-object -property @{Name="Utente";Expression={$_.Name}},@{Name="GB";Expression = {"{0:N2}" -f ((get-mailbox $_.Alias|Get-MailboxStatistics).Totalitemsize.value.tomb()/1024)}},@{Name="Limite";Expression={$_.ProhibitSendReceiveQuota}} | sort-object GB -Descending;(get-mailbox)| % { $Totale+=((get-mailbox $_.Alias|Get-MailboxStatistics).Totalitemsize.value.tomb()/1024)};write-host ;write-host "Totale cassette (in GB):"([math]::Round($Totale))

Questo il risultato:

Utente          GB          Limite
------          --          ------
Valerio         9,52         12GB
Antonio         5,41          6GB
Leonardo        4,92          6GB
Emanuele        3,52          5GB
Salvatore       2,59          8GB

Totale cassette (in GB): 25,96

Lanciare una sessione di desktop remoto senza pulsante Start

Find username

Vorrestre lanciare una sessione di desktop remoto su di un server senza consentire all’utente di usare il pulsante Start?

Si può fare!

Ecco come:

Basta “killare” il processo Explorer dell’utente che accede ed egli non potrà più usare il pulsante start e i menu vari. Si potrà poi lanciare l’eseguibile del programma che volete far utilizzare all’utente remoto.

Ecco lo script di logon da lanciare in fase di accesso:

FOR /F "tokens=2" %%i IN ('tasklist.exe /FI "IMAGENAME eq explorer.exe" /FI "Username eq nome_dell_utente"^|findstr "exp"') DO taskkill /PID %%i /f
Nome-dell-Eseguibile-che-deve-essere-lanciato
logoff

Trovare il numero della settimana corrente con powershell

WeekNumber

In uno script vi serve il numero della settimana corrente per svolgere una determinata azione una settimana sì ed una no?

Usate Powershell!

Spesso capita di voler svolgere una determinata azione a seconda che il numero della settimana sia pari o dispari, ad esempio voglio fare una copia di alcuni files una settimana in un disco e una settimana in un altro.
In soccorso arriva Powershell. Con esso possiamo stabilire il numero della settimana corrente e di conseguenza capire se è pari o dispari, per poi disporre un’azione da eseguire.

Ad esempio volete lanciare un programma se la settimana corrente è dispari:

if((get-date -uformat %W)% 2 -eq 0) 
       {write "Pari. Non faccio niente!"
       } 
    else 
       {write "Dispari. Procedo con le azioni previste..."
        ...azione da eseguire
       } 

Oppure voglio connettere una LUN iScsi per le settimane pari ed un’altra per le settimane dispari:

write Disconnetto tutte le sessioni iScsi...
(iscsicli reporttargetmappings|findstr /i "sess").substring(30,33)| foreach-object -process {invoke-command{iscsicli logouttarget $_}}
if((get-date -uformat %W)% 2 -eq 0) 
       {write "Settimana pari. Attivo la LUN pari"
	iscsicli qlogintarget iqn.1992-04.com.emc:storage.LUN-PARI
       } 
    else 
       {write "Settimana dispari. Attivo la LUN dispari"
	iscsicli qlogintarget iqn.1992-04.com.emc:storage.LUN-DISP
       } 

Come tracciare i messaggi inviati/spediti tramite Exchange 2007/2010/2013

Track Exchange message

Come e’ possibile tracciare i messaggi inviati da e verso un server Exchange?

Con la EMS (Exchange Management Shell)!

Ecco come fare…

Per verificare i messaggi che escono da un server Exchange in un determinato range di date/ora è possibile usare la seguente sintassi nella Exchange Management Console:

get-messagetrackinglog -EventID "SEND" -Start "12/18/2013 00:01:00" -End "12/18/2013 16:11:00"| ConvertTo-Html -as Table -property Timestamp, Sender, MessageSubject, RecipientCount > ReportMail.html; ii ReportMail.html
get-messagetrackinglog -EventID "SEND" -Start "12/18/2013 00:01:00" -End "12/18/2013 16:11:00"| where-object {$_.Sender -eq "EmailDelMittente"} | ConvertTo-Html -as Table -property Timestamp, Sender, MessageSubject, RecipientCount > ReportMail.html; ii ReportMail.html

Il tipo di evento “SEND” può essere sostituito con “RECEIVE” in questo modo:

get-messagetrackinglog -EventID "RECEIVE" -Start "12/18/2013 14:31:00" -End "12/18/2013 16:11:00" | select Timestamp, Sender, {$_.Recipients}, MessageSubject, RecipientCount | ConvertTo-Html -as table > ReportMail.html; ii ReportMail.html

Ad esempio, per verificare le e-mail ricevute da un proprio utente:

get-messagetrackinglog -EventID "RECEIVE" -Start "12/18/2013 14:31:00" -End "12/18/2013 16:11:00" | where-object {$_.Recipients -like "*EmailDelDestinatarioInterno*"} | select Timestamp, Sender, {$_.Recipients}, MessageSubject, RecipientCount | ConvertTo-Html -as table > ReportMail.html; ii ReportMail.html

Mentre per controllare le e-mail spedite da nomeutente@gmail.com a mioutente@miodominio.it:

get-messagetrackinglog -EventID "RECEIVE" -Start "12/18/2013 14:31:00" -End "12/18/2013 16:11:00" | where-object {$_.Sender -eq "nomeutente@gmail.com" -and $_.Recipients -like "*mioutente@miodominio.it*"} | select Timestamp, Sender, {$_.Recipients}, MessageSubject, RecipientCount | ConvertTo-Html -as table > ReportMail18122013.html; ii ReportMail18122013.html

Volendo è possibile aggiungere un foglio CSS con il codice seguente:
(inserire il parametro -CssUri nomefile.css

table {
width: 100%;
color: #333;
font-family: Helvetica, Arial, sans-serif;
width: 640px;
border-collapse: collapse;
border-spacing: 0;
} 
td th {
border: 1px solid #CCC;
height: 60px;
}
th {
background: #F3F3F3;
font-weight: bold;
border: 1px solid #7F7F7F;
}
td {
background: #FAFAFA;
text-align: center;
font-size:12px;
border: 1px solid #7F7F7F;
}

Esempio
Voglio un file HTML per verificare tutte le email spedite ad utenti Gmail nel mese di Dicembre del 2013

get-messagetrackinglog -EventID "SEND" -Start "12/01/2013 00:00:00" -End "12/31/2013 23:59:59" |where-object {$_.Recipients -like "*gmail.com*"} | select @{Expression={$_.Timestamp};Label="Data/Ora"}, @{Expression={$_.Sender};Label="Mittente"}, @{Expression={$_.Recipients};Label="Destinatari"}, @{Expression={$_.MessageSubject};Label="Oggetto"}, @{Expression={$_.RecipientCount};Label="Numero destinatari"} | ConvertTo-html -cssuri "table.css" > ReportMail.html ; ii .\ReportMail.html

Voglio che mi venga spedito un file HTML allegato ad un email contenente tutte i messaggi ricevuti da un utente del mio dominio nelle ultime 24 ore

$allegato= $env:temp +'\Messaggi_' + (get-date).day + '-' + (get-date).month + '-' + (get-date).year +  '.html'
get-messagetrackinglog -EventID "RECEIVE" -Start (Get-Date).AddHours(-24) | where {$_.Recipients -like "*utente@dominio.com*"}| select Timestamp, Sender, MessageSubject | ConvertTo-Html -as table > $allegato; Send-MailMessage -to "destinatario-rapporto-mail@dominio.it" -from "postmaster@dominio.it"  -Subject ('Report mesaggi del ' + (get-date).day + '-' + (get-date).month + '-' + (get-date).year) -Attachments "$allegato" -
SmtpServer 127.0.0.1

Se invece volete esportare su Excel le email spedite nelle ultime 24 ore:

get-messagetrackinglog -EventID "SEND" -Start (get-date).AddHours(-24) |where-object {$_.Sender -like "*EmailDelMittente*"} | select @{Expression={$_.Timestamp};Label="Data/Ora"}, @{Expression={$_.Sender};Label="Mittente"}, @{Expression={$_.Recipients};Label="Destinatari"}, @{Expression={$_.MessageSubject};Label="Oggetto"}, @{Expression={$_.RecipientCount};Label="Numero destinatari"} | ConvertTo-CSV -delimiter "`t" > ReportMail.csv ; ii .\ReportMail.csv

ATTENZIONE
nel caso riceviate il seguente errore

Get-MessageTrackingLog : Impossibile associare il parametro 'Start'. Impossibile convertire il valore "12/18/2013 14:31:00" nel tipo "System.DateTime". Errore: "Stringa non riconosciuta come valore DateTime valido." In riga:1 car:49

Bisognerà invertire il mese ed il giorno nelle date!

Come sapere chi è loggato ad un PC di un dominio?

Find usernameVolete sapere su un PC della rete chi si è loggato ma non sapete come fare?

Potete usare un batch con un comando WMI.

Ecco come fare:

 
 

Create questo script che accetti come parametro l’indirizzo IP o il nome del computer:

@echo off
for /F "tokens=1 delims= " %%i in ('WMIC /node:%1 ComputerSystem Get UserName 2^>^&1 ^| find /i "\"') do set NOME=%%i
IF "%NOME%"=="" (echo Non e' possibile recuperare il valore richiesto per l'IP %1.) ELSE (echo L'utente connesso a %1 e' %NOME%)
SET NOME=

 
Ad esempio il risultato del comando “c:\temp\CercaUtenteLoggato.bat 192.168.100.221” sarà:

L'utente connesso a 192.168.100.221 e' DOMINIO\vincenzoconvertito