PowerShell – exécution à distance avec WMI

Hello,

Voici un petit script vite-fait qui permet l’exécution à distance d’un programme via WMI. Pratique lorsque le ‘remote management’ n’est pas activé. Vous pouvez le modifier afin d’inclure du logging ou d’autres vérifications.

N’oubliez pas de modifier les variables $tempPath et $installString afin de spécifier correctement les chemins des exécutables.

function Execute-Program
{
    <#
    .SYNOPSIS
    This function will execute a program on a remote computer
    .DESCRIPTION
    This function uses WMI to create a process on a remote computer to run a program
    Modify the $tempPath and $installString variable to suit your needs
    .EXAMPLE
    Execute-Program -Computername mycomputer01 -source d:\sources\program
    .PARAMETER computername
    The computer name to query. Just one.
    .PARAMETER source
    The path of the folder containing all required executable files and dependencies that will be copied to the target computer before execution
    #>

    param(
    [Parameter(Mandatory=$true,Position=1)]
    [string]$computername,
    [Parameter(Mandatory=$true,Position=2)]
    [string]$source) #end param


    # Check if the computer is up and running
    try {
        Test-Connection $computername -ErrorAction Stop | Out-Null

        # Define temp folder path
        $tempPath = "\\" + $computername + "\c$\temp\MyFolder" 
               
        # Copy the setup file to the target computer
        Copy-item $source $tempPath -Recurse -Force -ErrorAction Stop
        Write-Verbose -Message "Copied $source in $tempPath" -Verbose

        # Define the installString then start the process on the remote computer
        $installString = $tempPath + "\setup.exe"
        Write-Verbose -Message "Trying to execute $installString" -Verbose
        ([WMICLASS]"\\$computername\ROOT\CIMV2:Win32_Process").Create($InstallString) | Out-Null

        #Clean temp folder
        Remove-Item -Path $tempPath -Recurse -Force
        Write-Verbose -Message "Deleted $tempPath" -Verbose
    }
    catch {
        Write-Warning -Message "$($_.Exception.Message)"
        BREAK
    }
}

J’espère que cela pourra également vous être utile 🙂

 

Laisser un commentaire