gpt4 book ai didi

powershell - 在PowerShell脚本中测试路径的位置

转载 作者:行者123 更新时间:2023-12-03 09:04:15 38 4
gpt4 key购买 nike

我有一个脚本,当文件即将达到其最大大小时会发送电子邮件。

问题是,当在给定路径下找不到文件时,我无法对脚本应执行的操作进行验证检查。

我知道我应该实现:

if(!(Test-Path $item.Path))
{
"The file " + $item.Name + " is not found! <br />"
}

但是我不知道将其准确放置在哪里(因为到处都是错误)。

代码:

我首先从配置文件中检索文件:
$list = foreach ($file in $files)
{
$f = Get-Item $file.Path
New-Object -Type PSObject -Property @{

Name = $f.Name
Path = $file.Path
Size = ($f.Length/$byteSize)
}
}

然后我遍历文件列表并检查它们的大小:
foreach ($item in $list)
{
if($item.Size -gt $item.TriggerSize -And (Test-Path $item.Path))
{
#Write-Host $item.Name "Warning! File has reached it's max limit ("$item.Size.ToString(".00")"), The max size is" $item.MaxSize". The trigger size is: " $item.TriggerSize "`r`n"

$body +=

"The file " + $item.Name + " is reaching his max size!
<br /> Current size: <b>"+$item.Size.ToString(".00") + " " + $byteSize.Substring(1) + "</b>" +
"<br /> Maximum size: " + $item.MaxSize + " " + $byteSize.Substring(1) + "<br /><br />"
}
}

我尝试在以下位置执行错误检查:
$list = foreach ($file in $files)
{

if(!(Test-Path $item.Path))
{
"The file " + $item.Name + " is not found! <br />"
}

$f = Get-Item $file.Path
New-Object -Type PSObject -Property @{

Name = $f.Name
Path = $file.Path
Size = ($f.Length/$byteSize)
}
}

和这里
foreach ($item in $list)
{
if($item.Size -gt $item.TriggerSize -And (Test-Path $item.Path))
{
#Write-Host $item.Name "Warning! File has reached it's max limit ("$item.Size.ToString(".00")"), The max size is" $item.MaxSize". The trigger size is: " $item.TriggerSize "`r`n"

$body +=

"The file " + $item.Name + " is reaching his max size!
<br /> Current size: <b>"+$item.Size.ToString(".00") + " " + $byteSize.Substring(1) + "</b>" +
"<br /> Maximum size: " + $item.MaxSize + " " + $byteSize.Substring(1) + "<br /><br />"
}

if(!(Test-Path $item.Path))
{
"The file " + $item.Name + " is not found! <br />"
}
}

但是我不断收到错误消息,它是在 Get-Item上找不到文件:

我故意使用错误路径编写的文件的名称:
file123.exe

错误(在 if(!(Test-Path $file.path))行:

Get-Item : Cannot find path 'file123.exe' because it does not exist.

最佳答案

您正在尝试错误处理,但是您的代码仍然将控制权传递给了主逻辑。相反,您应该开发控制流,以便仅当Get-Item返回true时才调用Test-Path

$list = foreach ($file in $files)
{
if (Test-Path $file.Path) {

$f = Get-Item $file.Path
New-Object -Type PSObject -Property @{

Name = $f.Name
Path = $f.Path
Size = ($f.Length/$byteSize)
}
} else {
"The file " + $file.path + " is not found! <br />"
}
}

最后, 证明您的代码!您已经测试了 $item.path,但是可以访问 $file.path。给定您的foreach循环,两个地方都应该有 $file.path

关于powershell - 在PowerShell脚本中测试路径的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43365154/

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