Reason
A colleague requested a review of an old script because it did not work as intenden on Windows server 2016.
After an hour of reviewing and testing I decided to rewrite the script a bit. Copying some code from Stack Overflow and testing it, this script will ask the OU of the devices required to check and the username to see what tasks or services are run with that user.
remark: when looking for Admin, it will also return administrator because of the -like statement. Replace with -eq to narrow the search.
Please use parts of this script with caution, I am not responsible for any damage.
Script
<#
.Synopsis
PowerShell script to list all Scheduled Tasks and the User ID
.DESCRIPTION
This script scan the content of the c:\Windows\System32\tasks and search the UserID XML value.
The output of the script is a comma-separated log file containing the Computername, Task name, UserID.
#>
###Tasks###
#AD module
Import-Module ActiveDirectory
#var
$VerbosePreference = "continue"
$ou = read-host "Give the OU"
$list = (Get-ADComputer -searchbase $ou -LDAPFilter "(&(objectcategory=computer)(OperatingSystem=*server*))").Name | select-object
Write-Verbose -Message "Trying to query $($list.count) servers found in AD"
$logfilepath = "$home\Desktop\TaskLog.csv"
$ErrorActionPreference = "SilentlyContinue"
$username = "*"
$username += read-host "Give the username"
$username += "*"
#loop
foreach ($computername in $list)
{
$path = "\\" + $computername + "\c$\Windows\System32\Tasks\"
$tasks = Get-ChildItem -Path $path -File
if ($tasks)
{
Write-Verbose -Message "I found $($tasks.count) tasks for $computername"
}
foreach ($item in $tasks)
{
$AbsolutePath = $path + "\" + $item.Name
$task = [xml] (Get-Content $AbsolutePath)
[STRING]$check = $task.Task.Principals.Principal.UserId
if ($check -like $username)
{
Write-Verbose -Message "Writing the log file with values for $computername"
Add-content -path $logfilepath -Value "$computername,$item,$check"
}
}
}
###Services###
#function
Function GLOBAL:GET-PROCESSUSER ( $ProcessID ) {
(GET-WMIOBJECT win32_process –filter “Handle=$ProcessID”).GetOwner().User
}
#var
$a = @()
$logfilepath = "$home\Desktop\ServiceLog.csv"
#loop
foreach ($computername in $list)
{
$svcs = Get-Process -computername $computername
Write-Verbose -Message "I found $($svcs.count) services for $computername"
foreach ($svc in $svcs)
{
$owner = get-processuser $svc.id
if($owner -like $username)
{
$name = $svc.Name
$id = $svc.Id
Write-Verbose -Message "Writing the log file with values for $computername"
Add-content -path $logfilepath -Value "$computername,$id : $name,$owner"
}
}
}
Add comment
Comments