1

I'm trying to create a Powershell script that creates a CSV from a specific OU, takes the last created computer (ie computer-200), adds 1 (so computer-201) and renames the computer. I was able to create the CSV but haven't been able to add an increment of 1 to the name.

Here is the script so far:

Add-WindowsCapability –online –Name “Rsat.ActiveDirectory.DS-LDS.Tools~~~~0.0.1.0”

$OUpath = 'OU=Computers,OU=Test-Devices,DC=Test,DC=local'
$ExportPath = 'c:\temp\computers_in_ou.csv'
Get-ADComputer -Filter * -SearchBase $OUpath -Properties whenCreated | select-object Name,whenCreated | sort whenCreated | Export-Csv -NoType $ExportPath
$csvdata = Import-Csv 'c:\temp\computers_in_ou.csv'
$csvdata | Select-Object Name -Last 1 | Export-Csv -NoType 'c:\temp\renameWS.csv'
$name = Import-Csv 'c:\temp\renameWS.csv' | Select-Object Name -Last 1 

The $name shows output of

Name: Computer-200

How can I take that 200 and add 1?

Thank you!

joanis
  • 10,635
  • 14
  • 30
  • 40
  • Is this the naming convention of the computers (always end with `-XXX` where `XXX` can be any amount of numeric digits) or the digits can be anywhere in it's name? Also, are you sure that `sort whenCreated` will always give you the computer with the highest numeric digit? – Santiago Squarzon Mar 28 '22 at 01:14

2 Answers2

1

You can use replacing Regex.Replace with a script block to increment the digits in the computer's name by 1:

For example:

[regex]::Replace('computer-200', '\d+', {
    param($s)
    [int] $n = $s.Value; (++ $n)
})

# Results in: `computer-201`

If you have access to PowerShell Core, Replacement with a script block was added in PowerShell 6 and later:

'computer-200' -replace '\d+', {
    $n = [int] $_.Value; (++ $n)
}

Following above examples, you could do the following to get the latest computer name and increment the digits by 1:

$computers = Get-ADComputer -Filter * -SearchBase $OUpath -Properties whenCreated |
    Select-Object Name, whenCreated | Sort-Object whenCreated

[regex]::Replace($computers[-1].Name, '\d+', {
    param($s)
    [int] $n = $s.Value; (++ $n)
})
Santiago Squarzon
  • 41,465
  • 5
  • 14
  • 37
0

It really depends on the exact format/trustworthiness of your CSV data, but here's a non-regex way to accomplish this using your existing code.

$csvdata = Import-Csv 'c:\temp\renameWS.csv'
$split = $csvdata[-1].name.Split('-')
$addOne = [int]$split[1] + 1
$final = $split[0] + '-' + $addOne

You can then take that $final string output and append to your CSV, rename with other cmdlets, etc.

Walrusface
  • 11
  • 1
  • 2