Reputation:
I'm really bad at scripting but in any case I need to create a script which should delete special domain accounts with special naming convention. We are using power shell v3. I'm stuck at the filtering profiles area. I have a lot of profiles with bird numbers like: bb1231X, ba1231z, bb1231rw. So I want to delete only the profiles which contain BB****X for example and to double check mark it as 7 symbols and 7 symbol should be X and beginning should be BB.
And do not know how to write this double check. Any help would be appreciated.
Current script:
Function Get-System-Drive-Clean {
[CmdletBinding()]
Param(
[Parameter(Mandatory=$true)]
[string]$computerName
)
PROCESS {
foreach ($computer in $computerName) {
Write-Verbose "Housekeeping on $computer"
Write-Verbose "Mapping drive \\$computer\c$"
$drive = New-PSDrive -Name $computer.replace(".","-") -PSProvider FileSystem -Root \\$computer\C$
write-Verbose "Checking windows version"
#Cheking windows version
$version = (Get-WmiObject -ComputerName $computer -Class Win32_OperatingSystem ).version
Write-Verbose "Windows version $version"
#Profile Deleting area.
if ($version -ge 6) {
write-Verbose "Getting profiles from WMI (Win 2k8 and above)..."
$profiles = Get-WmiObject Win32_UserProfile -ComputerName $computer -Filter "LocalPath like 'C:%R'"
if ($profiles -ne $null) {
$profiles | foreach {
Write-Verbose ("Deleting profile: " + $_.LocalPath)
#$_.Delete()
#| Where {(!$_.Special) -and ($_.ConvertToDateTime($_.LastUseTime) -lt (Get-Date).AddDays(-5))}
}
}
}
}
}
}
}
Upvotes: 0
Views: 96
Reputation: 174505
Regular expressions (or regex
for short) are your friends, and PowerShell has native support for them!
You can use the -match
operator to do regex matching:
PS C:\> 'BB8972X' -match '^BB.{4}X$'
True
PS C:\> 'BA9042W' -match '^BB.{4}X$'
False
The pattern I used in the example above (^BB.{4}X$
) works as follows:
^
: The bare caret character means "start of string position"BB
: This is simply two B
characters.{4}
: In regex, .
means "any character". {4}
is a quantifier meaning "exactly 4 of the preceding character", so 4 of any characterX
: The letter X$
: This means "end of string position"So, if you have a number of Directories with these names and only want the ones where the name is like BB****X
, you'd do:
$BBXDirs = Get-ChildItem -Directory |Where-Object {$_.Name -match '^BB.{4}X$'}
Upvotes: 2