gpt4 book ai didi

powershell - 测试路径,路径无效

转载 作者:行者123 更新时间:2023-12-02 23:40:56 26 4
gpt4 key购买 nike

我得到一个“路径无效”,即使它是有效的。我用自己的用户运行它,我可以浏览文件夹并删除文件夹中的文件。但是,当我运行我的代码时,我得到“路径无效”。我也尝试过在管理控制台中运行它。难道我做错了什么?
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
}
}

最佳答案

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

将第二行更改为此:

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

或者,如果要切换到单引号字符串,请执行以下操作:
$paths = ('Debug `[11EXS05`]\','Backup `[11EXS05`]\'),

它会工作。

关于powershell - 测试路径,路径无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42852916/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com