Rechercher dans ce blog

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

vendredi 30 mars 2018

MDT - MoveOU - LDAP - With Get Credential MDT SecureString























Import-Module Z:\Tools\Modules\ZTIUtility\ZTIUtility.psm1

function Base64Decode($textBase64In) {
    $b  = [System.Convert]::FromBase64String($textBase64In)
    $decoded = [System.Text.Encoding]::UTF8.GetString($b)
    return $decoded
}

$DomainAdmin = Base64Decode($tsenv:DomainAdmin)  
$DomainAdminDomain = Base64Decode($tsenv:DomainAdminDomain) 
$DomainAdminPassword = convertto-securestring -string (Base64Decode($tsenv:DomainAdminPassword)) -AsPlainText -Force


$ComputerName = $env:COMPUTERNAME
$OU = $tsenv:MACHINEOBJECTOU

$ldap = "LDAP://DC=XX,DC=XXX,DC=XX"
$ObjComputer = "(&(objectclass=computer)(cn= $ComputerName))"

if($DomainAdmin.Contains("\") -eq $true){
    $login_admin = "$DomainAdmin"
}
else
{
    $login_admin = "$DomainAdminDomain\$DomainAdmin"
}

#$AdPass = convertto-securestring -string $DomainAdminPassword -AsPlainText -Force
$AdCred = new-object -typename System.Management.Automation.PSCredential -argumentlist $login_admin , $DomainAdminPassword

Remove-Job *



start-job -Name "ChangeOU" -ScriptBlock {
    New-Item -Path C:\XXXXXXXXXXX\XXXXX -ItemType Directory -ErrorAction SilentlyContinue
    $ServeurLdap = $args[1]
    $LaMachineARechercher = $args[0]
    $DestinationOU = $args[2]
    $WriteLog = "C:\XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX.log"

    $objDomain = New-Object System.DirectoryServices.DirectoryEntry  $ServeurLdap
    $objSearcher = New-Object System.DirectoryServices.DirectorySearcher
    $objSearcher.SearchRoot = $objDomain
    $objSearcher.PageSize = 10000
    $objSearcher.Filter = $LaMachineARechercher
    $objSearcher.SearchScope = "Subtree"
    $colResults = $objSearcher.FindAll()
    $ResultatMachine = ($colResults.Item(0)).path #$colResults.Item(0).Properties.Item("DistinguishedName")

    "$(Get-Date) - Actuellement : $(($colResults.Item(0)).path)" | Out-File -FilePath $WriteLog -Append
    "$(Get-Date) - Serveur LDAP : $ServeurLdap" | Out-File -FilePath $WriteLog -Append
    "$(Get-Date) - La machine : $LaMachineARechercher" | Out-File -FilePath $WriteLog -Append
    "$(Get-Date) - Destination : $DestinationOU" | Out-File -FilePath $WriteLog -Append


    $Object = New-Object -TypeName System.DirectoryServices.DirectoryEntry($ResultatMachine)
    $TargetOU = New-Object -TypeName System.DirectoryServices.DirectoryEntry("LDAP://$DestinationOU")
    $Object.psbase.Moveto($TargetOU)


    $objSearcher.Filter = $LaMachineARechercher
    $objSearcher.SearchScope = "Subtree"
    $colResults = $objSearcher.FindAll()
    "$(Get-Date) - Maintenant : $(($colResults.Item(0)).path)" | Out-File -FilePath $WriteLog -Append


} -Credential $AdCred -ArgumentList ($ObjComputer.Trim()), $ldap, $OU

$resultat = Receive-Job -Name ChangeOU -Wait


jeudi 15 mars 2018

Faire un ping sur plusieurs machines



J'ai eu a faire un ping régulier sur une liste de machine assez grosse qui prenait beaucoup de temps d’exécution, voici comment faire rapide :



$ComputersPing = Test-Connection -ComputerName (Get-Content "C:\..........\ListComputer.txt") -Delay 1 -Count 1 -ThrottleLimit 10 -ErrorAction SilentlyContinue -AsJob | Wait-Job

$Results = Receive-Job $ComputersPing
$Results = $Results | Sort-Object ResponseTime -Descending | Where-Object ResponseTime -NE $null
$Results




Des questions / remarques ?

mardi 6 février 2018

Powershell - Renommer une machine si elle existe dans landesk (webservice)

$Log = 'C:\Windows\Logs\RenamecomputerLog.log'
$URILandesk = "http://----YOURSERVER----/MBSDKService/MsgSDK.asmx"

function Write-Log {
    [CmdletBinding()]
    Param
    (
        [Parameter(Mandatory=$true,
                   ValueFromPipelineByPropertyName=$true)]
        [ValidateNotNullOrEmpty()]
        [Alias("LogContent")]
        [string]$Message,

        [Parameter(Mandatory=$false)]
        [Alias('LogPath')]
        [string]$Path= $Log,
        
        [Parameter(Mandatory=$false)]
        [ValidateSet("Error","Warn","Info")]
        [string]$Level="Info",
        
        [Parameter(Mandatory=$false)]
        [switch]$NoClobber
    )

    Begin
    {
        # Set VerbosePreference to Continue so that verbose messages are displayed.
        $VerbosePreference = 'Continue'
    }
    Process
    {
        
        # If the file already exists and NoClobber was specified, do not write to the log.
        if ((Test-Path $Path) -AND $NoClobber) {
            Write-Error "Log file $Path already exists, and you specified NoClobber. Either delete the file or specify a different name."
            Return
            }

        # If attempting to write to a log file in a folder/path that doesn't exist create the file including the path.
        elseif (!(Test-Path $Path)) {
            Write-Verbose "Creating $Path."
            $NewLogFile = New-Item $Path -Force -ItemType File
            }

        else {
            # Nothing to see here yet.
            }

        # Format Date for our Log File
        $FormattedDate = Get-Date -Format "yyyy-MM-dd HH:mm:ss"

        # Write message to error, warning, or verbose pipeline and specify $LevelText
        switch ($Level) {
            'Error' {
                Write-Error $Message
                $LevelText = 'ERROR:'
                }
            'Warn' {
                Write-Warning $Message
                $LevelText = 'WARNING:'
                }
            'Info' {
                Write-Verbose $Message
                $LevelText = 'INFO:'
                }
            }
        
        # Write log entry to $Path
        "$FormattedDate $LevelText $Message" | Out-File -FilePath $Path -Append
    }
    End
    {
    }
}

############################################################
#
#    CONNECT LANDESK
$Server = New-WebServiceProxy -Uri ($URILandesk) -UseDefaultCredential

############################################################
#
#    GET ALL DEVICES
$AllMachines = $Server.ListMachines("").Devices

############################################################
#
#    GET BIOS SERIAL NUMBER LOCAL
$SerialNumberBiosLocal = (Get-WmiObject -Class Win32_Bios | select SerialNumber).SerialNumber

############################################################
#
#    FIND CORRESPONDANCE IN LANDESK
$computersystem = Get-WmiObject -Class win32_computersystem

Foreach($Machine in $AllMachines)
{
   $LandeskSerialNumber = $Server.GetMachineData($Machine.guid, 'Computer.Bios."Serial Number"').MachineData.Value
     
   if($SerialNumberBiosLocal -eq $LandeskSerialNumber)
   {
        $match = $Machine.DeviceName
        Write-Log -Message "----------------------------------" -Level Info
        Write-Log -Message $Machine.DeviceName -Level Info
        Write-Log -Message $Machine.guid -Level Info
        Write-Log -Message $LandeskSerialNumber -Level Info
        Write-Log -Message "----------------------------------" -Level Info
        break;
   }
}
function FormRename {
    Add-Type -AssemblyName System.Windows.Forms

    $FormRenameComputer = New-Object system.Windows.Forms.Form
    $FormRenameComputer.Text = "Rename Computer"
    $FormRenameComputer.TopMost = $true
    $FormRenameComputer.Width = 431
    $FormRenameComputer.Height = 184

    $textBox2 = New-Object system.windows.Forms.TextBox
    $textBox2.Width = 312
    $textBox2.Height = 20
    $textBox2.location = new-object system.drawing.point(45,58)
    $textBox2.Font = "Microsoft Sans Serif,10"
    $FormRenameComputer.controls.Add($textBox2)

    $Label1 = New-Object System.Windows.Forms.Label
    $Label1.Width = 150
    $Label1.Height = 20
    $Label1.Text = "Rename Computer"
    $Label1.location = new-object system.drawing.point(45,20)
    $Label1.Font = "Microsoft Sans Serif,10"
    $FormRenameComputer.controls.Add($Label1)

    $button2 = New-Object system.windows.Forms.Button
    $button2.Text = "OK"
    $button2.Width = 60
    $button2.Height = 30
    $button2.location = new-object system.drawing.point(340,100)
    $button2.Font = "Microsoft Sans Serif,10"
    $FormRenameComputer.controls.Add($button2)

    $button2.Add_MouseClick({
        #$computersystem.Rename($textBox2.Text.Trim())
        $FormRenameComputer.Close()
      })


    [void]$FormRenameComputer.ShowDialog()
    $FormRenameComputer.Dispose()
}


If($computersystem.Name -eq $Machine.DeviceName)
{
    ############################################################
    #
    #    PROTECT
    Write-Log -Message "Rename computer : cannot be rename because the computer name is the same" -Level Info
    FormRename
}
else
{
    ############################################################
    #
    #    RENAME COMPUTER
    "Rename computer with : $($Machine.DeviceName)"
    $computersystem.Rename($Machine.DeviceName)
}