Executing Commands from PowerShell script

Executing Commands from PowerShell Script

PS interface to run system internal or external commands is supported via invoke-* cmdlets as listed below:

PS C:> get-command Invoke-* | ft name

Name

Invoke-Command
Invoke-Expression
Invoke-History
Invoke-Item
Invoke-WmiMethod
Invoke-WSManAction

PS C:>

Executing Command on Local Machine:

$executable = ‘c:WindowsSystem32sc.exe’
$parameters = ‘qc’
$arguments  = ‘WinRM’
$command    = “$executable $parameters $arguments”
Invoke-Expression $command

Execution Output:

PS C:> $executable = ‘c:WindowsSystem32sc.exe’
PS C:> $parameters = ‘qc’
PS C:> $arguments  = ‘WinRM’
PS C:> $command    = “$executable $parameters $arguments”
PS C:> Invoke-Expression $command
[SC] QueryServiceConfig SUCCESS

SERVICE_NAME: WinRM
TYPE               : 20  WIN32_SHARE_PROCESS
START_TYPE         : 3   DEMAND_START
ERROR_CONTROL      : 1   NORMAL
BINARY_PATH_NAME   : C:WindowsSystem32svchost.exe -k NetworkService
LOAD_ORDER_GROUP   :
TAG                : 0
DISPLAY_NAME       : Windows Remote Management (WS-Management)
DEPENDENCIES       : RPCSS
HTTP
SERVICE_START_NAME : NT AUTHORITYNetworkService
PS C:>

Executing an Application/Executable:

When you have a task to simply click once on an application file, you just have to invoke that application file using Invoke-Item as shown below:

Invoke-Item “C:TempMozilla Firefox.lnk”

Invoke-Item C:ToolsNotepad2.exe

Execute PowerShell Code Block on a Remote Computer:

C:PS>invoke-command -computername S1, S2 -scriptblock {get-process powershell}

PSComputerName    Handles  NPM(K)    PM(K)      WS(K) VM(M)   CPU(s)     Id   ProcessName
————–    ——-  ——    —–      —– —–   ——     —   ———–
S1                575      15        45100      40988   200     4.68     1392 powershell
S2                777      14        35100      30988   150     3.68     67   powershell

C:PS>

This feature helps in This including the values of local variables in a command run on a remote computer as shown below.

C:PS>$MWFO-LOg = Microsoft-Windows-Forwarding/Operational

C:PS> invoke-command -computername server01 -scriptblock {param($log, $num) get-eventlog -logname $log -newest $num} -ArgumentList $MWFO-log, 10