pakyrs
pakyrs

Reputation: 157

PowerShell - Partially match syntax to remove AD profile folders

I need to automate the removal of profile folders on Active Directory only for certain users that I have in a .csv file, for instance:

Users
john.doe

will have certain profile folders on my server:

\\myserver\john.doe.V2
\\myserver\john.doe.V6
\\myserver\john.doe.V6-old

My question is, can I in powershell somehow instruct, that if "john.doe" matches (even partially, since there is V2, V6 and so forth) then add at the end of each folder "-REMOVE" like so:

\\myserver\john.doe.V2-REMOVE
\\myserver\john.doe.V6-REMOVE
\\myserver\john.doe.V6-old-REMOVE

I think it should be something like this?? definitely need help:

Import-CSV "C:\\users.csv" | foreach {rename-item -path \\myserver\$_.Users –Newname + "-REMOVE"}

Many thanks

Upvotes: 1

Views: 103

Answers (1)

mklement0
mklement0

Reputation: 437308

Import-Csv C:\users.csv |
  ForEach-Object {
    Get-ChildItem -Directory -Path "\\myserver\$($_.Users).*" |
      Rename-Item –NewName { $_.Name + "-REMOVE" } -WhatIf 
  }

Note: The -WhatIf common parameter in the command above previews the operation. Remove -WhatIf once you're sure the operation will do what you want.

  • Get-ChildItem -Directory -Path "\\myserver\$($_.Users).*" locates all directories for the username ($_.Users) at hand, using an expandable string that expands to a wildcard expression passed to the -Path parameter, where * represents any (potentially empty) sequence of characters.

  • The resulting directories are piped to Rename-Item, which uses a delay-bind script block to determine the new name based on the old one ($_.Name).

Upvotes: 1

Related Questions