0

这是我第一次提出问题,所以请多多包涵。我通过编写一些基本的维护脚本来自学powershell。我的问题是关于我正在编写的清理脚本,它接受参数来确定要删除的目标目录和文件。

问题:

该脚本接受一个可选参数,用于处理文件删除时要查找的文件扩展名列表。我正在尝试在实际运行删除之前测试文件是否存在。我使用带有 –include 参数的 test-path 在 ValidateScript 块中运行检查。如果我传入一个文件扩展名或没有文件扩展名,它会起作用,但是当我尝试传入多个文件扩展名时,它会失败。

我尝试在脚本内的代码上使用以下变体:

[ValidateScript({ Test-Path $targetDirChk  -include $_ })]

[ValidateScript({ Test-Path $targetDirChk  -include "$_" })]

[ValidateScript({ Test-Path $targetDirChk  -include ‘$_’ })]

对于上述每种可能性,我已经使用以下变体从命令行运行了多扩展名文件列表的脚本:

& G:\batch\DeleteFilesByDate.ps1 30 G:\log  *.log,*.ext

& G:\batch\DeleteFilesByDate.ps1 30 G:\log  “*.log, *.ext”

& G:\batch\DeleteFilesByDate.ps1 30 G:\log  ‘*.log, *.ext’

错误信息示例:

chkParams : Cannot validate argument on parameter 'includeList'. The " Test-Path $targetDirChk -include "$_" " validation script for the argument with value "*.log, *.ext" did not return true. Determine why the validation script failed and then try the command again.
At G:\batch\DeleteFilesByDate.ps1:81 char:10
+ chkParams <<<<  @args
    + CategoryInfo          : InvalidData: (:) [chkParams], ParameterBindingValidationException
    + FullyQualifiedErrorId : ParameterArgumentValidationError,chkParams

完整的脚本如下。我还没有添加删除文件的实际代码,因为我仍在努力接受和验证传入的参数。

我已经搜索了 google 和 stackoverflow,但我还没有找到解决这个特定问题的方法。我假设我的代码有问题,或者有更好的方法来完成我想做的事情。

注意:我应该提到,我还尝试在脚本之外运行具有多个文件扩展名的测试路径,没有任何问题:

PS G:\batch\powershell> test-path G:\log\* -include *.log

True

PS G:\batch\powershell> test-path G:\log\* -include *.log, *.ext

True

脚本:

# Check that the proper number of arguments have been supplied and if not provide usage statement.
# The first two arguments are required and the third is optional.
if ($args.Length -lt 2 -or $args.Length -gt 3 ){
    #Get the name of the script currently executing.
    $ScriptName = $MyInvocation.MyCommand.Name
    $ScriptInstruction = @"

    usage: $ScriptName <Number of Days> <Directory> [File Extensions]

    This script deletes files from a given directory based on the file date.

    Required Paramaters:

    <Number of Days>:   
    This is an integer representing the number of days worth of files 
    that should be kept. Anything older than <Number of Days> will be deleted.

    <Directory>:        
    This is the full path to the target folder.

    Optional Paramaters:

    [File Extensions]   
    This is the set of file extensions that will be targeted for processing. 
    If nothing is passed all files will be processed.
"@  
    write-output $ScriptInstruction
    break
}
#Function to validate arguments passed in.
function chkParams()
{
    Param(
    [Parameter(Mandatory=$true,
        HelpMessage="Enter a valid number of days between 1 and 999")]

    #Ensure the value passed is between 1 and 999.
    #[ValidatePattern({^[1-9][0-9]{0,2}$})]
    [ValidateRange(1,999)]
    [Int]
    $numberOfDays,

    [Parameter(Mandatory=$true,
        HelpMessage="Enter a valid target directory.")]
    #Check that the target directory exists.
    [ValidateScript({Test-Path $_ -PathType 'Container'})] 
    [String]
    $targetDirectory,   

    [Parameter(Mandatory=$false,
        HelpMessage="Enter the list of file extensions.")]  
    #If the parameter is passed, check that files with the passed extension(s) exist.   
    [ValidateScript({ Test-Path $targetDirChk -include "$_" })]
    [String]
    $includeList
    )
    #If no extensions are passed check to see if any files exist in the directory.
    if (! $includeList ){
        $testResult = Test-path $targetDirChk
        if (! $testResult ){
            write-output "No files found in $targetDirectory"
            exit
        }
    } 
}
#
if ($args[1].EndsWith('\')){
    $targetDirChk = $args[1] + '*'
} else {
    $targetDirChk = $args[1] + '\*'
}       
chkParams @args
4

1 回答 1

1

-IncludeonTest-Path是一个string[]。您可能想反映该定义:

[ValidateScript({ Test-Path $targetDirChk -include $_ })]
[String[]]
$includeList

并从那里删除,""因为它们将强制参数为字符串,从而尝试匹配看起来像`foo.log blah.ext.

您还必须在调用函数时在该参数周围放置括号或删除空格。

于 2012-06-21T21:59:01.070 回答