Reputation: 1
I'm writing a PowerShell script that copies yesterdays logs and zips them. My issue is that I have a massive list of different folders that I need copied. I want to do something like GCI "L:\sites"
and take each folder and pipe them into a variable, so instead of a hard path I can use a variable such as $Path
. "L:\sites\$path\log"
and copy them each into their own L:\logTemp\$Path
. Then get the zipping part to zip each one of those folders separately.
Current script below:
Robocopy "l:\sites\TNSERVICE\log" "L:\LogTemp\TNSERVICE" /s /copy:DAT /Maxage:1
set-alias sz "$env:ProgramFiles\7-Zip\7z.exe"
$Date = Get-Date
$Date = $Date.adddays(-1)
$Date2Str = $Date.ToString("yyyMMdd")
sz a -mx=9 "L:\LogTEMP\TNSERVICE $Date2Str.zip" "L:\LogTEMP\TNSERVICE\*"
remove-item L:\LogTemp\TNSERVICE -recurse
Upvotes: 0
Views: 66
Reputation: 21
This looks like a job for foreach
.
Using what you stated above, it looks like what you need is:
# Get the list of directories (you could use a filter here to match a pattern)
$sites = Get-ChildItem L:\sites -Directory
# Loop through each object in $sites and perform a series of actions
foreach ($dir in $sites) {
# This is all your original code, I've just changed to use variables
Robocopy "$dir.Fullname\log" "L:\LogTemp\$dir.Name" /s /copy:DAT /Maxage:1
set-alias sz "$env:ProgramFiles\7-Zip\7z.exe"
$Date = Get-Date
$Date = $Date.adddays(-1)
$Date2Str = $Date.ToString("yyyMMdd")
sz a -mx=9 "L:\LogTEMP\$dir.Name $Date2Str.zip" "L:\LogTEMP\$dir.Name\*"
remove-item L:\LogTemp\$dir.Name -recurse
}
All I really did here was wrap a foreach loop around what you wrote, and replace some of the paths with variable names. If you run this, it should do everything in the foreach loop to each of the directory names returned from Get-ChildItem.
Upvotes: 1