Last active
June 17, 2024 02:12
-
-
Save davidlu1001/bc1f3bad8b685ef111d98278b777ed08 to your computer and use it in GitHub Desktop.
Get Service Executable Path
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
param( | |
[string]$ServiceNamePattern # Input parameter to match service names using regex | |
) | |
# Get all services matching the pattern | |
$services = Get-Service | Where-Object { $_.Name -match $ServiceNamePattern } | |
# Iterate through each matching service | |
foreach ($service in $services) { | |
try { | |
# Get the service properties | |
$serviceProperties = Get-WmiObject -Class Win32_Service -Filter "Name = '$($service.Name)'" | |
# Check if path contains quotes | |
if ($serviceProperties.PathName -match '^"(.+?\.exe)"') { | |
$pathToExecutable = $matches[1] | |
} else { | |
$pathToExecutable = ($serviceProperties.PathName -split ' ')[0] | |
} | |
# Output the path to executable | |
Write-Output "$($service.Name) : $pathToExecutable" | |
} | |
catch { | |
Write-Error "Failed to retrieve service properties for $($service.Name): $_" | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment