So, this code works great and I actually figured out a regex, albeit simple, I figured it out which is an accomplishment on a Friday afternoon. Basically, if a file exists, I want to update the path to append (1), (2)…and so on. I’m more curious if there is a more efficient way to do this:
$path = "C:\Test\Test_Jim_Johnson_8-12-2014.txt"
$int = 2
$regex = "\(\d+\)"
if (Test-Path $path) {
do {
if ($path -match $regex) {
$path = $path -replace $regex, ("({0})" -f $int)
}
else {
$path = $path -replace ".txt", ("({0}).txt" -f $int)
}
$int++
}
while (Test-Path -Path $path)
}
New-Item -ItemType File -Path $path -Force
Which generates:
PS C:\Users\sysrs.INT> gci C:\test
Directory: C:\test
Mode LastWriteTime Length Name
---- ------------- ------ ----
-a--- 7/11/2014 4:02 PM 0 Test_Jim_Johnson_8-12-2014(10).txt
-a--- 7/11/2014 4:02 PM 0 Test_Jim_Johnson_8-12-2014(11).txt
-a--- 7/11/2014 4:02 PM 0 Test_Jim_Johnson_8-12-2014(2).txt
-a--- 7/11/2014 4:02 PM 0 Test_Jim_Johnson_8-12-2014(3).txt
-a--- 7/11/2014 4:02 PM 0 Test_Jim_Johnson_8-12-2014(4).txt
-a--- 7/11/2014 4:02 PM 0 Test_Jim_Johnson_8-12-2014(5).txt
-a--- 7/11/2014 4:02 PM 0 Test_Jim_Johnson_8-12-2014(6).txt
-a--- 7/11/2014 4:02 PM 0 Test_Jim_Johnson_8-12-2014(7).txt
-a--- 7/11/2014 4:02 PM 0 Test_Jim_Johnson_8-12-2014(8).txt
-a--- 7/11/2014 4:02 PM 0 Test_Jim_Johnson_8-12-2014(9).txt
-a--- 7/11/2014 4:02 PM 0 Test_Jim_Johnson_8-12-2014.txt