Table of Contents

aggiornamento di powershell a command line

iex "& { $(irm https://aka.ms/install-powershell.ps1) } -UseMSI"

Group with admincount=1 (protected group)

un utente appartenente ad un protected groups eredita i permessi di sicurezza dal gruppo AdminSDHolder presente in system


per capire quali sono i gruppi di tipo protected groups è necessario verificare il valore dell'attributo adminCount

Get-ADGroup -LDAPFilter "(admincount=1)"

ricava le utenze attive con una certa mail

Get-ADUser -Properties * -filter 'mail -like "*davidedoro.it"' |where {$_.enabled -eq "True"} | select  mail, GivenName,  Surname

Comandi Powershell Utili

Powerfull Active directory command:
how to change displayname, distinguishedname, and setting an attribute (title for example) with given email address

Displayname:

Get-ADUser -Filter {Emailaddress -eq 'davide@davidedoro.it' } | % {Set-ADUser $_ -DisplayName ('Davide Doro')}

DistinguishedName:

Get-ADUser -Filter {Emailaddress -eq 'davide@davidedoro.it' } | % {Rename-ADObject $_.DistinguishedName -NewName 'Davide Doro'}

Title:

Get-ADUser -Filter {Emailaddress -eq 'davide@davidedoro.it' } | % {Set-ADUser $_ -Title ('Director')}

TaskScheduler

get task per user:

schtasks.exe /query /V /FO CSV | ConvertFrom-Csv|Where {$_."Run As User" -eq "domain\user" }
schtasks.exe /query /V /FO CSV | ConvertFrom-Csv|Where {$_.'Scheduled Task State' -ne "Enabled" -and $_."Run As User" -eq "domain\user" } |select taskname

Exchange

stato database

Get-MailboxDatabase  -status |select Name,DatabaseSize,availablenewmailboxspace

verifica mailbox su un dato database:

Get-Mailbox |where {$_.Database -eq "Mailbox Database X"} |select name,alias,archivedatabase,servername
Get-Mailbox |where {$_.ArchiveDatabase -eq "Mailbox Archive X"} |select name,alias,archivedatabase,servername
Get-Mailbox | where {$_.PrimarySmtpAddress -like "*dominio.net"} |select * | Out-String -Stream | Select-String archivedatabase

export mailbox

Get-MailboxExportRequest -Mailbox nomemailbox | select Mailbox,Status

mailbox statistics

Get-MailboxFolderStatistics -identity aaaa |select  identity

verifica archivio

Get-Mailbox -identity aaaa | where {$_.ArchiveDatabase -ne $null} |Get-MailboxStatistics -archive | select-object * 

Export su pst collegato a delle date

New-MailboxExportRequest -ContentFilter {(Received -lt '04/01/2010') -and (Received -gt '03/01/2010')} -Mailbox "aaaa" -Name name aaaa  -FilePath \\ExServer1\Imports\aaaa.pst

Con il deletecontent per cancellare

Search-Mailbox -Identity  -SearchQuery '(Received:07/20/2015..08/12/2015)' -deletecontent

aggiungi il permesso send as ad un utente per un gruppo

Get-DistributionGroup "Group" | Add-ADPermission -User "User" -ExtendedRights "Send As"

ed anche send on behalf

Set-DistributionGroup -Identity "Group" -GrantSendOnBehalfTo "User"

verifica dello spazio ripristinabile: ed eliminare col comando 2

Search-Mailbox -identity utente -SearchDumpsterOnly -LogOnly -targetFolder Bozze -TargetMailbox utente2
Search-Mailbox -identity utente -SearchDumpsterOnly -DeleteContent

archivio in pst le mail in dumpster dell'archivio online enon

New-MailboxExportRequest -Mailbox mailname -name name-process -isarchive -FilePath \\nas\\backup\Dumpster-arc.pst -IncludeFolder "#Recoverable Items/Deletions#"
New-MailboxExportRequest -Mailbox mailname -name name-process -FilePath \\nas\\backup\Dumpster.pst -IncludeFolder "#Recoverable Items/Deletions#"

verifica spazio di archiviazione filtrando per db exchange

C:\Windows\system32>Get-Mailbox |where {$_.ArchiveDatabase -eq "Mailbox Archive 1"} | Get-MailboxStatistics -Archive | ft displayname,totaldeleteditemsize,totalitemsize

Esporto tutti gli indirizzi email configurati nell'azienda

Get-Recipient | Select Name -ExpandProperty EmailAddresses | Select Name, SmtpAddress | Export-csv C:\temp\AllEmailAddress.csv

esporto tutti gli indirizzi di posta configurati sui distribution group

Get-DistributionGroup |select samaccountname,EmailAddresses | Format-Table -Wrap -AutoSize |export-csv C:\temp\distributiongroup.csv

exchange autorseponse for an ex-employee

Set-MailboxAutoReplyConfiguration -Identity utente -AutoReplyState Scheduled -StartTime "19/07/2021" -EndTime "31/07/2021 23:00:00" -External Message "Sarò assente fino al 31.07, Vi prego di inoltrare la mail al seguente indirizzo aaa"

Comandi Utili

start di un servizio da remoto

sc.exe \\serverA start serviceName

verificare i servizi:

 sc.exe \\serverA query
 or 
 sc.exe \\serverA query serviceName

Script To zip files inside directory older then:

$dir = "C:\dir"
$scriptDir = "c:\scripts"
$logfile = "zippaoldfiles.log"
$LastWrite = (get-date).AddDays(-60)
$LastWrite

$Files = Get-ChildItem -path $dir -Filter "*.txt" -File | Where-Object {$_.LastWriteTime -le $LastWrite}
$files

ForEach ($File in $Files) {
    C:\'Program Files (x86)'\GnuWin32\bin\gzip.exe $dir\$file 
}

___

Powershell Execution Policy

#create self sign certificate to sign scripts

$authenticode = New-SelfSignedCertificate -Subject "ATA Authenticode" -CertStoreLocation Cert:\LocalMachine\My -Type CodeSigningCert

# Add the self-signed Authenticode certificate to the computer's root certificate store. ## Create an object to represent the LocalMachine\Root certificate store.

$rootStore = [System.Security.Cryptography.X509Certificates.X509Store]::new("Root","LocalMachine")

## Open the root certificate store for reading and writing.

$rootStore.Open("ReadWrite")

## Add the certificate stored in the $authenticode variable.

$rootStore.Add($authenticode)

## Close the root certificate store.

$rootStore.Close()

# Add the self-signed Authenticode certificate to the computer's trusted publishers certificate store. ## Create an object to represent the LocalMachine\TrustedPublisher certificate store.

$publisherStore = [System.Security.Cryptography.X509Certificates.X509Store]::new("TrustedPublisher","LocalMachine")

## Open the TrustedPublisher certificate store for reading and writing.

$publisherStore.Open("ReadWrite")

## Add the certificate stored in the $authenticode variable.

$publisherStore.Add($authenticode)

## Close the TrustedPublisher certificate store.

$publisherStore.Close()
Get-ChildItem Cert:\LocalMachine\My | Where-Object {$_.Subject -eq "CN=ATA Authenticode"}

# Confirm if the self-signed Authenticode certificate exists in the computer's Root certificate store

Get-ChildItem Cert:\LocalMachine\Root | Where-Object {$_.Subject -eq "CN=ATA Authenticode"}

# Confirm if the self-signed Authenticode certificate exists in the computer's Trusted Publishers certificate store

Get-ChildItem Cert:\LocalMachine\TrustedPublisher | Where-Object {$_.Subject -eq "CN=ATA Authenticode"}
$codeCertificate = Get-ChildItem Cert:\LocalMachine\My | Where-Object {$_.Subject -eq "CN=ATA Authenticode"}

# Sign the PowerShell script # PARAMETERS: # FilePath - Specifies the file path of the PowerShell script to sign, eg. C:\ATA\myscript.ps1. # Certificate - Specifies the certificate to use when signing the script. # TimeStampServer - Specifies the trusted timestamp server that adds a timestamp to your script's digital signature. Adding a timestamp ensures that your code will not expire when the signing certificate expires.

Set-AuthenticodeSignature -FilePath C:\job\repo\scripts\script.ps1 -Certificate $codeCertificate
Get-ExecutionPolicy
Set-ExecutionPolicy AllSigned

aggiornare Certificato Exchange

per la rimozione del vecchio certificato è necessario aprire lo snapin da mmc e rimuoverlo da la (certificati server)

  1. creare il certificato (anche wildcard)
  2. convertirlo in pfx con password
  3. da powershell su exchange Get-ExchangeCertificate
  4. copiare il thumbprint collegato al certificato da installare
  5. Enable-ExchangeCertificate -Thumbprint 4975AE7A253AF247AC42BC46316CDF558E26FEAB -services “IMAP,POP,SMTP”
  6. restart trasnport service