Rechercher dans ce blog

lundi 3 juin 2024

Powershell : Récupére les sessions ouvertes a distance

 


Function Get-Session($HostName)

{

    $Computer = query session /server:$HostName

    $UserSession = ($Computer -replace "\s+", ";") | ConvertFrom-Csv -Delimiter ";" -Header "HOSTNAME", "SESSIONNAME", "USERNAME", "ID", "STATE", "TYPE", "DEVICE"

    $UserSession | % {$_.HOSTNAME = $HostName}

    $UserSession = $UserSession | ? {$_.STATE -eq "Actif"}

    Return $UserSession

}


Get-Session NomDeLaMachine

mardi 28 mai 2024

Powershell : Cryptage et décryptage simple d'un mot de passe


  1. Faire la génération d'une clef ($Key) depuis un site qui est capable de générer des mots de passe complex et remplacer la valeur de $Key

  2. Jouer le script une fois pour pouvoir utiliser les "function"
  3. Lancer la commande "Mask -Message MonMotDePasse", vous deviez avoir un retour avec une chaine complement crypté, copier cette chaine
  4. Utiliser cette chaine crypté dans votre code en ajoutant que la partie $key et UnMask


Add-Type -AssemblyName System.Security


$key = "c!LL!hm&&A##oaQ/-G4x+#TBzS!!tzCT#k!rs9NNz"


Function Mask($Message)

{

    $encryptedBytes = [System.Security.Cryptography.ProtectedData]::Protect([System.Text.Encoding]::UTF8.GetBytes($Message), [System.Text.Encoding]::UTF8.GetBytes($key), [System.Security.Cryptography.DataProtectionScope]::CurrentUser)

    $encrypted = [Convert]::ToBase64String($encryptedBytes)


    Return $encrypted

}


Function UnMask($Message)

{

    $decryptedBytes = [System.Security.Cryptography.ProtectedData]::Unprotect([Convert]::FromBase64String($Message), [System.Text.Encoding]::UTF8.GetBytes($key), [System.Security.Cryptography.DataProtectionScope]::CurrentUser)   

    $decrypted = [System.Text.Encoding]::UTF8.GetString($decryptedBytes)

    Return $decrypted

}

vendredi 10 février 2023

Alarme évènements sur un écran - Mode télé travail

Update 10/02/2023

--------------------------------------------------


$i = 0

$PathPicture = "C:\..........\..........\imagesscreen"

New-Item $PathPicture -ItemType Directory -ErrorAction SilentlyContinue


Remove-Item "$($PathPicture)\*.*" -Force -Recurse


sleep -Seconds 5


do {

    sleep -Seconds 1

    $i++

    $File = "$($PathPicture)\Image$($i).bmp"


    Add-Type -AssemblyName System.Windows.Forms

    Add-type -AssemblyName System.Drawing



    $Screen = [System.Windows.Forms.SystemInformation]::VirtualScreen

    $Width = [System.Windows.Forms.SystemInformation]::PrimaryMonitorSize.Width

    $Height = [System.Windows.Forms.SystemInformation]::PrimaryMonitorSize.Height


    $Left = 0

    $Top = 0


    ($bitmap = New-Object System.Drawing.Bitmap $Width, ($Height-40))  | Out-Null

    ($graphic = [System.Drawing.Graphics]::FromImage($bitmap)) | Out-Null


    ($graphic.CopyFromScreen($Left, $Top, 0, 0, $bitmap.Size))  | Out-Null

    $bitmap.Save($File) | Out-Null


    $CountPicture = (Get-ChildItem "$($PathPicture)\Image*.*").Count


    If($CountPicture -ge 2)

    {

        $Picture1 = Get-ChildItem "$($PathPicture)\Image$($i).bmp"

        $Picture2 = Get-ChildItem "$($PathPicture)\Image$($i-1).bmp"

    }

    else

    {

        Continue

    }

    $f1 = Get-FileHash -Path $Picture1
    $f2 = Get-FileHash -Path $Picture2


    Write-Host "$($Picture2.Name) : $($f2.Hash)"
    Write-Host "$($Picture1.Name) : $($f1.Hash)"


    if($f1.Hash -ne $f2.Hash)
   {

        Write-Host "PlaySound" -ForegroundColor Yellow

        $PlayWav = New-Object System.Media.SoundPlayer

        $PlayWav.SoundLocation = "C:\Windows\Media\Alarm01.wav"

        $PlayWav.playsync()


        #& "C:\Program Files\VideoLAN\VLC\vlc.exe" --play-and-exit '"C:\Windows\Media\Alarm01.wav"'


        sleep -Seconds 10


        # (New-Object Media.SoundPlayer 'C:\Windows\Media\Afternoon\Windows Notify.wav').Play();

    }


    Remove-Item $Picture2 -Force 

} while (

    $true

)

mercredi 6 juillet 2022

Maintenir l'écran allumé - mode télétravail

 Il faudra faire un changement de valeur $Push si trop long (en secondes)



$wshell = New-Object -ComObject wscript.shell


[int]$Push = 300

Do

{

    $wshell.SendKeys('^')

    Write-Host "$(Get-Date) : Push CTRL"

    

    start-sleep $Push

    #Write-host  "$([int]$Push - [Int]$i )"


} While ($p -ne 'n') 

mercredi 6 février 2019

Get PasswordRecovery Bitlocker (msFVE-RecoveryInformation, msfve-recoverypassword) without Import-Module ActiveDirectory





Extract All KeysRecovery in ActiveDirectory


$strFilter = "(&(objectcategory=msFVE-RecoveryInformation))"
$ldap = "LDAP://DC=xx,DC=xxx,DC=xx"
$objDomain = New-Object System.DirectoryServices.DirectoryEntry $ldap
$objSearcher = New-Object System.DirectoryServices.DirectorySearcher
$objSearcher.SearchRoot = $objDomain
$objSearcher.PageSize = 10000
$objSearcher.Filter = $strFilter.Trim()
$objSearcher.SearchScope = "Subtree"
$colResults = $objSearcher.FindAll()

[array]$Resultat = $colResults

$ComputerNameRecoveryPassword = @()

foreach ($objResult in $Resultat)
{
    $ComputerName = $objResult.Path.Split(",")[1].Replace("CN=", "")
    $RecoveryPassword = $objResult.Properties.'msfve-recoverypassword'
    $whencreated = $objResult.Properties.whencreated

    $Object = New-Object PSObject
    $Object | add-member Noteproperty ComputerName           $ComputerName
    $Object | add-member Noteproperty RecoveryPassword       $RecoveryPassword
    $Object | add-member Noteproperty whencreated            $whencreated
    $ComputerNameRecoveryPassword += $Object
}

$ComputerNameRecoveryPassword | Sort-Object -Property ComputerName


Extract for one computer (start local with adm account)


$ComputerName = $env:COMPUTERNAME
$strFilter = "(&(objectclass=computer)(cn= $ComputerName))"
#$strFilter = "(&(objectcategory=msFVE-RecoveryInformation))"
$ldap = "LDAP://DC=xx,DC=xx,DC=xx"
$objDomain = New-Object System.DirectoryServices.DirectoryEntry $ldap
$objSearcher = New-Object System.DirectoryServices.DirectorySearcher
$objSearcher.SearchRoot = $objDomain
$objSearcher.PageSize = 10000
$objSearcher.Filter = $strFilter.Trim()
$objSearcher.SearchScope = "Subtree"
$colResultsComputer = $objSearcher.FindOne()

$strFilter = "(&(objectcategory=msFVE-RecoveryInformation))"
$ldap = $colResultsComputer.Path
$objDomain2 = New-Object System.DirectoryServices.DirectoryEntry $ldap
$objSearcher = New-Object System.DirectoryServices.DirectorySearcher
$objSearcher.SearchRoot = $objDomain2
$objSearcher.PageSize = 10000
$objSearcher.Filter = $strFilter.Trim()
$objSearcher.SearchScope = "Subtree"
$colResults = $objSearcher.FindOne()



[array]$Resultat = $colResults

$ComputerNameRecoveryPassword = @()

foreach ($objResult in $Resultat)
{
    $ComputerName = $objResult.Path.Split(",")[1].Replace("CN=", "")
    $RecoveryPassword = $objResult.Properties.'msfve-recoverypassword'
    $whencreated = $objResult.Properties.whencreated

    $Object = New-Object PSObject
    $Object | add-member Noteproperty ComputerName           $ComputerName
    $Object | add-member Noteproperty RecoveryPassword       $RecoveryPassword
    $Object | add-member Noteproperty whencreated            $whencreated
    $ComputerNameRecoveryPassword += $Object
}

$ComputerNameRecoveryPassword | Sort-Object -Property ComputerName




mardi 25 septembre 2018

Récupère la description des drivers en erreur








Function DeviceManagerErrorMessage($ConfigManagerErrorCode)
{
    Switch($ConfigManagerErrorCode)
    {
        # https://docs.microsoft.com/en-us/windows-hardware/drivers/install/cm-prob-will-be-removed
        CM_PROB_NOT_CONFIGURED {"This device is not configured correctly. (Code 1)"}
        CM_PROB_OUT_OF_MEMORY {"The driver for this device might be corrupted, or your system may be running low on memory or other resources. (Code 3)"}
        CM_PROB_INVALID_DATA {"Windows cannot identify this hardware because it does not have a valid hardware identification number. (Code 9)"}
        CM_PROB_FAILED_START {"This device cannot start. (Code 10)"}
        CM_PROB_NORMAL_CONFLICT {"This device cannot find enough free resources that it can use. (Code 12)"}
        CM_PROB_NEED_RESTART {"This device cannot work properly until you restart your computer. (Code 14)"}
        CM_PROB_PARTIAL_LOG_CONF{"Windows cannot identify all the resources this device uses. (Code 16)"}
        CM_PROB_REINSTALL {"Reinstall the drivers for this device. (Code 18)"}
        CM_PROB_REGISTRY {"Windows cannot start this hardware device because its configuration information (in the registry) is incomplete or damaged. (Code 19)"}
        CM_PROB_WILL_BE_REMOVED {"Windows is removing this device. (Code 21)"}
        CM_PROB_DISABLED {"This device is disabled. (Code 22)"}
        CM_PROB_DEVICE_NOT_THERE {"This device is not present, is not working properly, or does not have all its drivers installed. (Code 24)"}
        CM_PROB_FAILED_INSTALL {"The drivers for this device are not installed. (Code 28)"}
        CM_PROB_HARDWARE_DISABLED {"This device is disabled because the firmware of the device did not give it the required resources. (Code 29)"}
        CM_PROB_FAILED_ADD {"This device is not working properly because Windows cannot load the drivers required for this device. (Code 31)"}
        CM_PROB_DISABLED_SERVICE {"A driver (service) for this device has been disabled. An alternate driver may be providing this functionality. (Code 32)"}
        CM_PROB_TRANSLATION_FAILED {"Windows cannot determine which resources are required for this device. (Code 33)"}
        CM_PROB_NO_SOFTCONFIG {"Windows cannot determine the settings for this device. Consult the documentation that came with this device and use the Resource tab to set the configuration. (Code 34)"}
        CM_PROB_BIOS_TABLE {"Your computer's system firmware does not include enough information to properly configure and use this device. To use this device, contact your computer manufacturer to obtain a firmware or BIOS update. (Code 35)"}
        CM_PROB_IRQ_TRANSLATION_FAILED {"This device is requesting a PCI interrupt but is configured for an ISA interrupt (or vice versa). Please use the computer's system setup program to reconfigure the interrupt for this device. (Code 36)"}
        CM_PROB_FAILED_DRIVER_ENTRY {"Windows cannot initialize the device driver for this hardware. (Code 37)"}
        CM_PROB_DRIVER_FAILED_PRIOR_UNLOAD {"Windows cannot load the device driver for this hardware because a previous instance of the device driver is still in memory. (Code 38)"}
        CM_PROB_DRIVER_FAILED_LOAD {"Windows cannot load the device driver for this hardware. The driver may be corrupted or missing. (Code 39)"}
        CM_PROB_DRIVER_SERVICE_KEY_INVALID {"Windows cannot access this hardware because its service key information in the registry is missing or recorded incorrectly. (Code 40)"}
        CM_PROB_LEGACY_SERVICE_NO_DEVICES {"Windows successfully loaded the device driver for this hardware but cannot find the hardware device. (Code 41)"}
        CM_PROB_DUPLICATE_DEVICE {"Windows cannot load the device driver for this hardware because there is a duplicate device already running in the system. (Code 42)"}
        CM_PROB_FAILED_POST_START {"Windows has stopped this device because it has reported problems. (Code 43)"}
        CM_PROB_HALTED {"An application or service has shut down this hardware device. (Code 44)"}
        CM_PROB_PHANTOM {"Currently, this hardware device is not connected to the computer. (Code 45)"}
        CM_PROB_SYSTEM_SHUTDOWN {"Windows cannot gain access to this hardware device because the operating system is in the process of shutting down. (Code 46)"}
        CM_PROB_HELD_FOR_EJECT {"Windows cannot use this hardware device because it has been prepared for 'safe removal', but it has not been removed from the computer. (Code 47)"}
        CM_PROB_DRIVER_BLOCKED {"The software for this device has been blocked from starting because it is known to have problems with Windows. Contact the hardware vendor for a new driver. (Code 48)"}
        CM_PROB_REGISTRY_TOO_LARGE {"Windows cannot start new hardware devices because the system hive is too large (exceeds the Registry Size Limit). (Code 49)"}
        CM_PROB_SETPROPERTIES_FAILED {"Windows cannot apply all of the properties for this device. Device properties may include information that describes the device's capabilities and settings (such as security settings for example). (Code 50)"}
        CM_PROB_WAITING_ON_DEPENDENCY {"This device is currently waiting on another device or set of devices to start. (Code 51)."}
        CM_PROB_UNSIGNED_DRIVER {"Windows cannot verify the digital signature for the drivers required for this device. A recent hardware or software change might have installed a file that is signed incorrectly or damaged, or that might be malicious software from an unknown source. (Code 52)"}
        CM_PROB_USED_BY_DEBUGGER {"This device has been reserved for use by the Windows kernel debugger for the duration of this boot session. (Code 53)"}
        CM_PROB_DEVICE_RESET {"This device has failed and is undergoing a reset. (Code 54)"}
    }
}


$VerifDriver = Get-PnpDevice -Status ERROR | select *

if($VerifDriver.count -gt 0){
    Foreach($itemDrive in $VerifDriver)
    {
        $OutDrivers = "Clavier standard PS/2", "Bluetooth PAN Network Adapter"
        $itemDrive  | ? {$OutDrivers.Contains($_.Name); continue}
        "$($itemDrive.Name) ----> $(DeviceManagerErrorMessage -ConfigManagerErrorCode ($itemDrive.ConfigManagerErrorCode))"
    }
}
else
{
        "Aucun driver sen erreur"
}




jeudi 5 avril 2018

WinRM, Enable service, Start, and connect remote on the system Windows 7





$computer = "xxxxxxxxxx"
Set-Service winrm -ComputerName $computer -StartupType Automatic
get-service -ComputerName $computer -Name winrm | Start-Service
Invoke-WmiMethod -Class Win32_Process -Name create -ArgumentList "powershell.exe enable-psremoting -force" -ComputerName $computer
Invoke-WmiMethod -Class Win32_Process -Name create -ArgumentList "powershell.exe set-executionpolicy RemoteSigned -force" -ComputerName $computer
sleep -Seconds 30
Enter-PSSession -ComputerName $computer