Home > Mobile >  Parsing strings before character in Powershell
Parsing strings before character in Powershell

Time:01-07

I want to obtain the environment, project name and location from a string and store it in a variable in Powershell. The string is in the format of env-project-location. Exampleuat-hrapp-westeurope

How do I filter the string and store the outputs in a variable?

$environment = "uat"
$project = "hrapp"
$location = "westeurope"

CodePudding user response:

You don't need regex for this, assuming the string will always have the same naming convention a simple split would do it:

$environment, $project, $location = 'uat-hrapp-westeurope'.Split('-')

CodePudding user response:

Santiago Squarzon's post got me thinking so I did a little googling and found that you can also use this method if you want a PSCustomObject vs independent variables.

Clear-Host
$Base = "uat-hrapp-westeurope"
$CFSArgs = @{PropertyNames = "Environment", "Project", "Location"
             Delimiter = '-'}
$obj = $Base | ConvertFrom-String @CFSArgs
$Obj

Output:


Environment Project Location  
----------- ------- --------  
uat         hrapp   westeurope


PS> $obj | gm


   TypeName: System.Management.Automation.PSCustomObject

Name        MemberType   Definition                    
----        ----------   ----------                    
Equals      Method       bool Equals(System.Object obj)
GetHashCode Method       int GetHashCode()             
GetType     Method       type GetType()                
ToString    Method       string ToString()             
Environment NoteProperty string Environment=uat        
Location    NoteProperty string Location=westeurope    
Project     NoteProperty string Project=hrapp          
  •  Tags:  
  • Related