随着您的脚本和自动化库的增长,您所做的一切都将开始依赖于您的常用数据集。数据集如您的用户信息或服务器详细信息。想想您已经有多少脚本和工具,可以获得服务器列表,或者您提供服务器列表。可能是您为您的数据创建公共接口可能是时候了。

get-myserver

What you need is a get-myserver function. Put all your server list building logic into that function. Even if all it does is import a csv at first.

    function get-myserver
    {
        [cmdletbinding()]
        param()
        Import-CSV $PSScriptRoot\servers.csv
    }

Over time, you can add features to your function and all your future scripts will benefit from it. Adding a quick filter can make a big difference in your get-myserver function.

    function get-myserver
    {
        [cmdletbinding()]
        param($ComputerName = '*')

        Import-CSV $PSScriptRoot\servers.csv |
            Where ComputerName -like $ComputerName
    }

我甚至甚至可以为像这样的函数创建模块。

隐藏细节

These Get functions hide the implementation details from your other scripts. Your other scripts should not care where the data comes from, only that the Get functions provides the needed information.

这允许您更轻松地更改数据源。您可以轻松切换到使用Active Directory或SQL Server或Complex JSON文件。只要保持输出对象的形状相同,您的脚本可能永远可能永远不知道Anthing更改。

指尖数据

I find having simple get functions readily available makes all my other scripts easier to write. I can’t tell you how many times I reach for our get-myserver list in a given week.

We track additional metadata on our servers that is available in our version of get-myserver. We assign each server to a role and tag it with an environment in our data. By exposing that info in our get-myserver, we can do queries like this:

PS:> Get-MyServer -Environment Production -Role SQL

ComputerName Role Environment IP
------------ ---- ----------- --
MyServer01   SQL  Production  172.169.10.3
MyServer02   SQL  Production  172.169.10.4

或者执行反向并查询服务器以弄清楚它被分配的角色或环境。

PS:> Get-MyServer MyServer01

ComputerName Role Environment IP
------------ ---- ----------- --
MyServer01   SQL  Production  172.169.10.3

结束思想

My main example was servers, but this applies to all common sources of data. Having the data available makes it easier for you to use it too. Go make your get-myserver function and let me know how well it works for you.

在我最初发布这个后, 迈克谢泼德 与我分享一篇他写的文章,这一想法更深入了解更多例子: 现在是10点。你知道你的服务器在哪里吗?.