【发布时间】:2017-03-17 08:47:50
【问题描述】:
我得到一个“路径无效”,即使它是有效的。我用自己的用户运行它,我可以浏览文件夹并删除文件夹中的文件。但是当我运行我的代码时,我得到“路径无效”。我也尝试在管理控制台中运行它。难道我做错了什么? 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
}
}
【问题讨论】:
标签: powershell