PowerShell: Invoke-Command

Bonjour, aujourd’hui nous allons parler de la fonction PowerShell: Invoke-Command

J’ai eu l’occasion d’utiliser cette fonction dans le cadre de l’écriture d’un script pour rechercher à distance la présence d’un dossier sur un PC distant.

Simplement cette fonction est utilisée avec cette commande, elle sert à se connecter sur le PC $comp et d’y mettre le code demandé entre les crochets.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
Invoke-Command -Computername $comp -ScriptBlock {}
Invoke-Command -Computername $comp -ScriptBlock {}
Invoke-Command -Computername $comp -ScriptBlock {}

Exemple ici, on va exécuter une commande de récupération d’OS:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
Invoke-Command -Computername $comp -ScriptBlock {
(Get-CimInstance Win32_OperatingSystem).Caption
}
Invoke-Command -Computername $comp -ScriptBlock { (Get-CimInstance Win32_OperatingSystem).Caption }
Invoke-Command -Computername $comp -ScriptBlock {
(Get-CimInstance Win32_OperatingSystem).Caption
}

Résultat de la commande exécutée:

Maintenant je vous donne la commande que j’ai utilisé pour récupérer tous les profils d’un PC distant.
Donc je vais sur le PC que j’avais mis dans ma variable $comp, puis je recherche sur ce PC dans les clés de registres les profils, que je filtre en fonction du nom avec le .startsWith, car j’avais besoin uniquement des profils se trouvant dans C:\Users\ et qui ne soit pas le compte « Administrateur ».

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
$array = Invoke-Command -Computername $comp -ScriptBlock {
$regPath = 'HKLM:\Software\Microsoft\Windows NT\CurrentVersion\ProfileList'
Get-ChildItem -path $regPath |
ForEach-Object {
(Get-ItemProperty -path (join-path -path $regPath -child $_.pschildName) -Name profileImagePath).profileImagePath
} | where {$_.startsWith("C:\Users\") -And $_ -notlike "*Administrateur*" }
}
$array = Invoke-Command -Computername $comp -ScriptBlock { $regPath = 'HKLM:\Software\Microsoft\Windows NT\CurrentVersion\ProfileList' Get-ChildItem -path $regPath | ForEach-Object { (Get-ItemProperty -path (join-path -path $regPath -child $_.pschildName) -Name profileImagePath).profileImagePath } | where {$_.startsWith("C:\Users\") -And $_ -notlike "*Administrateur*" } }
$array = Invoke-Command -Computername $comp -ScriptBlock {
        $regPath = 'HKLM:\Software\Microsoft\Windows NT\CurrentVersion\ProfileList'
        
        Get-ChildItem  -path $regPath |
        ForEach-Object {
         (Get-ItemProperty -path (join-path -path $regPath -child $_.pschildName) -Name profileImagePath).profileImagePath
        } | where {$_.startsWith("C:\Users\") -And  $_ -notlike "*Administrateur*" }
    }

A vous de vous amusez !