将参数传递给PowerShell脚本以用于Test-Path -include选项?

时间:2012-06-21 21:50:31

标签: 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

1 个答案:

答案 0 :(得分:1)

-Include上的

Test-Pathstring[]。您可能想要反映该定义:

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

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

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