{"id":394172,"date":"2024-12-17T08:10:17","date_gmt":"2024-12-17T08:10:17","guid":{"rendered":"https:\/\/www.ninjaone.com\/?post_type=script_hub&#038;p=394172"},"modified":"2024-12-17T08:10:17","modified_gmt":"2024-12-17T08:10:17","slug":"derniere-connexion-ad-powershell","status":"publish","type":"script_hub","link":"https:\/\/www.ninjaone.com\/fr\/script-hub\/derniere-connexion-ad-powershell\/","title":{"rendered":"D\u00e9verrouiller les informations sur Active Directory avec PowerShell\u00a0: r\u00e9cup\u00e9ration des donn\u00e9es de la derni\u00e8re connexion pour les ordinateurs AD\u00a0"},"content":{"rendered":"<h2>Introduction<\/h2>\n<p>Il est essentiel de savoir quand les appareils se sont connect\u00e9s pour la derni\u00e8re fois \u00e0 <a href=\"https:\/\/www.ninjaone.com\/it-hub\/endpoint-management\/what-is-active-directory\/\">Active Directory (AD)<\/a> pour maintenir un environnement informatique s\u00e9curis\u00e9 et bien g\u00e9r\u00e9. Les syst\u00e8mes dormants ou rarement utilis\u00e9s peuvent pr\u00e9senter des risques, tels que des terminaux non autoris\u00e9s ou des inefficacit\u00e9s dans l&rsquo;allocation des ressources. Le script <a href=\"https:\/\/www.ninjaone.com\/it-hub\/endpoint-management\/what-is-powershell\/\">PowerShell<\/a> fourni propose une solution efficace aux administrateurs informatiques et aux <a href=\"https:\/\/www.ninjaone.com\/what-is-an-msp\/\">fournisseurs de services g\u00e9r\u00e9s (MSP)<\/a> afin de r\u00e9cup\u00e9rer et d&rsquo;analyser efficacement les derni\u00e8res donn\u00e9es de connexion pour tous les ordinateurs de leur environnement AD.<\/p>\n<h2>Contexte<\/h2>\n<p>Active Directory est la cl\u00e9 de vo\u00fbte de la gestion des utilisateurs et des appareils dans de nombreux environnements d&rsquo;entreprise. Le suivi de l&rsquo;horodatage de la derni\u00e8re connexion des ordinateurs est essentiel pour l&rsquo;audit, la conformit\u00e9 et le maintien d&rsquo;un r\u00e9pertoire propre. Ce script simplifie le processus traditionnellement lourd de collecte de ces donn\u00e9es en exploitant les capacit\u00e9s d&rsquo;automatisation de PowerShell et en s&rsquo;int\u00e9grant \u00e0 des outils tels que NinjaOne pour des fonctionnalit\u00e9s \u00e9tendues. Il ne se contente pas de r\u00e9cup\u00e9rer les horodatages de la derni\u00e8re connexion, mais propose \u00e9galement des options permettant d&rsquo;interroger d&rsquo;autres donn\u00e9es sur les utilisateurs et de visualiser les r\u00e9sultats dans un format personnalisable.<\/p>\n<h2>Le script\u00a0:<\/h2>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"powershell\">#Requires -Version 5.1\r\n\r\n&lt;#\r\n.SYNOPSIS\r\n    Gets the last login time for all computers in Active Directory.\r\n.DESCRIPTION\r\n    Gets the last login time for all computers in Active Directory.\r\n    The last login time is retrieved from the LastLogonTimeStamp property of the computer object.\r\n    If the user name cannot be retrieved from an offline computer, the script will return Unknown.\r\n    If the computer name cannot be retrieved, the script will return Unknown.\r\n\r\n    By using this script, you indicate your acceptance of the following legal terms as well as our Terms of Use at https:\/\/www.ninjaone.com\/terms-of-use.\r\n    Ownership Rights: NinjaOne owns and will continue to own all right, title, and interest in and to the script (including the copyright). NinjaOne is giving you a limited license to use the script in accordance with these legal terms. \r\n    Use Limitation: You may only use the script for your legitimate personal or internal business purposes, and you may not share the script with another party. \r\n    Republication Prohibition: Under no circumstances are you permitted to re-publish the script in any script library or website belonging to or under the control of any other software provider. \r\n    Warranty Disclaimer: The script is provided \u201cas is\u201d and \u201cas available\u201d, without warranty of any kind. NinjaOne makes no promise or guarantee that the script will be free from defects or that it will meet your specific needs or expectations. \r\n    Assumption of Risk: Your use of the script is at your own risk. You acknowledge that there are certain inherent risks in using the script, and you understand and assume each of those risks. \r\n    Waiver and Release: You will not hold NinjaOne responsible for any adverse or unintended consequences resulting from your use of the script, and you waive any legal or equitable rights or remedies you may have against NinjaOne relating to your use of the script. \r\n    EULA: If you are a NinjaOne customer, your use of the script is subject to the End User License Agreement applicable to you (EULA).\r\n\r\n.EXAMPLE\r\n    (No Parameters)\r\n    ## EXAMPLE OUTPUT WITHOUT PARAMS ##\r\n\r\nPARAMETER: -WysiwygCustomField \"myWysiwygCustomField\"\r\n    Saves results to a WYSIWYG Custom Field.\r\n.EXAMPLE\r\n    -WysiwygCustomField \"myWysiwygCustomField\"\r\n    ## EXAMPLE OUTPUT WITH WysiwygCustomField ##\r\n    [Info] Found 10 computers.\r\n    [Info] Attempting to set Custom Field 'myWysiwygCustomField'.\r\n    [Info] Successfully set Custom Field 'myWysiwygCustomField'!\r\n\r\nPARAMETER: -QueryForLastUserLogon \"true\"\r\n    When checked, the script will query for the last user logon time for each computer.\r\n    Note that this will take longer to run and will try to connect to each computer in the domain.\r\n.EXAMPLE\r\n    -QueryForLastUserLogon \"true\"\r\n    ## EXAMPLE OUTPUT WITH QueryForLastUserLogon ##\r\n    [Warn] Remote computer WIN-1234567891 is not available.\r\n    [Info] Found 2 computers.\r\n\r\n    Computer                  Last Logon Date   Last Login in Days   User\r\n    --------                  ---------------   ------------------   ----\r\n    WIN-1234567891            2024-04-01 12:00   0                   Unknown\r\n    WIN-1234567890            2024-04-01 12:00   0                   Fred\r\n    WIN-9876543210            2023-04-01 12:00   32                  Bob\r\n\r\n.NOTES\r\n    Minimum OS Architecture Supported: Windows Server 2016\r\n    Release Notes: Initial Release\r\n#&gt;\r\n\r\n[CmdletBinding()]\r\nparam (\r\n    [Parameter()]\r\n    [String]$WysiwygCustomField,\r\n    [Parameter()]\r\n    [Switch]$QueryForLastUserLogon\r\n)\r\n\r\nbegin {\r\n    # CIM timeout\r\n    $CIMTimeout = 10\r\n\r\n    function Test-IsElevated {\r\n        $id = [System.Security.Principal.WindowsIdentity]::GetCurrent()\r\n        $p = New-Object System.Security.Principal.WindowsPrincipal($id)\r\n        $p.IsInRole([System.Security.Principal.WindowsBuiltInRole]::Administrator)\r\n    }\r\n    function Set-NinjaProperty {\r\n        [CmdletBinding()]\r\n        Param(\r\n            [Parameter(Mandatory = $True)]\r\n            [String]$Name,\r\n            [Parameter()]\r\n            [String]$Type,\r\n            [Parameter(Mandatory = $True, ValueFromPipeline = $True)]\r\n            $Value,\r\n            [Parameter()]\r\n            [String]$DocumentName\r\n        )\r\n    \r\n        $Characters = $Value | Measure-Object -Character | Select-Object -ExpandProperty Characters\r\n        if ($Characters -ge 10000) {\r\n            throw [System.ArgumentOutOfRangeException]::New(\"Character limit exceeded, value is greater than 10,000 characters.\")\r\n        }\r\n        \r\n        # If we're requested to set the field value for a Ninja document we'll specify it here.\r\n        $DocumentationParams = @{}\r\n        if ($DocumentName) { $DocumentationParams[\"DocumentName\"] = $DocumentName }\r\n        \r\n        # This is a list of valid fields that can be set. If no type is given, it will be assumed that the input doesn't need to be changed.\r\n        $ValidFields = \"Attachment\", \"Checkbox\", \"Date\", \"Date or Date Time\", \"Decimal\", \"Dropdown\", \"Email\", \"Integer\", \"IP Address\", \"MultiLine\", \"MultiSelect\", \"Phone\", \"Secure\", \"Text\", \"Time\", \"URL\", \"WYSIWYG\"\r\n        if ($Type -and $ValidFields -notcontains $Type) { Write-Warning \"$Type is an invalid type! Please check here for valid types. https:\/\/ninjarmm.zendesk.com\/hc\/en-us\/articles\/16973443979789-Command-Line-Interface-CLI-Supported-Fields-and-Functionality\" }\r\n        \r\n        # The field below requires additional information to be set\r\n        $NeedsOptions = \"Dropdown\"\r\n        if ($DocumentName) {\r\n            if ($NeedsOptions -contains $Type) {\r\n                # We'll redirect the error output to the success stream to make it easier to error out if nothing was found or something else went wrong.\r\n                $NinjaPropertyOptions = Ninja-Property-Docs-Options -AttributeName $Name @DocumentationParams 2&gt;&amp;1\r\n            }\r\n        }\r\n        else {\r\n            if ($NeedsOptions -contains $Type) {\r\n                $NinjaPropertyOptions = Ninja-Property-Options -Name $Name 2&gt;&amp;1\r\n            }\r\n        }\r\n        \r\n        # If an error is received it will have an exception property, the function will exit with that error information.\r\n        if ($NinjaPropertyOptions.Exception) { throw $NinjaPropertyOptions }\r\n        \r\n        # The below types require values not typically given in order to be set. The below code will convert whatever we're given into a format ninjarmm-cli supports.\r\n        switch ($Type) {\r\n            \"Checkbox\" {\r\n                # While it's highly likely we were given a value like \"True\" or a boolean datatype it's better to be safe than sorry.\r\n                $NinjaValue = [System.Convert]::ToBoolean($Value)\r\n            }\r\n            \"Date or Date Time\" {\r\n                # Ninjarmm-cli expects the GUID of the option to be selected. Therefore, the given value will be matched with a GUID.\r\n                $Date = (Get-Date $Value).ToUniversalTime()\r\n                $TimeSpan = New-TimeSpan (Get-Date \"1970-01-01 00:00:00\") $Date\r\n                $NinjaValue = $TimeSpan.TotalSeconds\r\n            }\r\n            \"Dropdown\" {\r\n                # Ninjarmm-cli is expecting the guid of the option we're trying to select. So we'll match up the value we were given with a guid.\r\n                $Options = $NinjaPropertyOptions -replace '=', ',' | ConvertFrom-Csv -Header \"GUID\", \"Name\"\r\n                $Selection = $Options | Where-Object { $_.Name -eq $Value } | Select-Object -ExpandProperty GUID\r\n        \r\n                if (-not $Selection) {\r\n                    throw [System.ArgumentOutOfRangeException]::New(\"Value is not present in dropdown\")\r\n                }\r\n        \r\n                $NinjaValue = $Selection\r\n            }\r\n            default {\r\n                # All the other types shouldn't require additional work on the input.\r\n                $NinjaValue = $Value\r\n            }\r\n        }\r\n        \r\n        # We'll need to set the field differently depending on if its a field in a Ninja Document or not.\r\n        if ($DocumentName) {\r\n            $CustomField = Ninja-Property-Docs-Set -AttributeName $Name -AttributeValue $NinjaValue @DocumentationParams 2&gt;&amp;1\r\n        }\r\n        else {\r\n            $CustomField = Ninja-Property-Set -Name $Name -Value $NinjaValue 2&gt;&amp;1\r\n        }\r\n        \r\n        if ($CustomField.Exception) {\r\n            throw $CustomField\r\n        }\r\n    }\r\n}\r\nprocess {\r\n    if (-not (Test-IsElevated)) {\r\n        Write-Host -Object \"[Error] Access Denied. Please run with Administrator privileges.\"\r\n        exit 1\r\n    }\r\n\r\n    # Get Script Variables and override parameters with them\r\n    if ($env:wysiwygCustomField -and $env:wysiwygCustomField -notlike \"null\") {\r\n        $WysiwygCustomField = $env:wysiwygCustomField\r\n    }\r\n    if ($env:queryForLastUserLogon -and $env:queryForLastUserLogon -notlike \"null\") {\r\n        if ($env:queryForLastUserLogon -eq \"true\") {\r\n            $QueryForLastUserLogon = $true\r\n        }\r\n        else {\r\n            $QueryForLastUserLogon = $false\r\n        }\r\n    }\r\n\r\n    # Check that Active Directory module is available\r\n    if (-not (Get-Module -ListAvailable -Name ActiveDirectory)) {\r\n        Write-Host \"[Error] Active Directory module is not available. Please install it and try again.\"\r\n        exit 1\r\n    }\r\n\r\n    # Get the computer system from the CIM\r\n    $ComputerSystem = $(Get-CimInstance -ClassName Win32_ComputerSystem)\r\n\r\n    # Check if this script is running on a domain joined computer\r\n    if ($ComputerSystem.PartOfDomain -eq $false) {\r\n        Write-Host \"[Error] This script must be run on a domain joined computer.\"\r\n        exit 1\r\n    }\r\n\r\n    # Check if this script is running on a domain controller\r\n    switch ($ComputerSystem.DomainRole) {\r\n        0 { Write-Host \"[Info] Running script on a Standalone Workstation.\" }\r\n        1 { Write-Host \"[Info] Running script on a Member Workstation.\" }\r\n        2 { Write-Host \"[Info] Running script on a Standalone Server.\" }\r\n        3 { Write-Host \"[Info] Running script on a Member Server.\" }\r\n        4 { Write-Host \"[Info] Running script on a Backup Domain Controller.\" }\r\n        5 { Write-Host \"[Info] Running script on a Primary Domain Controller.\" }\r\n    }\r\n\r\n    # Get the SearchBase for the domain\r\n    $Domain = \"DC=$($ComputerSystem.Domain -split \"\\.\" -join \",DC=\")\"\r\n\r\n    # Get Computers from Active Directory\r\n    try {\r\n        $Computers = Get-ADComputer -Filter { (Enabled -eq $true) } -Properties Name, LastLogonTimeStamp -SearchBase \"$Domain\" -ErrorAction Stop\r\n    }\r\n    catch {\r\n        Write-Host \"[Error] Failed to get computers. Make sure this is running on a domain controller.\"\r\n        exit 1\r\n    }\r\n\r\n    $IsFirstError = $true\r\n\r\n    $LastLogonInfo = foreach ($Computer in $Computers) {\r\n        try {\r\n            # Get the LastLogonTimeStamp for the computer from Active Directory\r\n            $PCInfo = Get-ADComputer -Identity $Computer.Name -Properties LastLogonTimeStamp -ErrorAction Stop | Select-Object -Property @(\r\n                @{Name = \"Computer\"; Expression = { $_.Name } },\r\n                @{Name = \"LastLogon\"; Expression = { [DateTime]::FromFileTime($_.LastLogonTimeStamp) } }\r\n            )\r\n        }\r\n        catch {\r\n            # This should only happen if the script is not running as the system user on a domain controller or not as a domain admin\r\n            Write-Debug \"[Debug] $($_.Exception.Message)\"\r\n            Write-Host \"[Warn] Failed to get details for $($Computer.Name) from Active Directory. Skipping.\"\r\n            continue\r\n        }\r\n        try {\r\n            if ($QueryForLastUserLogon) {\r\n                # Get the User Principal Name from the computer\r\n                $LastUserLogonInfo = Get-CimInstance -ClassName Win32_UserProfile -ComputerName $Computer.name -OperationTimeoutSec $CIMTimeout -ErrorAction Stop | Where-Object { $_.LocalPath -like \"*Users*\" } | Sort-Object -Property LastUseTime | Select-Object -Last 1\r\n                $SecIdentifier = New-Object System.Security.Principal.SecurityIdentifier($LastUserLogonInfo.SID) -ErrorAction Stop\r\n                $UserName = $SecIdentifier.Translate([System.Security.Principal.NTAccount])\r\n            }\r\n        }\r\n        catch {\r\n            if ($null -eq $UserName) {\r\n                if ($IsFirstError) {\r\n                    # Only show on the first error\r\n                    Write-Debug \"[Debug] $($_.Exception.Message)\"\r\n                    Write-Host \"[Error] Failed to connect to 1 or more computers via Get-CimInstance.\"\r\n                    $IsFirstError = $false\r\n                }\r\n                Write-Host \"[Warn] Remote computer $($Computer.Name) is not available or could not be queried.\"\r\n            }\r\n        }\r\n\r\n        if ($null -eq $UserName) {\r\n            $UserName = [PSCustomObject]@{\r\n                value = \"Unknown\"\r\n            }\r\n        }\r\n        if ($null -eq $PCInfo.LastLogon) {\r\n            $PCInfo = [PSCustomObject]@{\r\n                Computer  = $Computer.Name\r\n                LastLogon = \"Unknown\"\r\n            }\r\n            Write-Host \"[Warn] Failed to get LastLogonTimeStamp for $($Computer.Name).\"\r\n        }\r\n\r\n        # Get the number of days since the last login\r\n        $LastLoginDays = try {\r\n            0 - $(Get-Date -Date $PCInfo.LastLogon).Subtract($(Get-Date)).Days\r\n        }\r\n        catch {\r\n            # Return unknown if the date is invalid or does not exist\r\n            \"Unknown\"\r\n        }\r\n\r\n        # Output the results\r\n        if ($QueryForLastUserLogon) {\r\n            [PSCustomObject]@{\r\n                'Computer'           = $PCInfo.Computer\r\n                'Last Logon Date'    = $PCInfo.LastLogon\r\n                'Last Login in Days' = $LastLoginDays\r\n                'User'               = $UserName.value\r\n            }\r\n        }\r\n        else {\r\n            [PSCustomObject]@{\r\n                'Computer'           = $PCInfo.Computer\r\n                'Last Logon Date'    = $PCInfo.LastLogon\r\n                'Last Login in Days' = $LastLoginDays\r\n            }\r\n        }\r\n\r\n        $PCInfo = $null\r\n        $LastUserLogonInfo = $null\r\n        $SecIdentifier = $null\r\n        $UserName = $null\r\n    }\r\n\r\n    # Output the number of computers found\r\n    if ($LastLogonInfo -and $LastLogonInfo.Count -gt 0) {\r\n        Write-Host \"[Info] Found $($LastLogonInfo.Count) computers.\"\r\n    }\r\n    else {\r\n        Write-Host \"[Error] No computers were found.\"\r\n        $ExitCode = 1\r\n    }\r\n\r\n    function Write-LastLoginInfo {\r\n        param ()\r\n        $LastLogonInfo | Format-Table -AutoSize | Out-String -Width 4000 | Write-Host\r\n    }\r\n\r\n    # Save the results to a custom field\r\n    if ($WysiwygCustomField) {\r\n        $LastLoginOkayDays = 30\r\n        $LastLoginTooOldDays = 90\r\n        # Convert the array to an HTML table\r\n        $HtmlTable = $LastLogonInfo | ConvertTo-Html -Fragment\r\n        # Set the color of the rows based on the last logon time\r\n        $HtmlTable = $HtmlTable -split [Environment]::NewLine | ForEach-Object {\r\n            if ($_ -match \"&lt;td&gt;(?'LastLoginDays'\\d+)&lt;\\\/td&gt;\") {\r\n                # Get the last login days from the HTML table\r\n                [int]$LastLoginDays = $Matches.LastLoginDays\r\n                if ($LastLoginDays -lt $LastLoginTooOldDays -and $LastLoginDays -ge $LastLoginOkayDays) {\r\n                    # warning = 31 days to 89 days\r\n                    $_ -replace \"&lt;tr&gt;&lt;td&gt;\", '&lt;tr class=\"warning\"&gt;&lt;td&gt;'\r\n                }\r\n                elseif ($LastLoginDays -ge $LastLoginTooOldDays) {\r\n                    # danger = 90 days or more\r\n                    $_ -replace \"&lt;tr&gt;&lt;td&gt;\", '&lt;tr class=\"danger\"&gt;&lt;td&gt;'\r\n                }\r\n                else {\r\n                    # success = 30 days or less\r\n                    $_ -replace \"&lt;tr&gt;&lt;td&gt;\", '&lt;tr class=\"success\"&gt;&lt;td&gt;'\r\n                }\r\n            }\r\n            else {\r\n                $_\r\n            }\r\n        }\r\n        # Set the width of the table to 10% to reduce the width of the table to its minimum possible width\r\n        $HtmlTable = $HtmlTable -replace \"&lt;table&gt;\", \"&lt;table style='white-space:nowrap;'&gt;\"\r\n        try {\r\n            Write-Host \"[Info] Attempting to set Custom Field '$WysiwygCustomField'.\"\r\n            Set-NinjaProperty -Name $WysiwygCustomField -Value $($HtmlTable | Out-String)\r\n            Write-Host \"[Info] Successfully set Custom Field '$WysiwygCustomField'!\"\r\n        }\r\n        catch {\r\n            Write-Host \"[Error] Failed to set Custom Field '$WysiwygCustomField'.\"\r\n            Write-LastLoginInfo\r\n            $ExitCode = 1\r\n        }\r\n    }\r\n    else {\r\n        Write-LastLoginInfo\r\n    }\r\n\r\n    exit $ExitCode\r\n}\r\nend {\r\n    \r\n    \r\n    \r\n}<\/pre>\n<p>&nbsp;<\/p>\n\n<div class=\"in-context-cta\"><p>Gagnez du temps gr\u00e2ce \u00e0 plus de 300 scripts du Dojo NinjaOne.<\/p>\n<p>\u2192 <a class=\"waffle-rich-text-link\" href=\"https:\/\/www.ninjaone.com\/freetrialform\/\">Obtenir l&rsquo;acc\u00e8s<\/a><\/p>\n<\/div>\n<h2>Description d\u00e9taill\u00e9e<\/h2>\n<p>Le script est con\u00e7u pour \u00eatre \u00e0 la fois puissant et polyvalent, ce qui permet aux professionnels de l&rsquo;informatique de l&rsquo;adapter \u00e0 leurs besoins sp\u00e9cifiques. Vous trouverez ci-dessous une description d\u00e9taill\u00e9e de ses fonctionnalit\u00e9s\u00a0:<\/p>\n<p><strong>1. V\u00e9rification des pr\u00e9requis<\/strong>\u00a0:<br \/>\nLe script v\u00e9rifie d&rsquo;abord l&rsquo;environnement du syst\u00e8me\u00a0:<\/p>\n<p>a. Confirme qu&rsquo;il est ex\u00e9cut\u00e9 sur un ordinateur reli\u00e9 \u00e0 un domaine.<\/p>\n<p>b. S&rsquo;assure que le module Active Directory PowerShell est install\u00e9.<\/p>\n<p><strong>2. Traitement des param\u00e8tres<\/strong>\u00a0:<br \/>\nLe script accepte deux param\u00e8tres cl\u00e9s\u00a0:<\/p>\n<p>a. -WysiwygCustomField\u00a0: sp\u00e9cifie un champ personnalis\u00e9 dans NinjaOne pour enregistrer les r\u00e9sultats.<\/p>\n<p>b. -QueryForLastUserLogon\u00a0: permet d&rsquo;interroger les d\u00e9tails de la derni\u00e8re connexion de l&rsquo;utilisateur sur chaque ordinateur, bien que cela prolonge le temps d&rsquo;ex\u00e9cution.<\/p>\n<p><strong>3. Requ\u00eate Active Directory<\/strong>\u00a0:<br \/>\nLe script utilise \u00ab\u00a0Get-ADComputer\u00a0\u00bb pour r\u00e9cup\u00e9rer les objets informatiques activ\u00e9s ainsi que leur \u00ab\u00a0LastLogonTimeStamp\u00a0\u00bb (horodatage indiquant la derni\u00e8re connexion). Il arrange les donn\u00e9es dans un tableau lisible, \u00e9ventuellement compl\u00e9t\u00e9 par les d\u00e9tails de la derni\u00e8re connexion de l&rsquo;utilisateur.<\/p>\n<p><strong>4. Gestion des erreurs et journalisation<\/strong>\u00a0:<br \/>\nUne gestion compl\u00e8te des erreurs garantit la fiabilit\u00e9 de l&rsquo;ex\u00e9cution du script. Par exemple\u00a0:<\/p>\n<p>a. Les ordinateurs hors ligne sont signal\u00e9s par des avertissements.<\/p>\n<p>b. Les erreurs commises lors de l&rsquo;interrogation de certains syst\u00e8mes sont enregistr\u00e9es, mais le script continue \u00e0 traiter les autres syst\u00e8mes.<\/p>\n<p><strong>5. Traitement et visualisation des donn\u00e9es<\/strong>\u00a0:<\/p>\n<p>a. Le script calcule le nombre de jours \u00e9coul\u00e9s depuis la derni\u00e8re connexion.<\/p>\n<p>b. Si cette option est sp\u00e9cifi\u00e9e, les r\u00e9sultats sont format\u00e9s dans un tableau HTML pour faciliter la cr\u00e9ation de rapports, avec codes couleur indiquant l&rsquo;anciennet\u00e9 de l&rsquo;activit\u00e9 de connexion.<\/p>\n<p><strong>6. Int\u00e9gration avec NinjaOne<\/strong>\u00a0:<br \/>\nLes r\u00e9sultats peuvent \u00eatre enregistr\u00e9s dans un champ personnalis\u00e9 NinjaOne, ce qui les rend accessibles pour des analyses et des rapports ult\u00e9rieurs.<\/p>\n<h2>Cas d&rsquo;utilisation potentiels<\/h2>\n<h3>\u00c9tude de cas\u00a0:<\/h3>\n<p>L&rsquo;administrateur informatique d&rsquo;une entreprise de taille moyenne remarque un pic d&rsquo;ordinateurs inactifs lors d&rsquo;un audit annuel. Utilisation du script\u00a0:<\/p>\n<ul>\n<li>Il r\u00e9cup\u00e8re les donn\u00e9es de la derni\u00e8re connexion pour tous les appareils du domaine.<\/li>\n<li>Les syst\u00e8mes dormants qui ne se sont pas connect\u00e9s depuis plus de 90 jours sont signal\u00e9s et mis hors service.<\/li>\n<li>Les informations sur l&rsquo;activit\u00e9 des utilisateurs sont utilis\u00e9es pour optimiser l&rsquo;allocation des ressources mat\u00e9rielles.<\/li>\n<\/ul>\n<p>Cette approche am\u00e9liore l&rsquo;\u00e9tat de s\u00e9curit\u00e9 de l&rsquo;entreprise en r\u00e9duisant les surfaces d&rsquo;attaque et permet de r\u00e9aliser des \u00e9conomies en identifiant les ressources sous-utilis\u00e9es.<\/p>\n<h3>Comparaisons<\/h3>\n<p>Traditionnellement, les administrateurs informatiques s&rsquo;appuyaient sur des outils tels que l&rsquo;interface utilisateur graphique d&rsquo;Active Directory Users and Computers (ADUC) ou des logiciels d&rsquo;audit tiers pour collecter les informations de connexion. Ces m\u00e9thodes manquent souvent d&rsquo;\u00e9volutivit\u00e9 ou n\u00e9cessitent un effort manuel important. En revanche, ce script PowerShell\u00a0:<\/p>\n<ul>\n<li>Automatise le processus de r\u00e9cup\u00e9ration des donn\u00e9es, ce qui permet de gagner du temps.<\/li>\n<li>Offre une grande flexibilit\u00e9 gr\u00e2ce \u00e0 des param\u00e8tres personnalisables.<\/li>\n<li>S&rsquo;int\u00e8gre \u00e0 des outils tels que NinjaOne pour am\u00e9liorer les rapports.<\/li>\n<\/ul>\n<h2>FAQ<\/h2>\n<h3>Q\u00a0: Le script n\u00e9cessite-t-il des droits administrateur\u00a0?<\/h3>\n<p>Oui, il doit \u00eatre ex\u00e9cut\u00e9 avec des autorisations \u00e9lev\u00e9es pour interroger efficacement les donn\u00e9es AD.<\/p>\n<h3>Q\u00a0: Quelle est la pr\u00e9cision de la propri\u00e9t\u00e9 LastLogonTimeStamp\u00a0?<\/h3>\n<p>Cette propri\u00e9t\u00e9 peut ne pas refl\u00e9ter l&rsquo;activit\u00e9 en temps r\u00e9el, car elle est mise \u00e0 jour environ tous les 14 jours par d\u00e9faut. Pour obtenir des donn\u00e9es de connexion pr\u00e9cises, envisagez d&rsquo;interroger des contr\u00f4leurs de domaine individuels.<\/p>\n<h3>Q\u00a0: Que se passe-t-il si un ordinateur est hors ligne\u00a0?<\/h3>\n<p>Les syst\u00e8mes hors ligne sont signal\u00e9s par des avertissements et leurs coordonn\u00e9es d&rsquo;utilisateur sont d\u00e9finies comme \u00ab\u00a0inconnues\u00a0\u00bb<\/p>\n<h3>Q\u00a0: Le script peut-il \u00eatre personnalis\u00e9\u00a0?<\/h3>\n<p>Oui, il est con\u00e7u pour \u00eatre flexible. Des param\u00e8tres tels que WysiwygCustomField et QueryForLastUserLogon permettent de personnaliser les cas d&rsquo;utilisation.<\/p>\n<h2>Implications<\/h2>\n<p>Les r\u00e9sultats g\u00e9n\u00e9r\u00e9s par ce script ont des implications significatives pour la s\u00e9curit\u00e9 informatique et l&rsquo;efficacit\u00e9 op\u00e9rationnelle\u00a0:<\/p>\n<ul>\n<li><strong>S\u00e9curit\u00e9 renforc\u00e9e<\/strong>\u00a0: l&rsquo;identification des appareils inactifs r\u00e9duit les vecteurs d&rsquo;attaque potentiels.<\/li>\n<li><strong>Am\u00e9lioration de la conformit\u00e9<\/strong>\u00a0: les entreprises peuvent r\u00e9pondre aux exigences d&rsquo;audit en conservant des enregistrements pr\u00e9cis sur les appareils.<\/li>\n<li><strong>Rationalisation des op\u00e9rations<\/strong>\u00a0: l&rsquo;automatisation \u00e9limine la charge de travail manuelle li\u00e9e au suivi de l&rsquo;activit\u00e9 des appareils.<\/li>\n<\/ul>\n<h2>Recommandations<\/h2>\n<ol>\n<li><strong>Ex\u00e9cutez-le r\u00e9guli\u00e8rement<\/strong>\u00a0: programmez l&rsquo;ex\u00e9cution du script une fois par mois afin de maintenir \u00e0 jour l&rsquo;inventaire des syst\u00e8mes actifs.<\/li>\n<li><strong>Associez-le \u00e0 des strat\u00e9gies<\/strong>\u00a0: utilisez les r\u00e9sultats pour appliquer des politiques telles que la mise hors service des appareils inactifs apr\u00e8s une p\u00e9riode donn\u00e9e.<\/li>\n<li><strong>Utilisez des identifiants s\u00e9curis\u00e9es<\/strong>\u00a0: veillez \u00e0 ce que le script soit ex\u00e9cut\u00e9 dans un environnement s\u00e9curis\u00e9 afin de prot\u00e9ger les donn\u00e9es AD sensibles.<\/li>\n<\/ol>\n<h3>Conclusion<\/h3>\n<p>Pour les administrateurs informatiques et les MSP, l&rsquo;automatisation de la r\u00e9cup\u00e9ration des donn\u00e9es de derni\u00e8re connexion est essentielle pour maintenir un environnement AD s\u00e9curis\u00e9 et efficace. Ce script PowerShell simplifie non seulement le processus, mais s&rsquo;int\u00e8gre \u00e9galement de mani\u00e8re transparente \u00e0 des plateformes telles que NinjaOne, ce qui permet d&rsquo;obtenir des rapports et une gestion avanc\u00e9s. En tirant parti d&rsquo;outils de ce type, les entreprises peuvent optimiser leurs op\u00e9rations informatiques et renforcer leurs cadres de s\u00e9curit\u00e9.<\/p>\n","protected":false},"author":35,"featured_media":0,"parent":0,"menu_order":0,"comment_status":"closed","ping_status":"closed","template":"","meta":{"_acf_changed":false,"_relevanssi_hide_post":"","_relevanssi_hide_content":"","_relevanssi_pin_for_all":"","_relevanssi_pin_keywords":"","_relevanssi_unpin_keywords":"","_relevanssi_related_keywords":"","_relevanssi_related_include_ids":"","_relevanssi_related_exclude_ids":"","_relevanssi_related_no_append":"","_relevanssi_related_not_related":"","_relevanssi_related_posts":"","_relevanssi_noindex_reason":"","_lmt_disableupdate":"no","_lmt_disable":""},"operating_system":[4212],"use_cases":[4289],"class_list":["post-394172","script_hub","type-script_hub","status-publish","hentry","script_hub_category-windows"],"acf":[],"_links":{"self":[{"href":"https:\/\/www.ninjaone.com\/fr\/wp-json\/wp\/v2\/script_hub\/394172","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.ninjaone.com\/fr\/wp-json\/wp\/v2\/script_hub"}],"about":[{"href":"https:\/\/www.ninjaone.com\/fr\/wp-json\/wp\/v2\/types\/script_hub"}],"author":[{"embeddable":true,"href":"https:\/\/www.ninjaone.com\/fr\/wp-json\/wp\/v2\/users\/35"}],"replies":[{"embeddable":true,"href":"https:\/\/www.ninjaone.com\/fr\/wp-json\/wp\/v2\/comments?post=394172"}],"wp:attachment":[{"href":"https:\/\/www.ninjaone.com\/fr\/wp-json\/wp\/v2\/media?parent=394172"}],"wp:term":[{"taxonomy":"script_hub_category","embeddable":true,"href":"https:\/\/www.ninjaone.com\/fr\/wp-json\/wp\/v2\/operating_system?post=394172"},{"taxonomy":"use_cases","embeddable":true,"href":"https:\/\/www.ninjaone.com\/fr\/wp-json\/wp\/v2\/use_cases?post=394172"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}