Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove last element from array

Tags:

powershell

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]}}
like image 226
user20732118 Avatar asked Aug 13 '26 19:08

user20732118


1 Answers

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('\')}}
like image 51
Mathias R. Jessen Avatar answered Aug 21 '26 01:08

Mathias R. Jessen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!