Calling a function in PowerShell

This is a quick example that shows how you can call a function in PowerShell.  The example has a function that accepts an Active Directory (AD) Organisation Unit (OU) name, enumerates the computers within that OU and kills any process with the name “Application1.exe”.

Create two files in a folder called PowerShell in the root of C:\, one called KillProcess.ps1, which will contain the function and another called EnumPCsKillProcess.ps1, which will call the function.  Below is the contents of each file:

KillProcess.ps1

Function KillProcess
{
ForEach ($child In $ou.psbase.Children)
{
if ($child.ObjectCategory -Like ‘*computer*’)
{
$Procs = gwmi -ComputerName $child.Name -Query “Select * from Win32_Process Where Name = ‘Application1.exe'”
ForEach ($Proc In $Procs)
{
Write-Host $child.Name
$Proc.Terminate()
}
}
}
}

EnumPCsKillProcess.ps1

. C:\PowerShell\KillProcess.ps1
$ou = [ADSI]”LDAP://OU=ENTER 1ST OU PATH HERE”
KillProcess
$ou = [ADSI]”LDAP://OU=ENTER 2nd OU PATH HERE”
KillProcess

The key line is the one in red above, which references the KillProcess.ps1 file, which contains the function.

Advertisement