I have a script that copies the files from one server to another. I have basically 3 different server locations, that I want to copy from , and create on another server, a folder for each of the location from the source and the contents inside it. I made that, but I declared a variable for each source and each folder/destination. I want to create one variable, and from that it should automatically get each location of the source, and copy everything in the correct location. Would defining $server= "\path1 , \path2, \path3 " do it and it would go into a foreach loop? and go through each part of the path and copy and paste? If so, how can I define the destination if I have 1 folder with 3 subfolders each corresponding to one source. for example \path1 should alwasy put items in the path1destination , \path2 should always put items in the path2destination and so on. basically I want somehow to correlate that for each source path to have a specific path destination and everything should use as less variables as possible.
Anyone can provide and ideas on how to tackle this ? My code works but I had to define $path1 , $path2 , $path3 and so on, and then go for a loop on each, which is great but I need to make it clean and less lines of code .
$server1 = "C:\Users\nicolae.calimanu\Documents\B\"
$server2 = "C:\Users\nicolae.calimanu\Documents\A\" # UNC Path.
$datetime = Get-Date -Format "MMddyyyy-HHmmss"
$server3 = "C:\Users\nicolae.calimanu\Documents\C\" # UNC Path.
foreach ($server1 in gci $server1 -recurse)
{
Copy-Item -Path $server1.FullName -Destination $server2
}
ForEach ( $server2 in $server2 ) {
$curDateTime = Get-Date -Format yyyyMMdd-HHmmss
Get-ChildItem $server2 -Recurse |
Rename-Item -NewName {$_.Basename + '_' + $curDateTime + $_.Extension }
}
foreach ($server2 in gci $server2 -Recurse)
{
Move-Item -path $server2 -destination "C:\Users\nicolae.calimanu\Documents\C"
}
foreach ($server1 in gci $server1 -recurse)<<< is very strange. you REALLY should not use the same variable name like that. also, what is in the $Var at that point? file objects?foreach()loop, you do not have the benefit of the$_automatic variable as you would if you use aForEach-Object {}loop. In your case,$_.Basenamedoes not work. Also, you keep using the same variable for both the iterating variable and the collection to iterate through. I have tried to explain that to you earlier in your previous question. Please read about looping with eitherforeach(..)andForEach-Object{..}so you can see for yourself what you're doing wrong here.