PowerShell: Using PSExec with PowerShell

2 min readGinja

I use this Commandlet that I made to scan computers into assets combining both a .vbs file and psexec to run it on a remote machine.

function Add-ToAssets {
    param (
    $computerName = $(Throw "Please specify a computer name"),
    $explicit
    )
    
    if ($explicit -eq $null) {
        $computerName = Search-Computer($computerName)
    }
    
    if ($computerName) {
    
        $raescan = "\\$computerName\c$\ae_scan.vbs"
        $rscanex = "c:\ae_scan.vbs"
        $cmd     = "cmd.exe /c $psexec \\$computerName cscript.exe $rscanex"
        
        if (Test-Connection $computerName -quiet -count 1) {
            
            Write-Host "---------------------------"     -fore Gray
            Write-Host "Adding $computerName to assets." -fore Red
            Write-Host "---------------------------"     -fore Gray
            
            Copy-Item $aescan "\\$computerName\c$\" -ea Stop   
            Invoke-Expression $cmd -ea Stop
            Remove-Item $raescan
            
        } else {
        
            Write-Host "---------------------------"            -fore Gray
            Write-Host "Computer $computerName is unreachable." -fore Red
            Write-Host "---------------------------"            -fore Gray
            
        }
    }   
}


I will go through this line by line and explain how it works.

The magic really happens with:

$cmd     = "cmd.exe /c $psexec \\$computerName cscript.exe $rscanex" 

and

Invoke-Expression $cmd -ea Stop

The invoke-expression is a very powerful commandlet in itself. 

 

Comments

No comments yet. Be the first!