Hello dudes
I’ve created my advanced function and I want to know your remarks and notes. This function should read computer names from AD an invoke scriptblocks on them:
Function Invoke-CommandOnADComputers
{
[CmdletBinding(SupportsShouldProcess=$True,ConfirmImpact='Low')]
Param
(
# This is Active Directory Search Base to limit selection for computer accounts in domain.
# It can be for example "OU=Computers,OU=Company Name,DC=domain,DC=local"
[parameter(Mandatory=$true)]
[string]
$SearchBase,
# Active Directory filter to merge your computer selection in to the detail.
# It can be for example 'Name -like "Desktop*"'
[string]
$Filter = "*",
# This is scriptblock which should be run on every computer.
# For example { Restart-Service W32Time; }
[parameter(Mandatory=$true)]
[scriptblock]
$ScriptBlock
)
Begin
{
#
# Get list of computer accounts
#
Write-Debug "Getting list of computer from $ADSear"
try
{
$ADComputersList = Get-ADComputer -SearchBase $SearchBase -Filter $Filter -ErrorAction Stop
}
catch
{
Write-Error -Message "Couldn't search in $SearchBase" -ErrorAction Stop
}
#
# Write number of found computers
#
Write-Output "Found $($ADComputersList.Count) computers"
#
# If in debug, write list of computers
#
Write-Debug "List of machines:"
If (!$PSDebugContext)
{
foreach ($item in $ADComputersList)
{
Write-Debug " $($item.Name)"
}
}
Write-Debug "Done with domain computer list"
}
Process
{
#
# Let's invoke command on remote computer
#
foreach ($ADComputer in $ADComputersList)
{
Write-Output $ADComputer.Name
try
{
Write-Debug "Invoking scriptblock on computer"
Invoke-Command -ComputerName $ADComputer.Name -ScriptBlock { $ScriptBlock } -ErrorAction Stop
Write-Output " Scriptblock invoked successful."
}
catch
{
Write-Output " Scriptblock invoked UNSUCCESSFUL."
}
}
}
}