How to Create a Powershell CIR with the script below
Hi guys,
I have this script below that outputs the data I need in a CIR. The problem is i cannot get it to work in Kace/CIR but it works when ran in powershell. The Purpose of this script is to list all AD users who logged into the device.
process {
if ($FromAD -eq $true){
Write-Output "Getting server list from AD..."
$ComputerName = Get-ADComputer -Filter {(enabled -eq $True)} -Properties operatingsystem | Where operatingsystem -match 'server' | Select-Object -ExpandProperty Name
Write-Output " Done"
}
[System.Collections.ArrayList]$computerArray = @()
[System.Collections.ArrayList]$FailedComputerArray = @()
$i = 1
$count = $ComputerName.Count
foreach ($Computer in $ComputerName) {
Write-Progress -Activity "Checking host $computer" -Status "Host $i of $count" -PercentComplete (($i / $count) * 100)
$i++
try {
quser /server:$Computer 2>&1 | Select-Object -Skip 1 | ForEach-Object {
$CurrentLine = $_.Trim() -Replace '\s+',' ' -Split '\s'
$HashProps = @{
UserName = $CurrentLine[0]
ComputerName = $Computer
}
# If session is disconnected different fields will be selected
if ($CurrentLine[2] -eq 'Disc') {
$HashProps.SessionName = $null
$HashProps.Id = $CurrentLine[1]
$HashProps.State = $CurrentLine[2]
$HashProps.IdleTime = $CurrentLine[3]
$HashProps.LogonTime = $CurrentLine[4..6] -join ' '
$HashProps.LogonTime = $CurrentLine[4..($CurrentLine.GetUpperBound(0))] -join ' '
} else {
$HashProps.SessionName = $CurrentLine[1]
$HashProps.Id = $CurrentLine[2]
$HashProps.State = $CurrentLine[3]
$HashProps.IdleTime = $CurrentLine[4]
$HashProps.LogonTime = $CurrentLine[5..($CurrentLine.GetUpperBound(0))] -join ' '
}
$LoggedOnObject = [PSCustomObject]@{
ComputerName = $HashProps.computerName
UserName = $HashProps.UserName
SessionName = $HashProps.SessionName
ID = $HashProps.Id
State = $HashProps.State
IdleTime = $HashProps.IdleTime
Logontime = $HashProps.LogonTime
}
$computerArray.Add($LoggedOnObject) | Out-Null
}
} catch {
write-verbose "Computer: $computer"
write-verbose $error[0]
If ($_.Exception.Message -match "\*"){
write-verbose "$computer No sessions found"
}
else{
$FailedComputer = [PSCustomObject]@{
ComputerName = $Computer
Error = $_.Exception.Message
}
$FailedComputerArray.Add($FailedComputer) | Out-Null
}
}
}
If ($ComputerArray){
Write-Output "List of sessions:"
$ComputerArray | sort-object computername | select-object UserName,State,Id,IdleTime,LogonTime | ft
}
IF ($FailedComputerArray){
Write-Output "Errors:"
$FailedComputerArray | sort-object computername | select-object computerName,Error | ft
}
}
Answers (1)
the easiest thing is:
Build the script and run it regulary on the computer and put the output into a text file.
Show the text file in a CIR.