0

I have written the following script using a post on this forum. The script deletes the files which are older than 15 days:

cls
$servers = Get-Content server.txt
$limit = (Get-Date).AddDays(-15)
$path = "E:\CheckDBOutput"

ForEach ($line in $servers)
{
  Invoke-Command -cn $line -ScriptBlock {
    Get-ChildItem -Path $path -Recurse -Force | Where-Object {
      !$_.PSIsContainer -and $_.CreationTime -lt $limit
    } | Remove-Item -Force
  }
}

The script is executing fine, but no files are getting deleted.

Ansgar Wiechers
  • 193,178
  • 25
  • 254
  • 328
Lilly123
  • 330
  • 1
  • 2
  • 9
  • 2
    possible duplicate of [Invoke-command -ArgumentList parameter syntax](http://stackoverflow.com/questions/23761109/invoke-command-argumentlist-parameter-syntax). You need to pass your variables as arguments to the script block – Matt Jan 25 '15 at 04:25

2 Answers2

0

As already mentioned in the comments, you need to pass the parameters to use inside the scriptblock as arguments to the -ArgumentList parameter:

$RemoveOldFiles = {
  param(
    [string]$path,
    [datetime]$limit
  )

  Get-ChildItem -Path $path -Recurse -Force | Where-Object {
    !$_.PSIsContainer -and $_.CreationTime -lt $limit
    } | Remove-Item -Force
}

$servers = Get-Content server.txt
$limit = (Get-Date).AddDays(-15)
$path = "E:\CheckDBOutput"

ForEach ($line in $servers)
{
  Invoke-Command -cn $line -ScriptBlock $RemoveOldFiles -ArgumentList $path,$limit
}
Mathias R. Jessen
  • 157,619
  • 12
  • 148
  • 206
0

Remove-Item does not exist in PowerShell version 1.0 - make sure your destination servers have v2.0 or better installed.