Reputation: 75
I am running a powershell script, with the following
Copy-Item -Path c:\Windows\Microsoft.NET\Framework\v2.0.50727\CONFIG\machine.config -Destination c:\Windows\Microsoft.NET\Framework\v2.0.50727\CONFIG\machine.orig
If the machine.orig already exists, how can i make it copy it to machine.orig1, and if that already exists, machine.orgin2?
Upvotes: 0
Views: 1543
Reputation: 120
If I may make a suggestion. Personally, I like the idea of a date/time stamp on the file rather than an incremental number. This way you know when the file was backed up, and you're far less likely to run into confusion over the file. Plus the script code is simpler.
Hope this helps.
$TimeStamp = get-date -f "MMddyyyyHHmmss"
$SourceFile = Dir c:\folder\file.txt
$DestinationFile = "{0}\{1}_{2}.{3}" -f $SourceFile.DirectoryName, $SourceFile.BaseName, $TimeStamp, $SourceFile.Extension
copy-Item $sourcefile $DestinationFile
Upvotes: 2
Reputation: 4233
#let us first define the destination path
$path = "R:\WorkindDirectory"
#name of the file
$file = "machine.orgin"
#let us list the number of the files which are similar to the $file that you are trying to create
$list = Get-ChildItem $path | select name | where name -match $file
#let us count the number of files which match the name $file
$a = ($list.name).count
#if such count of the files matching $file is less than 0 (which means such file dont exist)
if ($a -lt 1)
{
New-Item -Path $path -ItemType file -Name machine.orgin
}
#if such count of the files matching $file is greater than 0 (which means such/similar file exists)
if ($a -gt 0)
{
$file = $file+$a
New-Item -Path $path -ItemType file -Name $file
}
Note: This works assuming that the names of the files are in series. Let us say using this script you create machine.orgin
machine.orgin1
machine.orgin2
machine.orgin3
and later delete machine.orgin2 and re run the same script then it won't work.
Here i have given an example where i have tried to create a new file and you can safely modify the same to copy such file using copy-item
instead of new-item
Upvotes: 0