Home > Software design >  Renaming computer based using Powershell and CSV
Renaming computer based using Powershell and CSV

Time:03-28

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!

CodePudding user response:

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)
})

CodePudding user response:

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.

  • Related