I want to run a powershell command, get info about a current windows service.
For example for Redis:
Current path is : "C:\Program Files\Redis\redis-server.exe"
Get-WmiObject win32_service |?{$_.Name -like 'redis*'} | Select-Object Name, DisplayName, state, startmode, @{Name="Path"; Expression={$_.PathName.split('"')}}| convertto-json
{
"Name": "Redis",
"DisplayName": "Redis",
"state": "Running",
"startmode": "Auto",
"Path": "C:\\Program Files\\Redis\\redis-server.exe"
}
But I want to use this path : "C:\Program Files\Redis"
Get-WmiObject win32_service |?{$_.Name -like 'redis*'} | Select-Object Name, DisplayName, state, startmode, @{Name="Path"; Expression={$_.PathName.split('"')[1].split('\\')[0..3]}}| convertto-json
{
"Name": "Redis",
"DisplayName": "Redis",
"state": "Running",
"startmode": "Auto",
"Path": {
"value": [
"C:",
"Program Files",
"Redis",
"redis-server.exe"
],
"Count": 4
}
}
Is there anyway to command like this
...split('\\')[0..length-1]}}
Use Select-Object -SkipLast 1:
@{Name='Path';Expression={$_.PathName.split('"')[1].split('\\') |Select -SkipLast 1}}
Although a simpler option is to use Split-Path to remove the leaf part of the path before splitting:
@{Name='Path';Expression={($_.PathName.split('"')[1] |Split-Path -Parent).Split('\')}}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With