Search code examples
powershellactive-directorydata-cleaning

How to convert the data from a wildcard into a string


I am trying to trim down strings located inside of a .csv so that they only contain the data I need. An example string might be "\path\folder\folder\folder\folder Owner = John Doe".

I just want the John doe part.

Currently I'm importing a list of about 6000 of these strings some have the line some don't.

What I'm trying is:

$owners = Import-Csv .\Owners.csv

ForEach($owner in $owners){
    if ($owner.Description -like "= *") {$owner.Description = "*"}
}

This doesn't seem to work. Is it possible to save the wildcard as a variable?


Solution

  • One method would be to use a Regular Expression rather than Wildcard globbing.

    $owners = Import-Csv .\Owners.csv
    
    $output = foreach ($owner in $owners) {
        # The Description Property has an equal sign followed by a space
        if ($owner.Description -like '*= *') {
            # Use a regex then capture the the text after the equals and space, replace the property with that capture group.
            $owner.Description = $owner.Description -replace '.*=\s(.*)$', '$1'
            $owner
        }
    }
    
    $output | Export-Csv .\Owners.update.csv -NoTypeInformation