Skip to content

Instantly share code, notes, and snippets.

@skunkie
Last active December 21, 2018 06:24
Show Gist options
  • Save skunkie/98f4a6c43b0248502d62966d01ffab8d to your computer and use it in GitHub Desktop.
Save skunkie/98f4a6c43b0248502d62966d01ffab8d to your computer and use it in GitHub Desktop.
Run a command async on a set of computers
#Requires -Version 3.0
<#
.SYNOPSIS
Wraps Invoke-WmiMethod to run a command async
.DESCRIPTION
Wraps Invoke-WmiMethod to run asynchronously on a number of computers
.PARAMETER Computer
An array of computers
.PARAMETER Command
Command to run
.PARAMETER Path
Path to a file to save errors in CSV format
.EXAMPLE
Invoke-WmiMethodAsync -Computer Server1,Server2,Server3 -Command notepad.exe -Path C:\errors.csv
.LINK
None
.NOTES
Author: skunkie
Last modified: 21.12.2018
#>
[CmdletBinding()]
param(
[Parameter(
Mandatory=$true,
Position=0)] [string[]] $Computer,
[Parameter(
Mandatory=$true,
Position=1)] [string] $Command,
[Parameter(
Mandatory=$false,
Position=2)] [string] $Path
)
Set-StrictMode -Version Latest
workflow Invoke-WmiMethodWF {
param([string[]]$Computer,[string]$Command)
foreach -parallel ($ComputerName in $Computer) {
$err = InlineScript {
try {
Invoke-WmiMethod -Class Win32_Process -Name Create -ArgumentList $using:Command -ComputerName $using:ComputerName -ErrorAction Stop | Out-Null
} catch {
[PSCustomObject]@{'Computer' = $using:ComputerName; 'Error' = $_.Exception.Message}
}
}
$err
}
}
$errs = Invoke-WmiMethodWF -Computer $Computer -Command $Command | Select-Object -Property Computer, Error
if ($errs) {
if ($Path) {
Export-Csv -NoTypeInformation -UseCulture -Path $Path -InputObject $errs
}
Format-Table -InputObject $errs
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment