Want to win a PS4? Go Premium and enter to win our High-Tech Treats giveaway. Enter to Win

x
?
Solved

PowerShell, deleting files from multiple servers

Posted on 2016-11-03
12
Medium Priority
?
147 Views
Last Modified: 2016-11-11
Hello experts. So I have this script below that deletes files from multiple servers > x days old. However, I am new to powershell and feel there is a better way to do this. For example I would like to use servers listed in a file. Below this script is the new one i am working on.
----------------------------------------------------------------------------------------------------------------------------------------------------
$limit = (Get-Date).AddDays(-15)
$path10 = "\\server10\C$\Users\dax\AppData\Local\Temp"
$path11 = "\\server11\C$\Users\dax\AppData\Local\Temp"
$path12 = "\\server12\C$\Users\dax\AppData\Local\Temp"
$path13 = "\\server13\C$\Users\dax\AppData\Local\Temp"
$path14 = "\\server14\C$\Users\dax\AppData\Local\Temp"

# Delete files older than the $limit.
Get-ChildItem -Path $path10 -Force | Where-Object { !$_.PSIsContainer -and $_.CreationTime -lt $limit } | Remove-Item -Force
Get-ChildItem -Path $path11 -Force | Where-Object { !$_.PSIsContainer -and $_.CreationTime -lt $limit } | Remove-Item -Force
Get-ChildItem -Path $path12 -Force | Where-Object { !$_.PSIsContainer -and $_.CreationTime -lt $limit } | Remove-Item -Force
Get-ChildItem -Path $path13 -Force | Where-Object { !$_.PSIsContainer -and $_.CreationTime -lt $limit } | Remove-Item -Force
Get-ChildItem -Path $path14 -Force | Where-Object { !$_.PSIsContainer -and $_.CreationTime -lt $limit } | Remove-Item -Force
----------------------------------------------------------------------------------------------------------------------------------------------------

here is the new script i am attempting
----------------------------------------------------------------------------------------------------------------------------------------------------
$Servers = Get-Content D:\Scripts\servers.txt
$limit = (Get-Date).AddDays(-15)
$path = "C$\Users\dax\AppData\Local\Temp"

Foreach ($Computer in $Computers)
{
    Invoke-Command -ComputerName $Servers {Get-ChildItem -Path $path10 -Force | Where-Object { !$_.PSIsContainer -and $_.CreationTime -lt $limit } | Remove-Item -Force -WhatIf}
}

Can you please help me determine what i am doing wrong? Or let me know if there is a better way altogether to compete this task. Thank you in advanced.
0
Comment
Question by:jacobJL
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 7
  • 5
12 Comments
 
LVL 16

Expert Comment

by:Jason Crawford
ID: 41872818
Try this:

Invoke-Command -ComputerName (Get-Content servers.txt) -ScriptBlock {Get-ChildItem c:\Users\dax\AppData\Local\Temp -Directory | Remove-Item -Force}

Open in new window

0
 
LVL 16

Expert Comment

by:Jason Crawford
ID: 41872822
The benefit of the method employed in the one-liner above is it will "fan" across all servers at the same time instead of one after the other the way you would see in a foreach loop.
0
 
LVL 16

Expert Comment

by:Jason Crawford
ID: 41872824
Hold up I forgot to specify the age limit.  Don't make my same mistake and just add that portion into the script block.
0
Problems using Powershell and Active Directory?

Managing Active Directory does not always have to be complicated.  If you are spending more time trying instead of doing, then it's time to look at something else. For nearly 20 years, AD admins around the world have used one tool for day-to-day AD management: Hyena. Discover why

 

Author Comment

by:jacobJL
ID: 41872871
Jason thank you for quick response.

I am not sure what you mean by this "Hold up I forgot to specify the age limit.  Don't make my same mistake and just add that portion into the script block."
0
 
LVL 16

Expert Comment

by:Jason Crawford
ID: 41872877
Yea sorry I'm doing too many things at once.  Here is a much cleaner option (requires Powershell 3.0 or above):
Invoke-Command -ComputerName (Get-Content servers.txt) -ScriptBlock {
  $date = (Get-Date).AddDays(-3)
  Set-Location 'c:\Users\dax\AppData\Local\Temp'
  Get-ChildItem -Directory | Where-Object {$_.LastWriteTime -lt $date} | Remove-Item -Force
}

Open in new window

0
 

Author Comment

by:jacobJL
ID: 41872899
I see. I am getting an error.
"Cannot find path 'C:\Windows\system32\servers.txt' because it does not exist."
Not sure why its looking on c when i specify D:\Scripts\servers.txt

This is what i have
$Servers = Get-Content D:\Scripts\servers.txt

Invoke-Command -ComputerName (Get-Content servers.txt) -ScriptBlock {
  $date = (Get-Date).AddDays(-10)
  Set-Location 'c:\Users\dax\AppData\Local\Temp'
  Get-ChildItem -Directory | Where-Object {$_.LastWriteTime -lt $date} | Remove-Item -Force -WhatIf
}

Get-Content : Cannot find path 'C:\Windows\system32\servers.txt' because it does not exist.
At line:5 char:31
+ Invoke-Command -ComputerName (Get-Content servers.txt) -ScriptBlock {
+                               ~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (C:\Windows\system32\servers.txt:String) [Get-Content], ItemNotFoundException
    + FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.GetContentCommand
 
Invoke-Command : Cannot validate argument on parameter 'ComputerName'. The argument is null or empty. Provide an argument that is not null or empty, and then try the command again.
At line:5 char:30
+ Invoke-Command -ComputerName (Get-Content servers.txt) -ScriptBlock {
+                              ~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidData: (:) [Invoke-Command], ParameterBindingValidationException
    + FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.PowerShell.Commands.InvokeCommandCommand
0
 
LVL 16

Expert Comment

by:Jason Crawford
ID: 41872905
Ok try this:

Invoke-Command -ComputerName (Get-Content 'D:\Scripts\servers.txt') -ScriptBlock {
  $date = (Get-Date).AddDays(-3)
  Set-Location 'c:\Users\dax\AppData\Local\Temp'
  Get-ChildItem -Directory | Where-Object {$_.LastWriteTime -lt $date} | Remove-Item -Force
}

Open in new window

0
 

Author Comment

by:jacobJL
ID: 41872954
Hmm, no error but It's not removing anything.  is "Get-ChildItem -Directory" correct?

if i run:
 Invoke-Command -ComputerName (Get-Content 'D:\NCR\DAX\Scripts\servers.txt') -ScriptBlock {
  $date = (Get-Date).AddDays(-10)
  Set-Location 'c:\Users\dax\AppData\Local\Temp'
  Get-ChildItem -Directory}

it returns each sub-directory in that location on each server. But doesn't return the files in directory
0
 
LVL 16

Accepted Solution

by:
Jason Crawford earned 2000 total points
ID: 41872960
My fault I didn't see the exclamation point in your script.  Ok last time hopefully :)

Invoke-Command -ComputerName (Get-Content 'D:\Scripts\servers.txt') -ScriptBlock {
  $date = (Get-Date).AddDays(-3)
  Set-Location 'c:\Users\dax\AppData\Local\Temp'
  Get-ChildItem -File | Where-Object {$_.LastWriteTime -lt $date} | Remove-Item -Force
}

Open in new window

0
 

Author Closing Comment

by:jacobJL
ID: 41872979
Bingo. Thank you so much! I learned a lot from this. I'll have to research -scriptblock now and include that in some of my other scripts. That's awesome. Really liking how powerful powershell is.
0
 

Author Comment

by:jacobJL
ID: 41883925
Hey Jason if you are interested I opened another question in relation to this one.
https://www.experts-exchange.com/questions/28982543/PowerShell-deleting-files-using-last-modified-and-last-accessed.html
Thanks
0

Featured Post

Q2 2017 - Latest Malware & Internet Attacks

WatchGuard’s Threat Lab is a group of dedicated threat researchers committed to helping you stay ahead of the bad guys by providing in-depth analysis of the top security threats to your network.  Check out our latest Quarterly Internet Security Report!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

The Nano Server Image Builder helps you create a custom Nano Server image and bootable USB media with the aid of a graphical interface. Based on the inputs you provide, it generates images for deployment and creates reusable PowerShell scripts that …
Auditing domain password hashes is a commonly overlooked but critical requirement to ensuring secure passwords practices are followed. Methods exist to extract hashes directly for a live domain however this article describes a process to extract u…
Exchange organizations may use the Journaling Agent of the Transport Service to archive messages going through Exchange. However, if the Transport Service is integrated with some email content management application (such as an antispam), the admini…
Have you created a query with information for a calendar? ... and then, abra-cadabra, the calendar is done?! I am going to show you how to make that happen. Visualize your data!  ... really see it To use the code to create a calendar from a q…

604 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question