如何将数组或列表作为参数传递给 PowerShell 函数? [英] How do I pass an array or list as a parameter to a PowerShell function?

查看:79
本文介绍了如何将数组或列表作为参数传递给 PowerShell 函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个 PowerShell 脚本来获取将在 30 天内过期的证书列表.脚本正在运行,但问题是应用和预服务器太多,我想尽量减少脚本代码.我的功能是:

I am writing a PowerShell script to get a list of certificates which are getting expired within 30 days. The script is working, but the problem is there are too many app and pres servers, and I want to minimize the script code. My function is:

function CheckCert($ComputerNames)
{
    $deadline = (Get-Date).AddDays($global:threshold) # Set deadline date
    Invoke-Command -ComputerName $ComputerNames { Dir Cert:\LocalMachine\My } |
        foreach {
            If ($_.NotAfter -le $deadline)
            {
                $_ | Select Issuer, Subject, NotAfter, @{Label="Expires In (Days)";Expression={($_.NotAfter - (Get-Date)).Days}}
            }
        }
}

我调用这个函数是这样的:

And I am calling this function like:

Switch ($xMenu1)
{
    1 {CheckCert -ComputerNames "CUKIRUNCSVR0242"}
    2 {CheckCert}
    3 {CheckCert}
    ...

我想传递诸如 serv1、serv2、serv3 之类的计算机名称,并且此服务器数量从 1 到 6 不等,具体取决于从菜单中选择的选项.**或我可以定义不同环境的服务器列表并将列表名称作为参数传递并修改我的 CheckCert 函数以遍历每个服务器并获取过期的证书详细信息吗?

I want to pass ComputerNames like serv1, serv2, serv3 and this number of servers cound vary from 1 to 6 depending upon the option selected from menu. **OR Can I define a list of servers of different envirinments and pass the list name as parameter and modify my CheckCert function to loop through for each server and get the expired certificate details?

Switch ($xMenu1)
{
    1 {CheckCert -ComputerNames CIT_envList}
    2 {CheckCert -ComputerNames SIT_envList}
    3 {CheckCert -ComputerNames Prod_envList}
    ...

他们的服务器列表类似于:

And their server lists are something like:

CIT_envList = serv1, serv2

SIT_envList = serv1, serv2, serv3,

PROD_envList = serv1, serv2, serv3, serv4

推荐答案

试试这个:

function CheckCert([string[]]$ComputerNames)
{
    $deadline = (Get-Date).AddDays($global:threshold) # Set deadline date
    foreach ($computer in $ComputerNames)
    {
        Invoke-Command -ComputerName $Computer { Dir Cert:\LocalMachine\My } |
        foreach {
            If ($_.NotAfter -le $deadline)
            {
                $_ | Select Issuer, Subject, NotAfter, @{N="Expires In (Days)";E={($_.NotAfter - (Get-Date)).Days}}
            }
        }
    }
}

这篇关于如何将数组或列表作为参数传递给 PowerShell 函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆