Skip to content

Instantly share code, notes, and snippets.

@davidlu1001
Last active June 17, 2024 02:12
Show Gist options
  • Save davidlu1001/bc1f3bad8b685ef111d98278b777ed08 to your computer and use it in GitHub Desktop.
Save davidlu1001/bc1f3bad8b685ef111d98278b777ed08 to your computer and use it in GitHub Desktop.
Get Service Executable Path
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