Search code examples
powershellcsvscriptingactive-directoryfilenames

Remove numbers from string in powershell


Okay, so I might be making this more difficult that it really is, so please tell me if I am.

My end goal: I have a list of computer backups that will be deleted. Each is named with the computer name and the date it was backed up. I'm trying to parse the file name of each backup to grab the usernames for the users themselves, so I can then create a list to be sent to managers. Our computer names and either FIRST-LAST or FLAST, which adds another layer of difficulty.

For instance, I have two computers in my list:
FIRST-LAST 2016.1.12
FLAST 2015.9.8

I want to strip the numbers entirely, leaving me with:
FIRST-LAST
FLAST

I then want to change the computer name of the first one to reflect the username of the original computer owner (we use FLAST as usernames in the company) so that I end up with: FLAST FLAST (obviously a different user outside of this example)

I can then use this information to search active directory for these users, export their names to a list, which will then be sent to managers notifying them of the impending deletion.

It's complicated, and I think maybe there just needs to be a change in our process to make it easier to pull this information, but this is kind of a fun puzzle so I'm curious if we can come to a solution.


Solution

  • Easiest way would be to just use a regex to remove the characters you don't want.

    $string1 = 'FIRST-LAST 2016.1.12'
    $string2 = 'FLAST 2016.1.12'
    
    $string1 = $string1 -replace '[^a-zA-Z-]',''
    $string2 = $string2 -replace '[^a-zA-Z-]',''
    

    That will give you FIRST-LAST and FLAST. '[^a-zA-Z-]','' will replace all non-alpha/- characters with an empty string. From there, you could split FIRST-LAST into two strings using - as the split condition, and use those to look up the information from AD you are looking for.

    $splitstring = $string1 -split '-'
    $first = $splitstring[0]
    $last = $splitstring[1]