简体   繁体   中英

Extract string from specific key word in Powershell

I Have a users in AD with Description that contains strings ex: "accountant TEMP 10/02/2021 and sth"

I would like to do two things:

  1. Extract user from specific Keyword like TEMP, PERM and date

I believe it should look like this:

$users = Get-ADUser -Filter * -Properties * -SearchBase "OU=Toster,DC=I,DC=Like,DC=Chocolate"|where {$_.Description -like "*TEMP*" -or $_.Description -like "*PERM*" } |select samaccountname,description,name
  1. Substring from TEMP and PERM a Date but from this specific keywords

For now I have a condition that PERM and TERM are at the beginning of description but I do not want that to be a permanent solution:(

    $DataPart=$use.description
    $DatePart= $DataPart.substring(5,10) #it substrings after PERM and TEMP a date in description and then i use below code to convert this string to date:
$FinalDate = [datetime]::ParseExact($DatePart,'dd/MM/yyyy',$null)

So my question is how do I substring from PERM and TERM keywords instead from specific place in string like I did in the above code?

Try:

$users = Get-ADUser -Filter * -Properties Description -SearchBase "OU=Toster,DC=I,DC=Like,DC=Chocolate" |
         Where-Object {$_.Description -match "TEMP|PERM" } |
         Select-Object SamAccountName,Description,Name, 
                       @{Name = 'FinalDate'; Expression = {
                            $date = ([regex]'(\d{2}/\d{2}/\d{4})').Match($_.Description).Groups[1].Value
                            [datetime]::ParseExact($date,'dd/MM/yyyy', $null)
                        }}


# output on screen
$users | Format-Table -AutoSize

# output to CSV
$users | Export-Csv -Path 'Path\To\tempusers.csv' -NoTypeInformation

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM