测试路径,路径无效

时间:2017-03-17 08:47:50

标签: powershell

我得到“路径无效”,即使它有效。我用我自己的用户运行它,我可以浏览文件夹并删除文件夹中的文件。但是当我运行我的代码时,我得到“路径无效”。我也尝试在管理控制台中运行它。难道我做错了什么? Powershell版本:4

param (  
    $rootPath = "$env:ProgramFiles\NetApp\SnapManager for Exchange\Report\",
    $paths = ("Debug [11EXS05]\","Backup [11EXS05]\"),
    $wildCard = "*.txt",
    $daysToKeep = "14"
)

#define LastWriteTime parameter based on $daysToKeep
$now = Get-Date
$lastWrite = $now.AddDays(-$daysToKeep)

#Loop through each path in paths
foreach($path in $paths)
{
    $currentPath = Join-Path -Path $rootPath $path    
    if(Test-Path $currentPath)
    {
        #get all the files that has LastWriteTime less than today minus $daysToKeep, then delete those files, pipe output to screen
        Get-ChildItem $currentPath `
            -Include $wildCard -Recurse | `
            Where {$_.LastWriteTime -le "$lastWrite"} | foreach{ "Removing file $($_.FullName)"; Remove-Item $_}
    }
    else
    {
        Write-Host ($currentPath + " is not valid") -ForegroundColor Red
    }

}

编辑,解决方案:

必须像下面的答案一样修复[]。而且,我必须将$currentPath添加到Remove-Item命令,完整脚本:

param (  
    $rootPath = "$env:ProgramFiles\NetApp\SnapManager for Exchange\Report\",
    $paths = ('Debug `[11EXS05`]\','Backup `[11EXS05`]\'),
    $wildCard = "*.txt",
    $daysToKeep = "17"
)

#define LastWriteTime parameter based on $daysToKeep
$lastWrite = (Get-Date).Date.AddDays(-$daysToKeep)

#Loop through each path in paths
foreach($path in $paths)
{
    $currentPath = Join-Path -path $rootPath $path

    if(Test-Path $currentPath)
    {
        #get all the files that has LastWriteTime less than today minus $daysToKeep, then delete those files, pipe output to screen
        Get-ChildItem $currentPath `
            -Filter $wildCard -Recurse | `
            Where {$_.LastWriteTime -le "$lastWrite"} | foreach{ "Removing file $($_.FullName)"; Remove-Item ($currentPath + "\" + $_) -Force}        

    }
    else
    {
        Write-Host ($currentPath + " is not valid") -ForegroundColor Red
    }
}

2 个答案:

答案 0 :(得分:2)

文件夹名称中的方括号会给您一个问题。见https://stackoverflow.com/a/21008352/1001100。你需要在每个方括号前加一个反引号。由于PowerShell使用反引号作为转义字符,因此如果要使用双引号字符串,则需要两个反引号。

将第二行更改为:

$paths = ("Debug ``[11EXS05``]\","Backup ``[11EXS05``]\"),

或者,如果你想切换到单引号字符串:

$paths = ('Debug `[11EXS05`]\','Backup `[11EXS05`]\'),

它会起作用。

答案 1 :(得分:0)

问题可能是$ RootPath

$rootPath = "$env:ProgramFiles\NetApp\SnapManager for Exchange\Report\",

$ env:或“$ env:HOMEDRIVE”+“\ ProgramFiles \ NetApp \ SnapManager for Exchange \ Report”

$ env:来电不正确..

(OR)

$paths = ('Debug `[11EXS05`]\','Backup `[11EXS05`]\')