【问题标题】:Can't figure out how to edit powershell script不知道如何编辑powershell脚本
【发布时间】:2017-11-23 02:35:14
【问题描述】:

此脚本收集有关本地计算机证书的信息并显示证书过期的日期(以 JSON 格式)。

{ "{#CERTINFO}" : "@{Expires in (Days)=8074}" }

我只需要8074(天)并且不知道如何编辑这个脚本。

$cert_ = get-childitem cert:LocalMAchine -recurse |
where-object {$_.NotAfter -gt (get-date)} |
select @{Name="Expires in (Days)";Expression={($_.NotAfter).subtract([DateTime]::Now).days}} |
Sort "Expires in (Days)"

write-host "{"
write-host " `"data`":[`n"
$idx = 1
foreach ($cert_arr in $cert_ )
{
if ($idx -lt $cert_.Count)

{
$line= "{ `"{#CERTINFO}`" : `"" + $cert_arr + "`" },"  
write-host $line 
}
elseif ($idx -ge $cert_.Count)
{
$line= "{ `"{#CERTINFO}`" : `"" + $cert_arr + "`" }"
write-host $line 
}
$idx++;
}
write-host
write-host " ]"
write-host "}"

【问题讨论】:

  • 这是一种非常糟糕的 PowerShell 编写方式。也许您应该简单地重新开始(并在此过程中学习一些有关该语言的知识)。
  • 你尝试了什么?从删除所有 write-host 语句开始。
  • 是的,我明白了:>
  • 当我将选择更改为选择 @{Name=" ";Expression={($_.NotAfter).subtract([DateTime]::Now).days}} 结果是:{ "{ #CERTINFO}" : "@{ =8074}" },
  • 我需要 write-host 来获取 Zabbix PS 的 JSON 格式 C:\Scripts> C:\Scripts\cert_check.ps1 { "data":[ { "{#CERTINFO}" : "@{过期(天)=8074}" } ] }

标签: powershell


【解决方案1】:

我会尝试:

function Get-CertInfo
{

    $cert_ = get-childitem cert:LocalMAchine -recurse | where-object {$_.NotAfter -gt (get-date)} | select @{Name="Expires in (Days)";Expression={($_.NotAfter).subtract([DateTime]::Now).days}} | Sort "Expires in (Days)"

    $data = @()

    foreach($c in $cert_)
    {
        $entry = [PSObject]@{"#CERTINFO"="$c"}

        $data += $entry
    }

    $certInfor = [PSObject]@{"data"=$data}

    $certInfor | ConvertTo-Json
}

生成:

{
"data":  [
             {
                 "#CERTINFO":  "@{Expires in (Days)=221}"
             },
             {
                 "#CERTINFO":  "@{Expires in (Days)=272}"
             }
         ]
}

希望对您有所帮助。

【讨论】:

    猜你喜欢
    • 2016-09-25
    • 2020-06-24
    • 2020-06-26
    • 2020-04-01
    • 1970-01-01
    • 2010-10-27
    • 1970-01-01
    • 2010-11-29
    • 2011-10-15
    相关资源
    最近更新 更多