Powershell脚本使用一个函数

时间:2014-05-08 18:51:12

标签: function powershell delete-file

我需要创建一个脚本来删除在单独的文本文件中提供的超过x天数的文件夹。 txt文件的格式在评论部分给出。 我需要弄清楚为什么函数没有加载;我收到以下错误:

clean:术语“clean”不会被识别为cmdlet,函数,脚本文件或的名称 可操作程序。检查名称的拼写,或者如果包含路径,请验证 路径是正确的,然后再试一次

请帮忙。这是我的剧本:

<#######################################################################
Use:  Enter UNC path of the folder and files that need to be deleted on 
        the path specified by $info variable
        Enter the entries in the txt file in the following format:
        "UNCPATH;DAYSTOKEEP;FILEEXTENSION"  
########################################################################>
CD C:\FileCleanup

@(
$info = get-content Directories.txt

foreach ($i in $info)
{
   $item = $i.split(";")
   if (Test-Path -Path ($item[0]) -ErrorAction SilentlyContinue)
   {
       #write-host "UNC:       " $item[0]
       #write-host "Days:      " $item[1]
       #write-host "Extension: " $item[2]
       clean $item[0] $item[1] $item[2]
       Write-Output ("cleaned: `""+$i)
   }
   else #Log the paths that are missing
   {Write-Output ("MISSING PATH `""+$i)}
}

)|Out-file -FilePath CleanedUpFiles.txt

function clean
{
param ([string]$Dir, [int]$Days, [string]$Extension)

$cutoff = (get-date).AddDays(-$Days)

    # Delete any files older than $limit

Get-ChildItem $Dir -Filter *.$Extension -Recurse| 
        ?{$_.LastWriteTime -lt $cutoff -and !$_.PSIsContainer}| remove-item

#Logging
    write-output "$Dir *.$Extension, Keeping $Days days worth of files"

    # Delete any empty directories left behind after deleting the old files.
    Get-ChildItem -Path $Dir -Recurse -Force | 
        Where-Object {$_.PSIsContainer -and (
            Get-ChildItem -Path $_.FullName -Recurse -Force |
        Where-Object { !$_.PSIsContainer }) -eq $null } |
        Remove-Item -Force -Recurse
}

1 个答案:

答案 0 :(得分:2)

您需要在使用之前定义清理功能,即在解释脚本如何工作的注释之下