From e21189551a275f897a4c16bcfc1b250cd7c86626 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Wojciech=20Napiera=C5=82a?= Date: Mon, 8 Apr 2019 10:43:41 +0200 Subject: [PATCH 01/11] word improvement --- Find-TaskServiceUser.ps1 | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Find-TaskServiceUser.ps1 b/Find-TaskServiceUser.ps1 index 9d35b2d..05e8a36 100644 --- a/Find-TaskServiceUser.ps1 +++ b/Find-TaskServiceUser.ps1 @@ -244,7 +244,7 @@ DONATION: If you want to support my work https://www.paypal.com/cgi-bin/webscr?c } if ($export) { Write-Information -MessageData "Export File: $($Exportpath)" -InformationAction Continue - Write-Information -MessageData "Export File: You can import faile using 'Import-Clixml `"$($Exportpath)`"'" -InformationAction Continue + Write-Information -MessageData "Export File: You can import file using 'Import-Clixml `"$($Exportpath)`"'" -InformationAction Continue $task_all_unique = $tasks_all | sort taskname -Unique $services_all_unique = $services_all | sort name -Unique $export_data = @{"Tasks"=$task_all_unique;"Services"=$services_all} From d6b49869003d0f1f567c0f0833f5f998e33194d2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Wojciech=20Napiera=C5=82a?= Date: Mon, 8 Apr 2019 10:54:12 +0200 Subject: [PATCH 02/11] formatting code --- Find-ServiceUser.ps1 | 73 ++++---- Find-TaskServiceUser.ps1 | 365 +++++++++++++++++++------------------- Find-TaskServiceUser.psd1 | Bin 8830 -> 9586 bytes Find-TaskServiceUser.psm1 | 27 ++- Find-TaskUser.ps1 | 17 +- Invoke-SCHTasks.ps1 | 45 ++--- Write-Log.ps1 | 6 +- 7 files changed, 269 insertions(+), 264 deletions(-) diff --git a/Find-ServiceUser.ps1 b/Find-ServiceUser.ps1 index 3595d3c..d3c196c 100644 --- a/Find-ServiceUser.ps1 +++ b/Find-ServiceUser.ps1 @@ -1,40 +1,41 @@ Function Find-ServiceUser { - [CmdletBinding()] - param ( - [parameter(mandatory=$true,position=0)] - [string[]] - $computer, + [CmdletBinding()] + param ( + [parameter(mandatory = $true, position = 0)] + [string[]] + $computer, - [parameter(mandatory=$false,position=1)] - [string] - $user - ) - $user = $user.trim() - $computer=$computer.trim() - if ([bool](Test-Connection -ComputerName $computer -Count 1 -ErrorAction SilentlyContinue)){ - $filter = "startname like '%$($user)%'" - Write-Verbose -Message "WMI query for system services." - try { - $service_ = Get-CimInstance -classname win32_service -filter "$filter" -ComputerName $computer -ErrorAction Stop - } - catch { - Write-Error -Message "Failed WMI query for system services with Service Logon Account as ""$user"": $_" + [parameter(mandatory = $false, position = 1)] + [string] + $user + ) + $user = $user.trim() + $computer = $computer.trim() + if ([bool](Test-Connection -ComputerName $computer -Count 1 -ErrorAction SilentlyContinue)) { + $filter = "startname like '%$($user)%'" + Write-Verbose -Message "WMI query for system services." + try { + $service_ = Get-CimInstance -classname win32_service -filter "$filter" -ComputerName $computer -ErrorAction Stop + } + catch { + Write-Error -Message "Failed WMI query for system services with Service Logon Account as ""$user"": $_" + } + if ($service_) { + Write-Verbose -Message "Return WMI query data" + return $service_ + #New-Object -TypeName psobject -Property @{` + #Server = $service_.Systemname; + #Servicename = $service_.Name; + #ServicePath = $service_.Pathname; + #ServiceDisplayName = $service_.Displayname; + #StartUser = $service_.Startname; + #ServiceState = $service_.state + #} + } + } + else { + Write-Verbose -Message "$computer`: Connection failed!" + Write-Information -MessageData "$computer`: Connection failed!" -InformationAction Continue + return $null } - if ($service_) { - Write-Verbose -Message "Return WMI query data" - return $service_ - #New-Object -TypeName psobject -Property @{` - #Server = $service_.Systemname; - #Servicename = $service_.Name; - #ServicePath = $service_.Pathname; - #ServiceDisplayName = $service_.Displayname; - #StartUser = $service_.Startname; - #ServiceState = $service_.state - #} - } - } else { - Write-verbose -Message "$computer`: Connection failed!" - Write-Information -MessageData "$computer`: Connection failed!" -InformationAction Continue - return $null - } }# end function Find-ServiceUser diff --git a/Find-TaskServiceUser.ps1 b/Find-TaskServiceUser.ps1 index 05e8a36..820c9d6 100644 --- a/Find-TaskServiceUser.ps1 +++ b/Find-TaskServiceUser.ps1 @@ -1,5 +1,5 @@ Function Find-TaskServiceUser { -<# + <# .SYNOPSIS Finding scheduled tasks, system services on computer by user name. .DESCRIPTION @@ -60,196 +60,205 @@ https://www.powershellgallery.com/packages/Find-TaskServiceUser ICON CREDITS: Module icon made by [Freepik](https://www.freepik.com/) from [Flaticon](https://www.flaticon.com/) is licensed [CC 3.0 BY](http://creativecommons.org/licenses/by/3.0/) DONATION: If you want to support my work https://www.paypal.com/cgi-bin/webscr?cmd=_donations&business=ZQJXFYKHL7JUA¤cy_code=PLN&source=url #> - [CmdletBinding()] - Param( - [parameter(mandatory=$false, position=0, valuefrompipeline = $true, ValueFromPipelineByPropertyName=$true, HelpMessage='Computer NetBIOS, DNS name or IP.')] - [Alias('MachineName','Server')] - [string[]]$Computer=$env:COMPUTERNAME, + [CmdletBinding()] + Param( + [parameter(mandatory = $false, position = 0, valuefrompipeline = $true, ValueFromPipelineByPropertyName = $true, HelpMessage = 'Computer NetBIOS, DNS name or IP.')] + [Alias('MachineName', 'Server')] + [string[]]$Computer = $env:COMPUTERNAME, - [parameter(Mandatory=$false, HelpMessage='User(s) or group name(s) to find scheduled tasks and/or services. Group is used for the security context of the scheduled task only, not system services.')] - [string[]]$User='Administrator', + [parameter(Mandatory = $false, HelpMessage = 'User(s) or group name(s) to find scheduled tasks and/or services. Group is used for the security context of the scheduled task only, not system services.')] + [string[]]$User = 'Administrator', - [parameter(Mandatory=$false, HelpMessage='Switch to find system services.')] - [switch]$Service, + [parameter(Mandatory = $false, HelpMessage = 'Switch to find system services.')] + [switch]$Service, - [parameter(Mandatory=$false, HelpMessage='Switch to find scheduled tasks.')] - [switch]$Task, + [parameter(Mandatory = $false, HelpMessage = 'Switch to find scheduled tasks.')] + [switch]$Task, - [parameter(Mandatory=$false, HelpMessage='Minimalistic results. Object containing the computer name, number of tasks and/or number of services only. with -Log info about log file is displayed but log file is not minimal.')] - [switch]$Minimal, + [parameter(Mandatory = $false, HelpMessage = 'Minimalistic results. Object containing the computer name, number of tasks and/or number of services only. with -Log info about log file is displayed but log file is not minimal.')] + [switch]$Minimal, - [parameter(Mandatory=$false, HelpMessage= 'Enable exporting to file.')] - [switch]$Export, + [parameter(Mandatory = $false, HelpMessage = 'Enable exporting to file.')] + [switch]$Export, - [parameter(Mandatory=$false, HelpMessage= 'Enter path to export file.')] - [string]$Exportpath = [Environment]::GetFolderPath("MyDocuments")+"\Find-TaskServiceUser.XML", + [parameter(Mandatory = $false, HelpMessage = 'Enter path to export file.')] + [string]$Exportpath = [Environment]::GetFolderPath("MyDocuments") + "\Find-TaskServiceUser.XML", - [parameter(Mandatory=$false, HelpMessage='Switch to enable logging.')] - [switch]$Log, + [parameter(Mandatory = $false, HelpMessage = 'Switch to enable logging.')] + [switch]$Log, - [parameter(Mandatory=$false, HelpMessage='Log file path. Default is ''[$env:TEMP]\Find-TaskServiceUser.log''.')] - [string]$Logfile="$env:TEMP\Find-TaskServiceUser.log" - ) - Begin { - if (!$service -and !$task) { - $Service = $Task = $true - } -# Write-output "You must provide 'service' or/and 'task' parameter`n" -# Write-output 'Examples:' -# Write-output ' Find-TaskServiceUser -Computer "WSRV00" -User "BobbyK" -Service -Task' -# Write-output ' Find-TaskServiceUser -Computer "WSRV01" -User "BobbyK" -Task -Log' -# Write-output ' "WSRV00","WSRV03" | Find-TaskServiceUser -Service -Task' -# Write-output ' "WSRV04" | Find-TaskServiceUser -Service' -# Write-output ' $object = Find-TaskServiceUser -Service -Task -Computer "WSRV04" -User "SYSTEM" -Minimal' - if (-not $Minimal) { - if ($user -eq "Administrator") { - Write-Output "Set default user: Administrator" - } - if ($computer -eq $env:COMPUTERNAME) { - Write-output "Set default computer: $env:COMPUTERNAME (localhost)" - } - } else { - Write-Verbose "Initializing minimalistic results." - $minimal_obj = @() - $s=0 - $t=0 - $services_count = $s - $tasks_count = $t - } - if ($Log) { - Write-Log "---------$(get-date)---------" - } - $i=1 #write-progress - } # end BEGIN block - Process { - foreach ($user_item in $User) { - $user_item = $user_item.trim() - write-progress -id 1 -activity "Searching user" -status "$user_item" -percentComplete ($i++ / $user.Count * 100) - $j=1 #write-progress - foreach ($item in $Computer) { - $item = $item.trim() - write-progress -parentId 1 -activity "Searching on server" -status "$item" -percentComplete ($j++ / $Computer.count * 100) - #Tasks - if ($task) { - if (!$Minimal) { - Write-output "Finding tasks with user: ""$($user_item.toupper())"" on machine: ""$($item.toupper())""" - } - if ($Log) { - Write-Log "$(get-date): Finding tasks with user: ""$($user_item.toupper())"" on machine: ""$($item.toupper())""" - } - $tasks = Find-TaskUser -server $item -user $user_item | Sort-Object taskname - #$tasks - if ($tasks) { - # tasks found - Write-Verbose "Task result not null" - if ($Log) { - Write-Log "$(get-date): Scheduled tasks:" + [parameter(Mandatory = $false, HelpMessage = 'Log file path. Default is ''[$env:TEMP]\Find-TaskServiceUser.log''.')] + [string]$Logfile = "$env:TEMP\Find-TaskServiceUser.log" + ) + Begin { + if (!$service -and !$task) { + $Service = $Task = $true + } + # Write-output "You must provide 'service' or/and 'task' parameter`n" + # Write-output 'Examples:' + # Write-output ' Find-TaskServiceUser -Computer "WSRV00" -User "BobbyK" -Service -Task' + # Write-output ' Find-TaskServiceUser -Computer "WSRV01" -User "BobbyK" -Task -Log' + # Write-output ' "WSRV00","WSRV03" | Find-TaskServiceUser -Service -Task' + # Write-output ' "WSRV04" | Find-TaskServiceUser -Service' + # Write-output ' $object = Find-TaskServiceUser -Service -Task -Computer "WSRV04" -User "SYSTEM" -Minimal' + if (-not $Minimal) { + if ($user -eq "Administrator") { + Write-Output "Set default user: Administrator" } - $tasksdata = $tasks | Select-Object Hostname, Taskname, Author, "Run as user", URI - if ($Minimal) { - $tasks_count = ($tasks | Measure-Object).count - } else { - Write-output "Found scheduled task(s) where ""$user_item"" matches task author or 'run as user'" - $tasksdata | Format-Table -AutoSize - } - if ($Log) { - $tasksdata | ForEach-Object { Write-Log $_ } - } - } else { - # tasks not found - if ($Log) { - Write-Log "$(get-date): No scheduled tasks or no data from ""$item"" for user ""$user_item""" - } - if ($Minimal) { - $tasks_count = $t - } else { - Write-output "No scheduled tasks or no data from ""$item"" for user ""$user_item""" - } - } + if ($computer -eq $env:COMPUTERNAME) { + Write-Output "Set default computer: $env:COMPUTERNAME (localhost)" + } } - #Services - if ($service) { - if (-not $Minimal) { - Write-output "Finding system services with user: ""$($user_item.toupper())"" on machine: ""$($item.toupper())""" - } - if ($Log) { - Write-Log "$(get-date): Finding services with user: ""$($user_item.toupper())"" on machine: ""$($item.toupper())""" - } - $services = Find-ServiceUser -computer $item -user $user_item | Sort-Object name - if ($services) { - # services found - Write-Verbose "Services result not null" - if ($Log) { - Write-Log "$(get-date): System services:" - } - $output1 = $services | select-object SystemName,Name, StartName,State - if ($Minimal) { - $services_count = ($services | Measure-Object).count - } else { - Write-output "Found system service(s) where ""$user_item"" matches 'Service Logon Account'" - $output1 | Format-Table -AutoSize - } - if ($Log) { - $output1 | ForEach-Object { Write-Log $_ } - } - } else { - # services not found - Write-Verbose "Services result is null" - if ($Log) { - Write-Log "$(get-date): No services found or no data from ""$item"" for user ""$user_item""" - } - if ($Minimal) { - $services_count = $s - } else { - Write-output "No system services or no data from ""$item"" for user ""$user_item""" - } - } + else { + Write-Verbose "Initializing minimalistic results." + $minimal_obj = @() + $s = 0 + $t = 0 + $services_count = $s + $tasks_count = $t + } + if ($Log) { + Write-Log "---------$(Get-Date)---------" } - if (-not $tasks -and (-not $task -and $service)) { - $tasks_count = $null + $i = 1 #write-progress + } # end BEGIN block + Process { + foreach ($user_item in $User) { + $user_item = $user_item.trim() + Write-Progress -id 1 -activity "Searching user" -status "$user_item" -percentComplete ($i++ / $user.Count * 100) + $j = 1 #write-progress + foreach ($item in $Computer) { + $item = $item.trim() + Write-Progress -parentId 1 -activity "Searching on server" -status "$item" -percentComplete ($j++ / $Computer.count * 100) + #Tasks + if ($task) { + if (!$Minimal) { + Write-Output "Finding tasks with user: ""$($user_item.toupper())"" on machine: ""$($item.toupper())""" + } + if ($Log) { + Write-Log "$(Get-Date): Finding tasks with user: ""$($user_item.toupper())"" on machine: ""$($item.toupper())""" + } + $tasks = Find-TaskUser -server $item -user $user_item | Sort-Object taskname + #$tasks + if ($tasks) { + # tasks found + Write-Verbose "Task result not null" + if ($Log) { + Write-Log "$(Get-Date): Scheduled tasks:" + } + $tasksdata = $tasks | Select-Object Hostname, Taskname, Author, "Run as user", URI + if ($Minimal) { + $tasks_count = ($tasks | Measure-Object).count + } + else { + Write-Output "Found scheduled task(s) where ""$user_item"" matches task author or 'run as user'" + $tasksdata | Format-Table -AutoSize + } + if ($Log) { + $tasksdata | ForEach-Object { Write-Log $_ } + } + } + else { + # tasks not found + if ($Log) { + Write-Log "$(Get-Date): No scheduled tasks or no data from ""$item"" for user ""$user_item""" + } + if ($Minimal) { + $tasks_count = $t + } + else { + Write-Output "No scheduled tasks or no data from ""$item"" for user ""$user_item""" + } + } + } + #Services + if ($service) { + if (-not $Minimal) { + Write-Output "Finding system services with user: ""$($user_item.toupper())"" on machine: ""$($item.toupper())""" + } + if ($Log) { + Write-Log "$(Get-Date): Finding services with user: ""$($user_item.toupper())"" on machine: ""$($item.toupper())""" + } + $services = Find-ServiceUser -computer $item -user $user_item | Sort-Object name + if ($services) { + # services found + Write-Verbose "Services result not null" + if ($Log) { + Write-Log "$(Get-Date): System services:" + } + $output1 = $services | Select-Object SystemName, Name, StartName, State + if ($Minimal) { + $services_count = ($services | Measure-Object).count + } + else { + Write-Output "Found system service(s) where ""$user_item"" matches 'Service Logon Account'" + $output1 | Format-Table -AutoSize + } + if ($Log) { + $output1 | ForEach-Object { Write-Log $_ } + } + } + else { + # services not found + Write-Verbose "Services result is null" + if ($Log) { + Write-Log "$(Get-Date): No services found or no data from ""$item"" for user ""$user_item""" + } + if ($Minimal) { + $services_count = $s + } + else { + Write-Output "No system services or no data from ""$item"" for user ""$user_item""" + } + } + } + if (-not $tasks -and (-not $task -and $service)) { + $tasks_count = $null + } + if (-not $services -and (-not $service -and $task)) { + $services_count = $null + } + if ($Minimal) { + $minimal_obj += [PSCustomObject]@{ + UserName = $user_item + ComputerName = $item + ServicesCount = $services_count + TasksCount = $tasks_count + } + $services_count = $s + $tasks_count = $t + } + if ($Export) { + Write-Verbose -Message "Building objects with all results" + if ($tasks) { + $tasks_all += $tasks + } + if ($services) { + $services_all += $services + } + } + } # end foreach $Computer + } # end foreach $User + } # end PROCESS block + End { + if ($Log -and -not $Minimal) { + Write-Output "Log File: $($Logfile)" } - if (-not $services -and (-not $service -and $task)) { - $services_count = $null + elseif ($minimal -and $Log) { + Write-Information -MessageData "Log File: $($Logfile)" -InformationAction Continue + $minimal_obj } - if ($Minimal) { - $minimal_obj += [PSCustomObject]@{ - UserName = $user_item - ComputerName = $item - ServicesCount = $services_count - TasksCount = $tasks_count - } - $services_count = $s - $tasks_count = $t + elseif ($minimal -and -not $log) { + $minimal_obj } - if ($Export) { - Write-Verbose -Message "Building objects with all results" - if ($tasks) { - $tasks_all += $tasks - } - if ($services) { - $services_all += $services - } + if ($export) { + Write-Information -MessageData "Export File: $($Exportpath)" -InformationAction Continue + Write-Information -MessageData "Export File: You can import file using 'Import-Clixml `"$($Exportpath)`"'" -InformationAction Continue + $task_all_unique = $tasks_all | Sort-Object taskname -Unique + $services_all_unique = $services_all | Sort-Object name -Unique + $export_data = @{"Tasks" = $task_all_unique; "Services" = $services_all } + #Add-Content -LiteralPath $Exportpath -Value $export_data -PassThru + Export-Clixml -LiteralPath $Exportpath -InputObject $export_data } - } # end foreach $Computer - } # end foreach $User - } # end PROCESS block - End { - if ($Log -and -not $Minimal) { - Write-output "Log File: $($Logfile)" - } elseif($minimal -and $Log) { - Write-Information -MessageData "Log File: $($Logfile)" -InformationAction Continue - $minimal_obj - } elseif ($minimal -and -not $log) { - $minimal_obj - } - if ($export) { - Write-Information -MessageData "Export File: $($Exportpath)" -InformationAction Continue - Write-Information -MessageData "Export File: You can import file using 'Import-Clixml `"$($Exportpath)`"'" -InformationAction Continue - $task_all_unique = $tasks_all | sort taskname -Unique - $services_all_unique = $services_all | sort name -Unique - $export_data = @{"Tasks"=$task_all_unique;"Services"=$services_all} - #Add-Content -LiteralPath $Exportpath -Value $export_data -PassThru - Export-Clixml -LiteralPath $Exportpath -InputObject $export_data - } - } # end END block + } # end END block } # end Find-TaskServiceUser function diff --git a/Find-TaskServiceUser.psd1 b/Find-TaskServiceUser.psd1 index b1a882de65f61564697db7d059d4b152afe1f49e..222595c48623dd46a5e815ea942940b3839d2c30 100644 GIT binary patch delta 1160 zcmZWo-%C?*6#w4+R`)|U_shE#=B3V|1m2@171K}B2p51s1sq?%EOxGIdN&9kfc)NHLnMqovK zh*W>nFU2H ziH0tU?=(E-emY}6VNv5-j%^zc5*9MeaBRucN7#mGMSjQd+I*O>pXPgL|n>qxd%v#4`Su~XXTH}IE;YQdbZlb)0c}O_y zf&@KHc9ImD6a1+knyHJ@zvfd_&!{7?OLEJ>*9<;8s>852$GJ_`*-h3Krx)Hi2ROdv z>`?Gh(3KLj{B*D=i96o;bGHajTMY2Zy$@DJBYbne@he@NVPm*UxtdLyZwaPAjG#zp+)vFph)25T+$fLtjcE`MPP^D=Jf6i$feU=iD}U5n_~mh+NPuz9sI3L@dKy{qMf$voBZH@g0(Z}+7 delta 662 zcmXw$OK1~e5XWbe&D*5gHLRO-lWelF4K)@MYLybTwxPzLF$5n0MNDm4txxhO3Q|No ziIm7+6rs?IM{g;`gJ3A0#6!;>#8W}hBI3;=PMVZuc4mI_&3v=}{hj@nZfrpmp6)5o z9e!$bn%~n@r<+tJosK*^wjW=^A~ppHR#O@UlZJJNb$5b>=pfqx8Xz}0+lH5>1lCPs zP|Zc#2|7n7DUDa=i`X(JUB`K3jjr+V3NDC;@IuUBLmWlSlIxvddYA4~g|5>qpQ&Nl zQio=}2i>ZoWqpowWBQcTcw0 zrdw1(LfXfj3Y_w5tjfveFS#Hf>z!(@c(Vem3a_BZNGo|PDI?9#3d6YCfpcmRAJs9) zz9~HL#o254V8-lLAvz=u&OI7^Uj57mVEm4(j zu<&uVDhpR_ckq5Yq|B4%S_3GLMKsOkQ0O~xDjJe*;P`@U>5Pb7;gkq@XC ZD$+(j`wZ5MqikMiQ5C7^1_t+L{sWt(y3YUr diff --git a/Find-TaskServiceUser.psm1 b/Find-TaskServiceUser.psm1 index ec22854..bcc08c7 100644 --- a/Find-TaskServiceUser.psm1 +++ b/Find-TaskServiceUser.psm1 @@ -1,16 +1,13 @@  #Get files. -$files = @( Get-ChildItem -Path $PSScriptRoot\*.ps1 -ErrorAction SilentlyContinue ) +$files = @( Get-ChildItem -Path $PSScriptRoot\*.ps1 -ErrorAction SilentlyContinue ) #Dot source the files -Foreach($import in @($files)) -{ - Try - { +Foreach ($import in @($files)) { + Try { . $import.fullname } - Catch - { + Catch { Write-Error -Message "Failed to import file $($import.fullname): $_" } } @@ -22,21 +19,17 @@ $url = "https://api.github.com/repos/voytas75/Find-TaskServiceUser/releases/late $oldProtocol = [Net.ServicePointManager]::SecurityProtocol # We switch to using TLS 1.2 because GitHub closes the connection if it uses 1.0 or 1.1 [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 -try -{ +try { $response = Invoke-WebRequest -URI $url | ConvertFrom-Json - if ([System.Version]$response.name -ge [System.Version]$ModuleVersion) - { - Write-Output "There is a newer version available. Run 'Update-Module -Name Find-TaskServiceUser' to update to the latest version." -ForegroundColor Red - Write-Output "Alternatively, you can download it manually from https://github.com/voytas75/Find-TaskServiceUser/releases/latest" -ForegroundColor RED + if ([System.Version]$response.name -ge [System.Version]$ModuleVersion) { + Write-Output "There is a newer version available. Run 'Update-Module -Name Find-TaskServiceUser' to update to the latest version." -ForegroundColor Red + Write-Output "Alternatively, you can download it manually from https://github.com/voytas75/Find-TaskServiceUser/releases/latest" -ForegroundColor RED } - else - { + else { Write-Output "You have the latest version installed!" -ForegroundColor Green } } -catch -{ +catch { # Github limits the number of unauthenticated API requests. To avoid this throwing an error we supress it here. Write-Output "Importing Find-TaskServiceUser version $ModuleVersion" -ForegroundColor Red Write-Output "Unable to reach GitHub, please manually verify that you have the latest version by going to https://github.com/voytas75/Find-TaskServiceUser/releases/latest" -ForegroundColor Red diff --git a/Find-TaskUser.ps1 b/Find-TaskUser.ps1 index 13da255..ca624e0 100644 --- a/Find-TaskUser.ps1 +++ b/Find-TaskUser.ps1 @@ -43,14 +43,15 @@ Function Find-TaskUser { try { Write-Verbose -Message "$server`: Try use Get-ScheduledTask." #do cimsession on local to have "pscomputername" property - return Get-ScheduledTask -CimSession $server -ErrorAction stop | Where-Object {$_.author -match $user -or $_.Principal.userid -match $user} | Select-Object @{Name="Hostname"; Expression = {$_.PSComputerName}}, taskname, @{Name="Run As User"; Expression = {$_.Principal.userid}}, Author, URI + return Get-ScheduledTask -CimSession $server -ErrorAction stop | Where-Object { $_.author -match $user -or $_.Principal.userid -match $user } | Select-Object @{Name = "Hostname"; Expression = { $_.PSComputerName } }, taskname, @{Name = "Run As User"; Expression = { $_.Principal.userid } }, Author, URI } catch { - Write-verbose -Message "$server`: Get-ScheduledTask error: $_" + Write-Verbose -Message "$server`: Get-ScheduledTask error: $_" Write-Verbose -Message "$server`: Switching to schtasks command." Invoke-SCHTasks -server $server -user $user } - } else { + } + else { #remote Write-Verbose -Message "$server`: Remote computer." try { @@ -58,7 +59,7 @@ Function Find-TaskUser { Test-Connection -ComputerName $server -Count 1 -ErrorAction Stop | Out-Null } catch { - Write-verbose -Message "$server`: Test-Connection error: $_" + Write-Verbose -Message "$server`: Test-Connection error: $_" Write-Information -MessageData "$server Offline?" -InformationAction Continue return $null } @@ -67,7 +68,7 @@ Function Find-TaskUser { try { #check if is local get-scheduledtask Write-Verbose -Message "$server`: Is local command Get-ScheduledTask ?" - Invoke-Command -ScriptBlock {Get-Command Get-ScheduledTask -ErrorAction Stop} -ErrorAction stop | Out-Null + Invoke-Command -ScriptBlock { Get-Command Get-ScheduledTask -ErrorAction Stop } -ErrorAction stop | Out-Null } catch { # no local get-scheduledtask @@ -75,10 +76,10 @@ Function Find-TaskUser { Write-Verbose -Message "$server`: No local command Get-ScheduledTask." try { Write-Verbose -Message "$server`: Is remote command Get-ScheduledTask ?" - Invoke-Command -ComputerName $server -EnableNetworkAccess -ScriptBlock {Get-Command Get-ScheduledTask -ErrorAction stop} -ErrorAction stop | Out-Null + Invoke-Command -ComputerName $server -EnableNetworkAccess -ScriptBlock { Get-Command Get-ScheduledTask -ErrorAction stop } -ErrorAction stop | Out-Null try { Write-Verbose -Message "$server`: Try use remote command Get-ScheduledTask." - $remote_data = Invoke-Command -ComputerName $server -EnableNetworkAccess -ScriptBlock {Get-ScheduledTask -erroraction stop} -erroraction stop | Where-Object {$_.author -match $user -or $_.Principal.userid -match $user} | Select-Object @{Name="Hostname"; Expression = {$_.PSComputerName}}, taskname, @{Name="Run As User"; Expression = {$_.Principal.userid}}, Author, URI + $remote_data = Invoke-Command -ComputerName $server -EnableNetworkAccess -ScriptBlock { Get-ScheduledTask -erroraction stop } -erroraction stop | Where-Object { $_.author -match $user -or $_.Principal.userid -match $user } | Select-Object @{Name = "Hostname"; Expression = { $_.PSComputerName } }, taskname, @{Name = "Run As User"; Expression = { $_.Principal.userid } }, Author, URI #$remote_data if ($remote_data) { Write-Verbose -Message "$server`: return data from remote command Get-ScheduledTask." @@ -114,7 +115,7 @@ Function Find-TaskUser { #26 end -<# + <# if ([bool](Get-Command Get-ScheduledTask -ErrorAction SilentlyContinue)) { Write-Verbose -Message 'Running ''Get-ScheduleTask''' $data = Get-ScheduledTask -CimSession $server.trim() | Where-Object {$_.author -match $user.trim() -or $_.Principal.userid -match $user.trim()} | Select-Object hostname, taskname, @{Name="Run As User"; Expression = {$_.Principal.userid}}, Author, URI diff --git a/Invoke-SCHTasks.ps1 b/Invoke-SCHTasks.ps1 index daca2e8..802e495 100644 --- a/Invoke-SCHTasks.ps1 +++ b/Invoke-SCHTasks.ps1 @@ -6,27 +6,28 @@ Function Invoke-SCHTasks { [string]$user ) process { -if (($server -match $env:COMPUTERNAME) -or ($server -eq "localhost")) { - Write-Verbose -Message "$server : Try use schtasks on local computer" - try { - $tasks=Invoke-Expression "schtasks /query /fo csv /v" -ErrorAction Stop - } - catch { - Write-Error -Message "Failed to invoke ""schtasks"": $_" - } -} else { - Write-Verbose -Message "$server : Try use schtasks on remote computer" - $exp_schtasks = "schtasks /Query /S $server /FO CSV /V" - write-Verbose $exp_schtasks - try { - $tasks=Invoke-Expression $exp_schtasks -ErrorAction Stop - } - catch { - Write-Error -Message "Failed to invoke ""schtasks"": $_" - } -} -Write-Verbose -Message "$server : Filtering scheduled tasks" -$header = "HostName","TaskName","Next Run Time","Status","Logon Mode","Last Run Time","Last Result","Author","Task To Run","Start In","Comment","Scheduled Task State","Idle Time","Power Management","Run As User","Delete Task If Not Rescheduled","Stop Task If Runs X Hours and X Mins","Schedule","Schedule Type","Start Time","Start Date","End Date","Days","Months","Repeat: Every","Repeat: Until: Time","Repeat: Until: Duration","Repeat: Stop If Still Running" -return $tasks | ConvertFrom-Csv -Header $header | Where-Object {$_."Run As User" -match $user -or $_."Author" -match $user}| Select-Object hostname, @{Name="taskname"; Expression = {($_.TaskName).split("\")[-1]}}, "run as user", author, @{Name="URI"; Expression = {$_.TaskName}} -Unique + if (($server -match $env:COMPUTERNAME) -or ($server -eq "localhost")) { + Write-Verbose -Message "$server : Try use schtasks on local computer" + try { + $tasks = Invoke-Expression "schtasks /query /fo csv /v" -ErrorAction Stop + } + catch { + Write-Error -Message "Failed to invoke ""schtasks"": $_" + } + } + else { + Write-Verbose -Message "$server : Try use schtasks on remote computer" + $exp_schtasks = "schtasks /Query /S $server /FO CSV /V" + Write-Verbose $exp_schtasks + try { + $tasks = Invoke-Expression $exp_schtasks -ErrorAction Stop + } + catch { + Write-Error -Message "Failed to invoke ""schtasks"": $_" + } + } + Write-Verbose -Message "$server : Filtering scheduled tasks" + $header = "HostName", "TaskName", "Next Run Time", "Status", "Logon Mode", "Last Run Time", "Last Result", "Author", "Task To Run", "Start In", "Comment", "Scheduled Task State", "Idle Time", "Power Management", "Run As User", "Delete Task If Not Rescheduled", "Stop Task If Runs X Hours and X Mins", "Schedule", "Schedule Type", "Start Time", "Start Date", "End Date", "Days", "Months", "Repeat: Every", "Repeat: Until: Time", "Repeat: Until: Duration", "Repeat: Stop If Still Running" + return $tasks | ConvertFrom-Csv -Header $header | Where-Object { $_."Run As User" -match $user -or $_."Author" -match $user } | Select-Object hostname, @{Name = "taskname"; Expression = { ($_.TaskName).split("\")[-1] } }, "run as user", author, @{Name = "URI"; Expression = { $_.TaskName } } -Unique } } \ No newline at end of file diff --git a/Write-Log.ps1 b/Write-Log.ps1 index 9c88daf..7a78ee7 100644 --- a/Write-Log.ps1 +++ b/Write-Log.ps1 @@ -1,5 +1,5 @@ function Write-Log { - param([string]$logstring) - Write-Debug -Message "Append ""$logstring"" to log file: ""$logfile""" - Add-Content $logfile -Value $logstring + param([string]$logstring) + Write-Debug -Message "Append ""$logstring"" to log file: ""$logfile""" + Add-Content $logfile -Value $logstring } From 19b833c4a0884070a47adad471b4c5e8e1040094 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Wojciech=20Napiera=C5=82a?= Date: Mon, 8 Apr 2019 10:56:21 +0200 Subject: [PATCH 03/11] delete file and code cleaning --- Find-ServiceUser.ps1 | 8 ----- Find-TaskServiceUser.ps1 | 7 ----- Find-TaskUser.ps1 | 65 ---------------------------------------- _config.yml | 1 - 4 files changed, 81 deletions(-) delete mode 100644 _config.yml diff --git a/Find-ServiceUser.ps1 b/Find-ServiceUser.ps1 index d3c196c..514b849 100644 --- a/Find-ServiceUser.ps1 +++ b/Find-ServiceUser.ps1 @@ -23,14 +23,6 @@ Function Find-ServiceUser { if ($service_) { Write-Verbose -Message "Return WMI query data" return $service_ - #New-Object -TypeName psobject -Property @{` - #Server = $service_.Systemname; - #Servicename = $service_.Name; - #ServicePath = $service_.Pathname; - #ServiceDisplayName = $service_.Displayname; - #StartUser = $service_.Startname; - #ServiceState = $service_.state - #} } } else { diff --git a/Find-TaskServiceUser.ps1 b/Find-TaskServiceUser.ps1 index 820c9d6..8fc47a7 100644 --- a/Find-TaskServiceUser.ps1 +++ b/Find-TaskServiceUser.ps1 @@ -94,13 +94,6 @@ DONATION: If you want to support my work https://www.paypal.com/cgi-bin/webscr?c if (!$service -and !$task) { $Service = $Task = $true } - # Write-output "You must provide 'service' or/and 'task' parameter`n" - # Write-output 'Examples:' - # Write-output ' Find-TaskServiceUser -Computer "WSRV00" -User "BobbyK" -Service -Task' - # Write-output ' Find-TaskServiceUser -Computer "WSRV01" -User "BobbyK" -Task -Log' - # Write-output ' "WSRV00","WSRV03" | Find-TaskServiceUser -Service -Task' - # Write-output ' "WSRV04" | Find-TaskServiceUser -Service' - # Write-output ' $object = Find-TaskServiceUser -Service -Task -Computer "WSRV04" -User "SYSTEM" -Minimal' if (-not $Minimal) { if ($user -eq "Administrator") { Write-Output "Set default user: Administrator" diff --git a/Find-TaskUser.ps1 b/Find-TaskUser.ps1 index ca624e0..9a528b3 100644 --- a/Find-TaskUser.ps1 +++ b/Find-TaskUser.ps1 @@ -8,34 +8,6 @@ Function Find-TaskUser { process { $server = $server.trim() $user = $user.trim() - <# - #23 start - #if ([bool](Get-Command Get-ScheduledTask -ErrorAction SilentlyContinue)) { - if ([bool](Test-Connection -ComputerName $server -Count 1 -ErrorAction SilentlyContinue)){ - if ([bool](Invoke-Command -ComputerName $server -EnableNetworkAccess -ScriptBlock {[bool](Get-Command Get-ScheduledTask -ErrorAction SilentlyContinue)} -erroraction silentlycontinue)) { - try { - Write-Verbose -Message "$server : Try use Get-ScheduledTask" - $data = Get-ScheduledTask -CimSession $server -ErrorAction stop | Where-Object {$_.author -match $user -or $_.Principal.userid -match $user} | Select-Object @{Name="Hostname"; Expression = {$_.PSComputerName}}, taskname, @{Name="Run As User"; Expression = {$_.Principal.userid}}, Author, URI - return $data - } - catch { - Write-verbose -Message "Get-ScheduledTask error: $_" - Write-Verbose -Message "$server : Switching to schtasks command." - - Invoke-SCHTasks -server $server -user $user - - } - } else { - Invoke-SCHTasks -server $server -user $user - - } - } else { - Write-verbose -Message "$server`: Connection failed!" - Write-Information -MessageData "$server`: Connection failed!" -InformationAction Continue - return $null - } - #23 end -#> #26 start if ($server -eq $env:COMPUTERNAME -or $server -eq "localhost") { #local @@ -102,49 +74,12 @@ Function Find-TaskUser { return $null } } - #return Get-ScheduledTask -CimSession $server -ErrorAction stop | Where-Object {$_.author -match $user -or $_.Principal.userid -match $user} | Select-Object @{Name="Hostname"; Expression = {$_.PSComputerName}}, taskname, @{Name="Run As User"; Expression = {$_.Principal.userid}}, Author, URI } catch { - #Write-verbose -Message "Get-ScheduledTask error: $_" - #Write-Verbose -Message "$server`: Switching to schtasks command." - #Invoke-SCHTasks -server $server -user $user Write-Verbose -Message $_ return $null } } #26 end - - - <# - if ([bool](Get-Command Get-ScheduledTask -ErrorAction SilentlyContinue)) { - Write-Verbose -Message 'Running ''Get-ScheduleTask''' - $data = Get-ScheduledTask -CimSession $server.trim() | Where-Object {$_.author -match $user.trim() -or $_.Principal.userid -match $user.trim()} | Select-Object hostname, taskname, @{Name="Run As User"; Expression = {$_.Principal.userid}}, Author, URI - foreach ($record in $data) { - $record.hostname = $server.trim() - } - return $data - } else { - Write-Verbose -Message 'Running system command ''schtasks''' - if ($server.trim() -match $env:COMPUTERNAME -or $server.trim() -eq "localhost") { - try { - $tasks=Invoke-Expression "schtasks /query /fo csv /NH /v" -ErrorAction Stop - } - catch { - Write-Error -Message "Failed to invoke ""schtasks"": $_" - } - } else { - try { - $tasks=Invoke-Expression "schtasks /query /s $server.trim() /NH /fo csv /v" -ErrorAction Stop - } - catch { - Write-Error -Message "Failed to invoke ""schtasks"": $_" - } - } - Write-Verbose -Message 'Filtering scheduled tasks' - $header = "HostName","TaskName","Next Run Time","Status","Logon Mode","Last Run Time","Last Result","Author","Task To Run","Start In","Comment","Scheduled Task State","Idle Time","Power Management","Run As User","Delete Task If Not Rescheduled","Stop Task If Runs X Hours and X Mins","Schedule","Schedule Type","Start Time","Start Date","End Date","Days","Months","Repeat: Every","Repeat: Until: Time","Repeat: Until: Duration","Repeat: Stop If Still Running" - return $tasks | ConvertFrom-Csv -Header $header | Where-Object {$_."Run As User" -match $user -or $_."Author" -match $user}| Select-Object hostname, @{Name="taskname"; Expression = {($_.TaskName).split("\")[-1]}}, "run as user", author, @{Name="URI"; Expression = {$_.TaskName}} -Unique - } # end if -#> - } } diff --git a/_config.yml b/_config.yml deleted file mode 100644 index c419263..0000000 --- a/_config.yml +++ /dev/null @@ -1 +0,0 @@ -theme: jekyll-theme-cayman \ No newline at end of file From d34f0bf72b31a1495003647fbc45e74073bc2d1a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Wojciech=20Napiera=C5=82a?= Date: Mon, 8 Apr 2019 22:54:28 +0200 Subject: [PATCH 04/11] formatting code --- Find-TaskServiceUser.ps1 | 2 +- README.md | 21 +++++++++++++++------ 2 files changed, 16 insertions(+), 7 deletions(-) diff --git a/Find-TaskServiceUser.ps1 b/Find-TaskServiceUser.ps1 index 8fc47a7..d274acb 100644 --- a/Find-TaskServiceUser.ps1 +++ b/Find-TaskServiceUser.ps1 @@ -17,7 +17,7 @@ A Switch to look for system services where user name is matched. .PARAMETER Minimal A switch to enable minimalistic results. Object containing the computer name, number of tasks and/or number of services only. With -Log information about log file path is displayed but log file is not minimal. The return value is en object. .PARAMETER Export -Enable exporting results objects to file (using "Export-Clixml"). Export file path is defined in "Exportpath" parameter. +Enable exporting results objectsr to file (using "Export-Clixml"). Export file path is defined in "Exportpath" parameter. .PARAMETER Exportpath File name path to export results finding scheduled tasks and/or system services. .PARAMETER Log diff --git a/README.md b/README.md index 7cfbbc1..d1aec48 100644 --- a/README.md +++ b/README.md @@ -24,24 +24,33 @@ Install-Module -Name Find-TaskServiceUser -Scope CurrentUser ### Examples -1. Find system services and scheduled tasks on "WSRV00" for user "BobbyK" with logging output to a file: +* Find system services and scheduled tasks on "WSRV00" for user "BobbyK" with logging output to a file: + ```powershell PS> Find-TaskServiceUser -Computer "WSRV00" -User "BobbyK" -Service -Task -Log ``` -2. Find system services and scheduled tasks on computers "WSRV01", "WSRV02" for user "Administrator": + +* Find system services and scheduled tasks on computers "WSRV01", "WSRV02" for user "Administrator": + ```powershell PS> "WSRV01","WSRV02" | Find-TaskServiceUser -Service -Task ``` -3. Find system services and scheduled tasks on computers "WSRV01", "WSRV02", "WSRV03" for user "BobbyK": + +* Find system services and scheduled tasks on computers "WSRV01", "WSRV02", "WSRV03" for user "BobbyK": + ```powershell PS> @("WSRV01","WSRV02"), "WSRV03" | Find-TaskServiceUser -Task -User "BobbyK" ``` -1. Find tasks and services on server "WSRV04" for "SYSTEM" user and return a minimalistic result as custom object `$data`: + +* Find tasks and services on server "WSRV04" for "SYSTEM" user and return a minimalistic result as custom object `$data`: + ```powershell PS> $data = Find-TaskServiceUser -Task -Service -Server "WSRV04" -User "SYSTEM" -Minimal PS> $data ``` -5. Find tasks and services on server "WSRV04" for "JohnK" user. Display results and save it as object in XML file. Import object data from XML and display tasks and services separately: + +* Find tasks and services on server "WSRV04" for "JohnK" user. Display results and save it as object in XML file. Import object data from XML and display tasks and services separately: + ```powershell PS> Find-TaskServiceUser -Task -Service -Server "WSRV04" -User "JohnK" -Export PS> $object = Import-Clixml "D:\dane\voytas\Dokumenty\Find-TaskServiceUser.XML" @@ -59,7 +68,7 @@ Module icon made by [Freepik](https://www.freepik.com/) from [Flaticon](https:// ## Authors -* **Wojciech Napierała** - *Initial work* - [Voytas75](https://github.com/voytas75) +* **Wojciech Napierała** - *Initial work* - [Voytas75](https://github.com/voytas75) See also the list of [contributors](https://github.com/voytas75/Find-TaskServiceUser/graphs/contributors) who participated in this project. From 5989fd1c68b99c8ca809ca2b6de90935b05d7b69 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Wojciech=20Napiera=C5=82a?= Date: Mon, 8 Apr 2019 23:03:02 +0200 Subject: [PATCH 05/11] aliases for minimal - #52 --- Find-TaskServiceUser.ps1 | 1 + 1 file changed, 1 insertion(+) diff --git a/Find-TaskServiceUser.ps1 b/Find-TaskServiceUser.ps1 index d274acb..19e2cbf 100644 --- a/Find-TaskServiceUser.ps1 +++ b/Find-TaskServiceUser.ps1 @@ -76,6 +76,7 @@ DONATION: If you want to support my work https://www.paypal.com/cgi-bin/webscr?c [switch]$Task, [parameter(Mandatory = $false, HelpMessage = 'Minimalistic results. Object containing the computer name, number of tasks and/or number of services only. with -Log info about log file is displayed but log file is not minimal.')] + [Alias('Count','CountOnly')] [switch]$Minimal, [parameter(Mandatory = $false, HelpMessage = 'Enable exporting to file.')] From 5f4bb63acce8101fd7336d799c1baa8d14ab72fa Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Wojciech=20Napiera=C5=82a?= Date: Mon, 8 Apr 2019 23:12:44 +0200 Subject: [PATCH 06/11] first implementation #51 --- Find-TaskServiceUser.ps1 | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/Find-TaskServiceUser.ps1 b/Find-TaskServiceUser.ps1 index 19e2cbf..d44e51d 100644 --- a/Find-TaskServiceUser.ps1 +++ b/Find-TaskServiceUser.ps1 @@ -85,6 +85,12 @@ DONATION: If you want to support my work https://www.paypal.com/cgi-bin/webscr?c [parameter(Mandatory = $false, HelpMessage = 'Enter path to export file.')] [string]$Exportpath = [Environment]::GetFolderPath("MyDocuments") + "\Find-TaskServiceUser.XML", + [parameter(Mandatory = $false, HelpMessage = 'Enable exporting to JSON file.')] + [switch]$ExportJSON, + + [parameter(Mandatory = $false, HelpMessage = 'Enter path to export JSON file.')] + [string]$ExportJSONpath = [Environment]::GetFolderPath("MyDocuments") + "\Find-TaskServiceUser.json", + [parameter(Mandatory = $false, HelpMessage = 'Switch to enable logging.')] [switch]$Log, @@ -222,7 +228,7 @@ DONATION: If you want to support my work https://www.paypal.com/cgi-bin/webscr?c $services_count = $s $tasks_count = $t } - if ($Export) { + if ($Export -or $ExportJSON) { Write-Verbose -Message "Building objects with all results" if ($tasks) { $tasks_all += $tasks @@ -254,5 +260,13 @@ DONATION: If you want to support my work https://www.paypal.com/cgi-bin/webscr?c #Add-Content -LiteralPath $Exportpath -Value $export_data -PassThru Export-Clixml -LiteralPath $Exportpath -InputObject $export_data } + if ($ExportJSON) { + Write-Information -MessageData "Export File: $($Exportjsonpath)" -InformationAction Continue + Write-Information -MessageData "Export File: You can import file using 'Import-Clixml `"$($Exportjsonpath)`"'" -InformationAction Continue + $task_all_unique = $tasks_all | Sort-Object taskname -Unique + $services_all_unique = $services_all | Sort-Object name -Unique + $export_data = @{"Tasks" = $task_all_unique; "Services" = $services_all } + $export_data | ConvertTo-Json | out-file $Exportjsonpath + } } # end END block } # end Find-TaskServiceUser function From 48ac4212b90a079ac8bce190dcc24b1e54c301cc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Wojciech=20Napiera=C5=82a?= Date: Mon, 8 Apr 2019 23:25:01 +0200 Subject: [PATCH 07/11] correcting the function #51 --- Find-TaskServiceUser.ps1 | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/Find-TaskServiceUser.ps1 b/Find-TaskServiceUser.ps1 index d44e51d..29c4658 100644 --- a/Find-TaskServiceUser.ps1 +++ b/Find-TaskServiceUser.ps1 @@ -252,8 +252,8 @@ DONATION: If you want to support my work https://www.paypal.com/cgi-bin/webscr?c $minimal_obj } if ($export) { - Write-Information -MessageData "Export File: $($Exportpath)" -InformationAction Continue - Write-Information -MessageData "Export File: You can import file using 'Import-Clixml `"$($Exportpath)`"'" -InformationAction Continue + Write-Information -MessageData "Export XML File: $($Exportpath)" -InformationAction Continue + Write-Information -MessageData "Export XML File: You can import file using 'Import-Clixml `"$($Exportpath)`"'" -InformationAction Continue $task_all_unique = $tasks_all | Sort-Object taskname -Unique $services_all_unique = $services_all | Sort-Object name -Unique $export_data = @{"Tasks" = $task_all_unique; "Services" = $services_all } @@ -261,8 +261,8 @@ DONATION: If you want to support my work https://www.paypal.com/cgi-bin/webscr?c Export-Clixml -LiteralPath $Exportpath -InputObject $export_data } if ($ExportJSON) { - Write-Information -MessageData "Export File: $($Exportjsonpath)" -InformationAction Continue - Write-Information -MessageData "Export File: You can import file using 'Import-Clixml `"$($Exportjsonpath)`"'" -InformationAction Continue + Write-Information -MessageData "Export JSON File: $($Exportjsonpath)" -InformationAction Continue + Write-Information -MessageData "Export JSON File: You can import file using '`$json_data = Get-Content -Raw -Path `"$($Exportjsonpath)`" | ConvertFrom-Json'" -InformationAction Continue $task_all_unique = $tasks_all | Sort-Object taskname -Unique $services_all_unique = $services_all | Sort-Object name -Unique $export_data = @{"Tasks" = $task_all_unique; "Services" = $services_all } From 6cb3daf03b26a100ec444be2e6c72936fe610924 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Wojciech=20Napiera=C5=82a?= Date: Tue, 9 Apr 2019 00:05:06 +0200 Subject: [PATCH 08/11] first implementation #53 --- Find-ServiceUser.ps1 | 13 +++++++++++-- Find-TaskServiceUser.ps1 | 15 +++++++++++++-- Find-TaskUser.ps1 | 25 +++++++++++++++++++++---- Invoke-SCHTasks.ps1 | 7 ++++++- 4 files changed, 51 insertions(+), 9 deletions(-) diff --git a/Find-ServiceUser.ps1 b/Find-ServiceUser.ps1 index 514b849..94167f0 100644 --- a/Find-ServiceUser.ps1 +++ b/Find-ServiceUser.ps1 @@ -7,12 +7,21 @@ Function Find-ServiceUser { [parameter(mandatory = $false, position = 1)] [string] - $user + $user, + + [parameter(Mandatory = $false, HelpMessage = 'Turns on the search after the exact username.')] + [switch] + $Strict ) $user = $user.trim() $computer = $computer.trim() if ([bool](Test-Connection -ComputerName $computer -Count 1 -ErrorAction SilentlyContinue)) { - $filter = "startname like '%$($user)%'" + if ($Strict) { + $filter = "startname = '$($user)'" + #Write-Information $filter -InformationAction Continue + } else { + $filter = "startname LIKE '%$($user)%'" + } Write-Verbose -Message "WMI query for system services." try { $service_ = Get-CimInstance -classname win32_service -filter "$filter" -ComputerName $computer -ErrorAction Stop diff --git a/Find-TaskServiceUser.ps1 b/Find-TaskServiceUser.ps1 index 29c4658..6df1f63 100644 --- a/Find-TaskServiceUser.ps1 +++ b/Find-TaskServiceUser.ps1 @@ -69,6 +69,9 @@ DONATION: If you want to support my work https://www.paypal.com/cgi-bin/webscr?c [parameter(Mandatory = $false, HelpMessage = 'User(s) or group name(s) to find scheduled tasks and/or services. Group is used for the security context of the scheduled task only, not system services.')] [string[]]$User = 'Administrator', + [parameter(Mandatory = $false, HelpMessage = 'Turns on the search after the exact username.')] + [switch]$Strict, + [parameter(Mandatory = $false, HelpMessage = 'Switch to find system services.')] [switch]$Service, @@ -138,7 +141,11 @@ DONATION: If you want to support my work https://www.paypal.com/cgi-bin/webscr?c if ($Log) { Write-Log "$(Get-Date): Finding tasks with user: ""$($user_item.toupper())"" on machine: ""$($item.toupper())""" } - $tasks = Find-TaskUser -server $item -user $user_item | Sort-Object taskname + if ($Strict) { + $tasks = Find-TaskUser -server $item -user $user_item -Strict | Sort-Object taskname + } else { + $tasks = Find-TaskUser -server $item -user $user_item | Sort-Object taskname + } #$tasks if ($tasks) { # tasks found @@ -179,7 +186,11 @@ DONATION: If you want to support my work https://www.paypal.com/cgi-bin/webscr?c if ($Log) { Write-Log "$(Get-Date): Finding services with user: ""$($user_item.toupper())"" on machine: ""$($item.toupper())""" } - $services = Find-ServiceUser -computer $item -user $user_item | Sort-Object name + if ($Strict){ + $services = Find-ServiceUser -computer $item -user $user_item -strict | Sort-Object name + } else { + $services = Find-ServiceUser -computer $item -user $user_item | Sort-Object name + } if ($services) { # services found Write-Verbose "Services result not null" diff --git a/Find-TaskUser.ps1 b/Find-TaskUser.ps1 index 9a528b3..ee977dd 100644 --- a/Find-TaskUser.ps1 +++ b/Find-TaskUser.ps1 @@ -3,7 +3,9 @@ Function Find-TaskUser { param( [string]$server, - [string]$user + [string]$user, + + [switch]$Strict ) process { $server = $server.trim() @@ -15,12 +17,19 @@ Function Find-TaskUser { try { Write-Verbose -Message "$server`: Try use Get-ScheduledTask." #do cimsession on local to have "pscomputername" property + if ($Strict) { + return Get-ScheduledTask -CimSession $server -ErrorAction stop | Where-Object { $_.author -eq $user -or $_.Principal.userid -eq $user } | Select-Object @{Name = "Hostname"; Expression = { $_.PSComputerName } }, taskname, @{Name = "Run As User"; Expression = { $_.Principal.userid } }, Author, URI + } return Get-ScheduledTask -CimSession $server -ErrorAction stop | Where-Object { $_.author -match $user -or $_.Principal.userid -match $user } | Select-Object @{Name = "Hostname"; Expression = { $_.PSComputerName } }, taskname, @{Name = "Run As User"; Expression = { $_.Principal.userid } }, Author, URI } catch { Write-Verbose -Message "$server`: Get-ScheduledTask error: $_" Write-Verbose -Message "$server`: Switching to schtasks command." - Invoke-SCHTasks -server $server -user $user + if ($Strict) { + Invoke-SCHTasks -server $server -user $user -Strict + } else { + Invoke-SCHTasks -server $server -user $user + } } } else { @@ -51,7 +60,11 @@ Function Find-TaskUser { Invoke-Command -ComputerName $server -EnableNetworkAccess -ScriptBlock { Get-Command Get-ScheduledTask -ErrorAction stop } -ErrorAction stop | Out-Null try { Write-Verbose -Message "$server`: Try use remote command Get-ScheduledTask." - $remote_data = Invoke-Command -ComputerName $server -EnableNetworkAccess -ScriptBlock { Get-ScheduledTask -erroraction stop } -erroraction stop | Where-Object { $_.author -match $user -or $_.Principal.userid -match $user } | Select-Object @{Name = "Hostname"; Expression = { $_.PSComputerName } }, taskname, @{Name = "Run As User"; Expression = { $_.Principal.userid } }, Author, URI + if ($Strict) { + $remote_data = Invoke-Command -ComputerName $server -EnableNetworkAccess -ScriptBlock { Get-ScheduledTask -erroraction stop } -erroraction stop | Where-Object { $_.author -eq $user -or $_.Principal.userid -eq $user } | Select-Object @{Name = "Hostname"; Expression = { $_.PSComputerName } }, taskname, @{Name = "Run As User"; Expression = { $_.Principal.userid } }, Author, URI + } else { + $remote_data = Invoke-Command -ComputerName $server -EnableNetworkAccess -ScriptBlock { Get-ScheduledTask -erroraction stop } -erroraction stop | Where-Object { $_.author -match $user -or $_.Principal.userid -match $user } | Select-Object @{Name = "Hostname"; Expression = { $_.PSComputerName } }, taskname, @{Name = "Run As User"; Expression = { $_.Principal.userid } }, Author, URI + } #$remote_data if ($remote_data) { Write-Verbose -Message "$server`: return data from remote command Get-ScheduledTask." @@ -65,7 +78,11 @@ Function Find-TaskUser { catch { Write-Verbose -Message "$server`: Error useing remote command Get-ScheduledTask: $_" Write-Verbose -Message "$server`: Switch to SCHTASK." - $remote_schtask_data = Invoke-SCHTasks -server $server -user $user + if ($Strict) { + $remote_schtask_data = Invoke-SCHTasks -server $server -user $user -Strict + } else { + $remote_schtask_data = Invoke-SCHTasks -server $server -user $user + } return $remote_schtask_data } } diff --git a/Invoke-SCHTasks.ps1 b/Invoke-SCHTasks.ps1 index 802e495..a2e4816 100644 --- a/Invoke-SCHTasks.ps1 +++ b/Invoke-SCHTasks.ps1 @@ -3,7 +3,9 @@ Function Invoke-SCHTasks { param( [string]$server, - [string]$user + [string]$user, + + [switch]$Strict ) process { if (($server -match $env:COMPUTERNAME) -or ($server -eq "localhost")) { @@ -28,6 +30,9 @@ Function Invoke-SCHTasks { } Write-Verbose -Message "$server : Filtering scheduled tasks" $header = "HostName", "TaskName", "Next Run Time", "Status", "Logon Mode", "Last Run Time", "Last Result", "Author", "Task To Run", "Start In", "Comment", "Scheduled Task State", "Idle Time", "Power Management", "Run As User", "Delete Task If Not Rescheduled", "Stop Task If Runs X Hours and X Mins", "Schedule", "Schedule Type", "Start Time", "Start Date", "End Date", "Days", "Months", "Repeat: Every", "Repeat: Until: Time", "Repeat: Until: Duration", "Repeat: Stop If Still Running" + if ($Strict) { + return $tasks | ConvertFrom-Csv -Header $header | Where-Object { $_."Run As User" -eq $user -or $_."Author" -eq $user } | Select-Object hostname, @{Name = "taskname"; Expression = { ($_.TaskName).split("\")[-1] } }, "run as user", author, @{Name = "URI"; Expression = { $_.TaskName } } -Unique + } return $tasks | ConvertFrom-Csv -Header $header | Where-Object { $_."Run As User" -match $user -or $_."Author" -match $user } | Select-Object hostname, @{Name = "taskname"; Expression = { ($_.TaskName).split("\")[-1] } }, "run as user", author, @{Name = "URI"; Expression = { $_.TaskName } } -Unique } } \ No newline at end of file From cc43ae972606f78347cbf90e73854eb173eec7d3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Wojciech=20Napiera=C5=82a?= Date: Tue, 9 Apr 2019 12:11:48 +0200 Subject: [PATCH 09/11] version note change --- CHANGELOG.md | 6 ++++++ Find-TaskServiceUser.psd1 | Bin 9586 -> 9586 bytes Find-TaskServiceUser.psm1 | 2 +- 3 files changed, 7 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index d7cca8c..1234d02 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,12 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](http://keepachangelog.com/) and this project adheres to [Semantic Versioning](http://semver.org/). +## 1.6.0 - 2019.04.09 + +### Added + +### Changed + ## 1.5.0 - 2019.04.07 ### Added diff --git a/Find-TaskServiceUser.psd1 b/Find-TaskServiceUser.psd1 index 222595c48623dd46a5e815ea942940b3839d2c30..0739d4fe34f6bde992bca80217291d29f58094e7 100644 GIT binary patch delta 14 Vcmez5^~q~P0~4d!=0>KEN&qw31}gvn delta 14 Vcmez5^~q~P0~4d^=0>KEN&qv|1}Xpm diff --git a/Find-TaskServiceUser.psm1 b/Find-TaskServiceUser.psm1 index bcc08c7..6fd335e 100644 --- a/Find-TaskServiceUser.psm1 +++ b/Find-TaskServiceUser.psm1 @@ -13,7 +13,7 @@ Foreach ($import in @($files)) { } #check update -New-Variable -Name ModuleVersion -Value "1.5.0" +New-Variable -Name ModuleVersion -Value "1.6.0" $url = "https://api.github.com/repos/voytas75/Find-TaskServiceUser/releases/latest" $oldProtocol = [Net.ServicePointManager]::SecurityProtocol From c4a49a2292e3a8da08957f75e320070314a343dd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Wojciech=20Napiera=C5=82a?= Date: Tue, 9 Apr 2019 12:56:41 +0200 Subject: [PATCH 10/11] add changelogs for 1.6.0 --- CHANGELOG.md | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index c6650c1..225f702 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,7 +8,11 @@ The format is based on [Keep a Changelog](http://keepachangelog.com/) and this p ### Added -### Changed +- Aliases `Count`, `CountOnly` for parameter `Minimal`, +- Export results to JSON file, parameter `ExportJSON` and `ExportJSONpath`, +- Search for the exact user name, parameter `Strict`. + +- Clearing and formatting the code ## 1.5.3 - 2019.04.09 From 9bd8e5c66e8e3b05db113fbcfafaf67ae1dd9160 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Wojciech=20Napiera=C5=82a?= Date: Tue, 9 Apr 2019 12:57:27 +0200 Subject: [PATCH 11/11] minor changes --- CHANGELOG.md | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 225f702..52a9d80 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,7 +12,10 @@ The format is based on [Keep a Changelog](http://keepachangelog.com/) and this p - Export results to JSON file, parameter `ExportJSON` and `ExportJSONpath`, - Search for the exact user name, parameter `Strict`. -- Clearing and formatting the code +### Changed + +- Clearing and formatting the code, +- Minor changes. ## 1.5.3 - 2019.04.09