PowerShell:如果找到字符串,则尝试打印文件的路径 [英] PowerShell: trying to print path of file if string found
问题描述
如果找到字符串,我正在尝试打印文件的路径.问题是,如果1个文件的文件夹中不包含字符串,那么我没有任何输出.基本上,我希望查看证书的有效期是否在有效期的30天内.下面是我的代码:
I am trying to print the path of a file if string is found. Problem is if 1 file does not contain the string in a folder then I do not get any output. Basically I am looking to see if a certificate epoch-time is within 30 days of expiration. Below is my code:
$c = Get-Date (Get-Date).ToUniversalTime() -UFormat %s
$epochtimes=[math]::Round($c)
$d = get-childitem C:\scripts\PALO\* -recurse | Select-String -pattern
"expiry-epoch"
$e=$d -split "epoch"
$certtime=[double] $e[1]
$certexp = $certtime - 2592000
ForEach ($i in $certexp){
If ($certexp -le $epochtime) {
Write-Host $i
}
}
推荐答案
我做出了两个假设,因为您的问题尚不清楚.重要的是,我假设您有一个目录树,其中包含一些文本文件,每个文本文件中都带有一行,如下所示:
I've made a couple of assumptions since it isn't totally clear from your question what is going on. Importantly, I've assumed you have a directory tree containing some text files each with a line in it like this:
expiry-epoch 1526854766.33933
如果是这种情况,则以下内容应显示一些有关文件的有用信息:
If this is the case, then the following should display some useful information about the files:
Get-ChildItem -Path "C:\test" -File -Recurse |
ForEach-Object {$threshold = [Math]::Round((Get-Date (Get-Date).ToUniversalTime() -UFormat %s)) + 2592000} {
$certEpochTime = ([double]($_ | Select-String -Pattern "^expiry-epoch (\d+\.\d+)$").Matches.Groups[1].Value)
$certExpiryTime = (Get-Date "1/1/1970").AddSeconds($certEpochTime)
New-Object -TypeName PsCustomObject|
Add-Member -MemberType NoteProperty -Name ExpiresSoon -Value ($certEpochTime -le $threshold) -PassThru |
Add-Member -MemberType NoteProperty -Name DaysUntilExpiry -Value ([Math]::Round(($certExpiryTime - (Get-Date)).TotalDays)) -PassThru |
Add-Member -MemberType NoteProperty -Name CertExpiryTime -Value $certExpiryTime -PassThru |
Add-Member -MemberType NoteProperty -Name CertEpochTime -Value $certEpochTime -PassThru |
Add-Member -MemberType NoteProperty -Name FilePath -Value $_.FullName -PassThru
} | Format-Table -AutoSize
如果您只需要30天之内带有 expiry-epoch
的所有文件的文件名,那么此简化版本将做到这一点:
If all you need is the filename of any files with an expiry-epoch
within 30 days, then this simplified version will do that:
Get-ChildItem -Path "C:\test" -File -Recurse |
ForEach-Object {$threshold = [Math]::Round((Get-Date (Get-Date).ToUniversalTime() -UFormat %s)) + 2592000} {
$certEpochTime = ([double]($_ | Select-String -Pattern "^expiry-epoch (\d+\.\d+)$").Matches.Groups[1].Value)
if($certEpochTime -le $threshold)
{
$_.FullName
}
}
这篇关于PowerShell:如果找到字符串,则尝试打印文件的路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!