【问题标题】:PowerShell: trying to print path of file if string foundPowerShell:如果找到字符串,则尝试打印文件的路径
【发布时间】:2018-09-20 14:23:38
【问题描述】:

如果找到字符串,我正在尝试打印文件的路径。问题是如果 1 个文件不包含文件夹中的字符串,那么我不会得到任何输出。基本上,我正在查看证书纪元时间是否在到期后的 30 天内。以下是我的代码:

$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
}
}

【问题讨论】:

    标签: powershell if-statement foreach


    【解决方案1】:

    我做了几个假设,因为从您的问题中并不清楚发生了什么。重要的是,我假设您有一个目录树,其中包含一些文本文件,每个文件中都有一行,如下所示:

    expiry-epoch 1526854766.33933
    

    如果是这种情况,那么下面应该显示一些关于文件的有用信息:

    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 的文件的文件名,那么这个简化版本就可以做到这一点:

    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
                }
            }
    

    【讨论】:

    • 我正在寻找的是打印 $certexp 在今天的 30 天内的每个文件的文件名或至少路径。
    • @user2214162,你真的尝试过我原来的例子吗?它确实提供了这些信息(以及更多)。无论如何,我添加了一个仅提供文件名的简化版本。
    • 我很抱歉我不明白,为什么 ForEach-Object 中的 $threshold 是?
    • 它在ForEach-Object-Begin块中(注意ForEach-Object之后的两个{..}块),所以只处理一次,在ForEach-Object开始处理文件之前通过管道的对象。你可以把它移到上面一行,结果是一样的。在ForEach-Object help 中获取更多信息。
    猜你喜欢
    • 1970-01-01
    • 2012-11-04
    • 1970-01-01
    • 2012-06-21
    • 2018-07-27
    • 2014-03-30
    • 2021-10-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多