powershell_我的PowerShell SwissKnife

powershell

以及如何制作自己的自定义商品 (and how to make your own custom one)

Originally published at https://mertsenel.tech on May 21, 2020.

最初于 2020年5月21日 https://mertsenel.tech 发布

Hi my name is Mert I’m a Cloud DevOps Engineer and in this post, I would like to talk about my PowerShell Swissknife functions(I’d like to call them) and how do I use them to make my life easier for my every day tasks. My hope is to inspire some, who are not already leveraging power of scripting and automation just because they can do things through a graphical user interface.

嗨,我叫Mert,我是Cloud DevOps工程师,在这篇文章中,我想谈谈我的PowerShell Swissknife函数(我想称呼它们)以及如何使用它们使我的生活更轻松日常任务。 我的希望是激发一些人,因为他们可以通过图形用户界面执行操作,因此他们尚未利用脚本和自动化功能。

创建您的自定义功能文件夹 (Create your custom functions folder)

First of all, you will need a folder to put all your custom script files. I keep them in under my user profile. Below is an example Microsoft.PowerShell_profile.ps1 that I’m using right now.

首先,您将需要一个文件夹来放置所有自定义脚本文件。 我将它们保留在我的用户个人资料下。 下面是我现在正在使用的示例Microsoft.PowerShell_profile.ps1。

If you don’t know your profile files location, just type $profile in your Powershell Terminal and it should print out the location to you.

如果您不知道配置文件的位置,只需在Powershell Terminal中键入$ profile,它就会为您打印出该位置。

> $profile
> C:\Users\Mert\Documents\PowerShell\Microsoft.PowerShell_profile.ps1

Below is the content of my profile.ps1 file.It contains the code you need to add in order to import your custom functions and It also has the Powershell auto-complete goodies

以下是我的profile.ps1文件的内容,它包含您需要添加以导入自定义功能的代码,还具有Powershell自动完成功能

# Shows navigable menu of all options when hitting Tab
Set-PSReadlineKeyHandler -Key Tab -Function MenuComplete


# Autocompletion for arrow keys
Set-PSReadlineKeyHandler -Key UpArrow -Function HistorySearchBackward
Set-PSReadlineKeyHandler -Key DownArrow -Function HistorySearchForward


#Custom functions location
$Path = "C:\Users\Mert\source\MertPSFunctions\"
Get-ChildItem -Path $Path -Filter *.ps1 |ForEach-Object {
    . $_.FullName
}

功能 (Functions)

Get-MyPublicIPAddress.ps1 (Get-MyPublicIPAddress.ps1)

This function is a great oneliner for all purposes you would need your public IP address for. Most common scenario I have is to whitelist my client IP address temporarily while allowing an Azure resource.

对于需要公用IP地址的所有目的,此功能都是一个很好的选择。 我最常见的情况是在允许Azure资源的同时暂时将客户端IP地址列入白名单。

Even when you don’t need your Public IP Address in a programmatically, manual way of retrieving is also very difficult. You need to Google “What is My IP Address” and copy and paste the result, maybe even clear from HTML formatting.

即使您不需要以编程方式使用公用IP地址,手动检索方法也非常困难。 您需要使用Google“我的IP地址是什么”并复制并粘贴结果,甚至可以从HTML格式中清除该结果。

This little custom function helped me out a ton while doing my regular tasks. Enterprise level companies and their networks are not simple due to security perimeters, compliance schemes etc. So in a regular day, I might need to connect to corporate VPN whenever I need production access and then drop back out to gain more internet speed again. (We are working remotely due to COVID-19 as of writing this post)

这个小的自定义功能在执行常规任务时帮助了我很多。 由于安全范围,合规性方案等原因,企业级公司及其网络并不简单。因此,在日常情况下,每当需要生产访问权限时,我可能需要连接到公司VPN,然后退出以再次获得更高的Internet速度。 (由于撰写本文时,由于COVID-19,我们正在远程工作)

To add on top of this, I don’t get assigned same Public IP address due to our VPNs architecture which I don’t know and have no interest in knowing.

最重要的是,由于我们的VPN架构,我没有被分配相同的公共IP地址,我不知道,也没有兴趣。

Long story short, I need to know my Public IP Address quite often some days, so this is definitely a life saver.

长话短说,我需要几天经常知道我的公共IP地址,因此绝对可以节省生命。

function Get-PublicIPAddress {
    [CmdletBinding()]


    $OriginalPref = $ProgressPreference # Default is 'Continue'


    $ProgressPreference = "SilentlyContinue"


    (Invoke-WebRequest -uri "http://ifconfig.me/ip").Content


    $ProgressPreference = $OriginalPref
}

设置MyAZSub.ps1 (Set-MyAZSub.ps1)

This function is a preconstructed Azure subscription list that allows you to change your PowerShell Az Module’s AzContext without needing to pass in explicit Subscription or Tenant id information each time you want to change subscriptions.

此功能是一个预先构建的Azure订阅列表,通过该列表,您可以更改PowerShell Az Module的AzContext,而无需在每次要更改订阅时都传递明确的Subscription或Tenant ID信息。

Normally this is what we do to change AzContext.

通常,这就是我们更改AzContext的工作。

Set-AzContext -Subscription 'SUBSCRIPTION-NAME-OR-ID' -TenantId 'AZURE-AD-DIRECTORY-TENANT-ID'

But I don’t want to go to Azure Portal and find a GUID or possible a second one, the tenant ID.

但是我不想转到Azure门户并找到GUID或第二个GUID(租户ID)。

When I’ve realized I was doing this a lot, I’ve created the script below so I can just jump between my subscriptions with a shorter and easy to remember way.

当我意识到自己在做很多事情时,就创建了以下脚本,因此我可以使用更短且易于记忆的方式在订阅之间进行切换。

So script below, needs some preparation on your end, you have to manually fill in the Subscription details, in the below hashtable. Once you have a populated table you may now change or login to your subscriptions with

因此,下面的脚本需要进行一些准备,您必须手动在下面的哈希表中填写“订阅”详细信息。 填充表格后,您现在可以使用以下命令更改或登录到您的订阅

Set-MyAzSub 'proj1-dev'

this small piece of code invocation. Pick 3–5 letter abbreviation for your projects and 3 letter codes should be enough for stages, like DEV,TST,STG. This way you will have a consistent model.

这小段代码调用。 为您的项目选择3–5个字母的缩写,对于DEV,TST,STG等阶段,三个字母代码就足够了。 这样,您将拥有一个一致的模型。

In my case in my current role, I’m mainly responsible for 2 products that both

就我目前的职位而言,我主要负责两种产品

has Development, Test, Staging subscriptions tied to my regular account(non-admin), I also have a Visual Studio Enterprise subscription where I can do proof of concepts with $200 monthly credit to spend.

具有与常规帐户(非管理员)绑定的“开发”,“测试”,“分期”订阅,我还有一个Visual Studio Enterprise订阅,可以每月花费200美元的信用额进行概念验证。

Hence changing my shell’s context on the fly easily is really handy. This script also logs you in, if it doesn’t detect an AzContext.

因此,轻松地动态更改外壳的上下文非常方便。 如果未检测到AzContext,该脚本还将使您登录。

function Set-MyAzSub {
    [CmdletBinding()]
    param (
        [Parameter(Mandatory = $true, Position = 0)][string]$SubCode
    )
    
    $SubscriptionTable = @{
        'proj1-dev'  = @{
            'SubscriptionName' = '' #Name of subscription Ex: 'Project1 - Development'
            'SubscriptionId'   = '' #Subscription ID(GUID) Ex: cb9ace2f-e5e1-42ba-afe2-b9a4d6126e01
            'TenantId'         = '' #Tenant ID(GUID) Ex: 0c683a78-b01a-4f8c-98ff-402276a56b22
        }
        'proj1-test' = @{
            'SubscriptionName' = ''
            'SubscriptionId'   = ''
            'TenantId'         = ''
        }
        'proj1-stg'  = @{
            'SubscriptionName' = ''
            'SubscriptionId'   = ''
            'TenantId'         = ''
        }
        'proj2-dev'  = @{
            'SubscriptionName' = ''
            'SubscriptionId'   = ''
            'TenantId'         = ''
        }
        'proj2-test' = @{
            'SubscriptionName' = ''
            'SubscriptionId'   = ''
            'TenantId'         = ''
        }
        'proj2-stg'  = @{
            'SubscriptionName' = ''
            'SubscriptionId'   = ''
            'TenantId'         = ''
        }
    }
    
    $SubscriptionName = $SubscriptionTable.$SubCode.SubscriptionName
    $SubscriptionId = $SubscriptionTable.$SubCode.SubscriptionId
    $TenantId = $SubscriptionTable.$SubCode.TenantId
    
    Write-Host "Changing AzContext to:" -ForegroundColor Red
    
    Write-Host "Subscription: " -ForegroundColor Green -NoNewline
    Write-Host "$SubscriptionName" -ForegroundColor Blue
    
    Write-Host "SubscriptionId: " -ForegroundColor Green -NoNewline
    Write-Host "$SubscriptionId" -ForegroundColor Blue
    
    Write-Host "TenantID: " -ForegroundColor Green -NoNewline
    Write-Host "$TenantId" -ForegroundColor Blue
    
    #region connect to correct tenant and subscription
    $CurrentContext = Get-AzContext
    #If there is no AzContext found connect to desired Subscription and Tenant
    if (!$CurrentContext) {
        Connect-AzAccount -Tenant $TenantId -Subscription $SubscriptionId -UseDeviceAuthentication
        $CurrentContext = Get-AzContext
    }
    #If subscription ID doesnt match, call the set-azcontext with subid and tenantid to allow switch between tenants as well. 
    if ($CurrentContext.Subscription.Id -ne $SubscriptionId) {
        $CurrentContext = Set-AzContext -Subscription $SubscriptionId -Tenant $TenantId
    }
    #endregion


    Get-AzContext
}
Image for post
The script in action
运行中的脚本

New-FeatureBranchName.ps1 (New-FeatureBranchName.ps1)

One major change you can tell if an IT shop is doing DevOps or not, is you can tell by their infrastructure assets and if they are being provisioned as code, their scripts and everything should be treated as a software project.

您可以判断IT车间是否在进行DevOps,这是一项重大更改,您可以通过其基础设施资产来判断它们是否被提供为代码,它们的脚本以及所有内容都应被视为软件项目。

This being the case, I work closely with Backend and FrontEnd Software Developers, Test Automation Engineers and all the other parties of Software Development Lifecycle.

在这种情况下,我与后端和前端软件开发人员,测试自动化工程师以及软件开发生命周期的所有其他方密切合作。

We are using textbook gitflow hence all of my changes needs to be tracked by a work item in our Kanban board so it can be referenced later on. I need to come up with branch names that explains my work. This may be easy for a developer as they are used to doing it for longer then a DevOps engineer.

我们使用的是教科书gitflow,因此我的所有更改都需要由看板中的工作项进行跟踪,以便以后可以引用。 我需要拿出分支名称来解释我的工作。 对于开发人员来说,这可能很容易,因为他们习惯于比DevOps工程师花费更长的时间。

We had a requirement to prefix all branch names with WorkItem ID associated, so I only had to come up some descriptive text. This led me constructing strings (branch name) directly from work item description.

我们需要为所有分支名称加上关联的WorkItem ID前缀,因此我只需要提出一些描述性文字。 这导致我直接从工作项描述中构造字符串(分支名称)。

Image for post
Gitflow
Gitflow

normally I call feature branches something like

通常我称功能分支为

“feature/WorkItemID_WorkItemTitle”

“功能/ WorkItemID_WorkItemTitle”

but sometimes if a project is in early stages there might be too many branches going active at the same time.

但是有时候,如果一个项目处于早期阶段,那么可能同时有太多分支处于活动状态。

So I sometimes use this format so everyone knows those branches belongs to the “DevOps Guy” and possibly includes, Infrastructure, Configuration, script or something similar.

所以我有时使用这种格式,以便每个人都知道那些分支属于“ DevOps Guy”,并且可能包括基础架构,配置,脚本或类似内容。

“feature/initials/WorkItemID_WorkItemTitle”

“功能/缩写/ WorkItemID_WorkItemTitle”

this way all of my branches are listed under “feature/ms/ID_Title” so their owner is visually observed easily.

这样,我所有的分支都列在“ feature / ms / ID_Title”下,这样就可以很容易地从视觉上观察它们的所有者。

function New-FeatureBranchName {
    [CmdletBinding()]
    param (
        # Work Item ID
        [Parameter(Mandatory)][Alias('i','id')][string]$workItemId,
        # Work Item Title
        [Parameter(Mandatory)][Alias('t','title')][string]$workItemTitle,
        # Initials
        [Parameter()][Alias('in','name', 'inits')][string]$initials
    )


        $featureprefix = "feature/"


        if($initials) {$featureprefix = $featureprefix + $initials + '/'}


        $TitleFormatted = $workItemTitle -replace " ", "_"


        $branchname = $featureprefix + $workItemId + '_' + $TitleFormatted


        return $branchname
}

Let’s now use the script for an example let say I have to create a branch for this work item:

现在让我们使用脚本作为示例,假设我必须为此工作项目创建一个分支:

Image for post
This is how a Work Item looks like in Azure DevOps Boards
这是工作项目在Azure DevOps董事会中的样子

I can execute:

我可以执行:

> New-FeatureBranchName -id 264 -title 'Create Azure VM via ARM Template'
feature/264_Create_Azure_VM_via_ARM_Template
#or with initials  
> New-FeatureBranchName -id 264 -title 'Create Azure VM via ARM Template' -initials ms
feature/ms/264_Create_Azure_VM_via_ARM_Template

and get back my feature branch name. It looks simple and it is but that is the good thing about this, I don’t want to think about a simple thing, I don’t want to curate a templated string value manually each time I need it, a machine can do it for me.

并找回我的功能分支名称。 它看起来很简单,但这是一件好事,我不想考虑简单的事情,我不想每次都需要手动整理模板化字符串值时,机器就可以做到为了我。

Do you also have these type of small handy scripts you use in your day to day tasks?

在日常任务中,您是否还使用了这类方便的小型脚本?

Around 2 years ago I started doing all the tasks asked of me scripted, even if it looks like a once off or a small simple task.I guarantee you, most of the time you would to either re-perform the same task or a variation of it. People provide you wrong passwords they give you wrong connection strings etc, you may have to update that KeyVault secret or AppSettings again and again.

大约2年前,我开始执行脚本要求的所有任务,即使它看起来像是一次过的任务或一个简单的小任务。我保证,在大多数情况下,您会重新执行同一任务或执行变体它的。 人们为您提供了错误的密码,他们为您提供了错误的连接字符串,等等,您可能不得不一次又一次地更新KeyVault机密或AppSettings。

Scripts(code) not only performs the tasks faster, they also produce consistent results than us humans.

脚本(代码)不仅可以更快地执行任务,而且还比我们人类产生一致的结果。

Although time benefited looks small, it is great practice to think in DevOps hat and look at automating as much as possible.

尽管节省的时间看起来很小,但是在DevOps帽子中思考并尽可能地自动化是一种很好的做法。

翻译自: https://medium.com/mertsenel/my-powershell-swissknife-4000ded8b296

powershell

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值