文件未从远程服务器中删除

Files not getting deleted from remote servers

我在这个论坛上使用 post 编写了以下脚本。该脚本删除超过 15 天的文件:

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
  }
}

脚本执行正常,但没有文件被删除。

如评论中所述,您需要将要在脚本块内使用的参数作为参数传递给 -ArgumentList 参数:

$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
}

Remove-Item 在 PowerShell 1.0 版中不存在 - 请确保您的目标服务器安装了 v2.0 或更高版本。