Sv3n
Sv3n

Reputation: 69

Need a loop for computer names on shares

I have this embarrassing .bat:

pushd \\computer00081\d    
rmdir "z:\dig_dok" /s /q   
mkdir . "dig_doc"   
cd dig_doc  
xcopy "C:\Users\myUser\Desktop\dig_doc" .\ /E  
C:  
net use z: /delete /y

The computer names on my network share the same name pattern: computer00081, computer00082, computer00083... and so on. They have the same file/folder structure in the "d" share. How can I create a loop for the computer names from let's say computer00001 to computer00200 and do the same for all of them? Maybe do it for a computers.txt list? Or loop them from the hosts file. Thanks in advance! You rock!

Upvotes: 0

Views: 274

Answers (2)

lit
lit

Reputation: 16236

While this can be dome in cmd, it is much easier in powershell. The for loop controls the system numbers; from 1 to 9 in this case. Change those to whatever you need. When you are happy with what would be done, remove the -WhatIf from the Remove-Item and `Copy-Item commands.

=== Do-CopyStuff.ps1

$DupDir = 'dig_doc'
$SourceDir = Join-Path -Path (Join-Path -Path $Env:USERPROFILE -ChildPath 'Desktop') -ChildPath $DupDir
$SHARENAME = 'D'
for ($i = 1; $i -lt 10; $i++) {
    $DestinationDir = '\\COMPUTER' + '{0:d5}' -f @($i) + "\$SHARENAME"
    if (Test-Path -Path $DestinationDir) {
        Remove-Item -Recurse -Force -Path $DestinationDir -WhatIf
        Copy-Item -Recurse -Path $SourceDir -Destination $DestinationDir -WhatIf
    }
}

If you must run this from cmd.exe, this can be used.

powershell -NoLogo -NoProfile -File ".\Do-CopyStuff.ps1"

Upvotes: 1

Grant Lindsey
Grant Lindsey

Reputation: 105

Check out this answer: https://stackoverflow.com/a/8086103/8954127

Looks like string variables are naturally iterable in cmd if there are common delimiters available (like ,). If you're able to build a comma-delimited string of the computer names, you can loop through them executing on each host.

This answer is incomplete but I think this should spur you in the right direction.

set "compnames="

:: needs extra logic to pad missing leading zeros
for /L %%i in (1,1,20) do call set "compnames=%compnames%,computername00%%i"

:: logic to remove any leading comma or space

for %%i in ( %compnames% ) do (
    :: do work with each computer name
    echo %%i
)

A few more references:

Upvotes: 0

Related Questions