gpt4 book ai didi

powershell - 使用 -Like 运算符

转载 作者:行者123 更新时间:2023-12-03 00:29:49 24 4
gpt4 key购买 nike

如果我们发现的目录名称中有“1970”,我需要修改我一直在处理的这个脚本以发送电子邮件警报。我正在尝试使用 -Like 运算符来完成此操作,但我无法使其正常工作。我不知道问题是我对运算符的使用,还是支票的放置,或者完全是其他什么。

一些注意事项:我已经编辑了电子邮件和我的 SMTP 服务器,但我可以确认这行代码确实可以自己运行。

这是我尝试过的:

$limit = (Get-Date).AddDays(0)
$logFile = "C:\STest\Log\log.txt"

#Throw a timestamp on the log file
Add-Content -Path $logFile "=======$(Get-Date)======="

#Get all of the paths for each camera
$paths = Get-ChildItem -Path "C:\Videos\" |Select-Object -ExpandProperty FullName

#for each path we found
foreach ($pa in $paths) {
# Delete directories older than the $limit.
$file = Get-ChildItem -Path $pa -Recurse -Force | Where-Object { $_.PSIsContainer -and $_.CreationTime -lt $limit }
$file | Remove-Item -Recurse -Force
$file | Select -Expand FullName | Out-File $logFile -append
if ($file.FullName -like '1970'){
Send-MailMessage -to "Joe <Joe@Joe.com>" -from "Tod <Tod@tod.com>" -subject "1970 Found" -body "Testing" -SmtpServer mySMTPserver
}
}

我也试过:
if($file -like "1970"){ } 

if ($file.FullName -like "1970"){ }

if ($file.FullName -like 1970) { }

最佳答案

-like是通配符运算符。要匹配字符串中任何位置的 '1970',您需要添加通配符 *两端的字符:

PS C:\> 'something 1970 somethingelse' -like '*1970*'
True

如果要匹配字符串开头的 '1970',请省略前导 * .
要匹配字符串末尾的 '1970',请省略尾随 * .

使用通配符 ?匹配任何单个字符的字符,以及 [n-m] 'globbing' 通配符语法以匹配一系列字符。

看:

Get-Help about_Wildcards



有关使用通配符匹配的更多信息。

从性能的角度来看,直接比较( -eq-ne-lt-gt)最快,其次是通配符匹配( -like-notlike)。正则表达式匹配( -match-notmatch )提供了最大的灵 active ,但也是最慢的。

关于powershell - 使用 -Like 运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26061486/

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