PowerShell的力量,第2部分

在第一部分中,我向您展示了一些可以用PowerShell进行处理的好东西,介绍了PowerShell的历史,并深入探讨了PowerShell作为一种强大的脚本语言的功能,该语言支持过程,功能和面向对象的编程。

在第二部分中,我将讨论交互式外壳,配置文件和提示,并将PowerShell与Bash进行比较。

PowerShell:交互式外壳

PowerShell从一开始就设计为Windows系统管理员和高级用户的交互式外壳。 它侧重于少量概念, 非常一致的经验以及用于链接和组合命令,过滤命令和格式化命令的对象管道。 它强大的帮助系统也遵循一致的格式,使用起来很愉快。

让我们看看其中的一些操作。

获得帮助

全面的帮助系统可以通过Get-Help访问。

PS C:\WINDOWS\system32> Help Invoke-WebRequest

NAME
    Invoke-WebRequest
    
SYNOPSIS
    Gets content from a web page on the Internet.
    
    
SYNTAX
    Invoke-WebRequest [-Uri] <Uri> [-Body <Object>] [-Certificate <X509Certificate>] [-CertificateThumbprint <String>] [-ContentType <String>] [-Credential <PSCredential>] [-DisableKeepAlive] [-Headers 
    <IDictionary>] [-InFile <String>] [-MaximumRedirection <Int32>] [-Method {Default | Get | Head | Post | Put | Delete | Trace | Options | Merge | Patch}] [-OutFile <String>] [-PassThru] [-Proxy <Uri>] 
    [-ProxyCredential <PSCredential>] [-ProxyUseDefaultCredentials] [-SessionVariable <String>] [-TimeoutSec <Int32>] [-TransferEncoding {chunked | compress | deflate | gzip | identity}] 
    [-UseBasicParsing] [-UseDefaultCredentials] [-UserAgent <String>] [-WebSession <WebRequestSession>] [<CommonParameters>]
    
    
DESCRIPTION
    The Invoke-WebRequest cmdlet sends HTTP, HTTPS, FTP, and FILE requests to a web page or web service. It parses the response and returns collections of forms, links, images, and other significant HTML 
    elements.
    
    This cmdlet was introduced in Windows PowerShell 3.0.
    

RELATED LINKS
    Online Version: http://go.microsoft.com/fwlink/?LinkId=821826
    Invoke-RestMethod 
    ConvertFrom-Json 
    ConvertTo-Json 

REMARKS
    To see the examples, type: "get-help Invoke-WebRequest -examples".
    For more information, type: "get-help Invoke-WebRequest -detailed".
    For technical information, type: "get-help Invoke-WebRequest -full".
    For online help, type: "get-help Invoke-WebRequest -online"

要获取更多详细的帮助并查看示例,请使用适当的开关: -examples-details-full

如果不确定命令名称是什么,只需使用关键字,PowerShell就会向您显示包含此关键字的所有可用命令。 让我们看看有哪些与CSV相关的cmdlet:

PS C:\Users\the_g> Get-Help -Category Cmdlet csv | select name

Name           
----           
ConvertFrom-Csv
ConvertTo-Csv  
Export-Csv     
Import-Csv

我创建了一个小管道,其中仅将Get-Help调用限制为Cmdlet类别,然后将其通过管道传递给“ select”(Select-Object的别名)以仅获得“ name”属性。

处理文件和目录

您可以执行几乎所有的操作:导航到各个目录,列出文件和子目录,检查文件的内容,创建目录和文件等。

PS C:\Users\the_g> mkdir test_dir | select name

Name    
----    
test_dir                                                                                                                        

PS C:\Users\the_g> cd .\test_dir

PS C:\Users\the_g\test_dir> "123" > test.txt

PS C:\Users\the_g\test_dir> ls | name Name                                                                                             ----                                                                                             test.txt                                                                                                                                                   

PS C:\Users\the_g\test_dir> get-content .\test.txt
123

与其他提供商合作

使用PowerShell,您可以将许多东西视为文件系统,并使用cd对其进行导航,并使用ls/dir检查其内容。 以下是一些其他提供程序:

Provider      Drive         Data store
--------      -----         ----------
Alias         Alias:        Windows PowerShell aliases

Certificate   Cert:         x509 certificates for digital signatures

Environment   Env:          Windows environment variables

Function      Function:     Windows PowerShell functions

Registry      HKLM:, HKCU:  Windows registry

Variable      Variable:     Windows PowerShell variables

WSMan         WSMan:        WS-Management configuration information

让我们检查一下环境,看看那里(我的机器上)有哪些与Go相关的环境变量:

PS C:\Users\the_g> ls env:GO*

Name   Value
----   -----
GOROOT C:\GO\                        
GOPATH C:\Users\the_g\Documents\Go

格式化

PowerShell鼓励使用标准开关组成cmdlet并创建管道。 格式化是一个明确的概念,在管道的最后放置格式化程序。 默认情况下,PowerShell在管道末端检查一个或多个对象的类型,并应用默认的格式化程序。 但是您可以通过自己指定格式化程序来覆盖它。 格式化程序只是cmdlet。 这是以前以列表格式显示的输出:

PS C:\Users\the_g> ls env:GO* | Format-List

Name  : GOROOT
Value : C:\Go\

Name  : GOPATH
Value : c:\Users\the_g\Documents\Go

个人资料

使用命令行的高级用户经常会执行许多任务,管道以及他们喜欢的带有默认开关的常用命令组合。 PowerShell配置文件是一个PowerShell脚本文件,每当您开始新会话时都会加载并执行。 您可以将所有喜欢的东西放在这里,创建别名和函数,设置环境变量,以及几乎所有其他内容。

我喜欢为深层嵌套的目录创建导航别名,激活Python虚拟环境,并为我经常运行的外部命令(如git和docker)创建快捷方式。

对我来说,配置文件是必不可少的,因为PowerShell的可读性和一致性一致的命令和开关通常太冗长,并且内置别名通常比帮助更麻烦(我将在后面讨论)。 以下是我的个人资料中的部分片段:

#---------------------------
#
#   D O C K E R
#
#---------------------------
Set-Alias -Name d -Value docker

function di { d images }
#---------------------------
#
#   G I T
#
#---------------------------
Set-Alias -Name g -Value git
function gs { g status }
function gpu { g pull --rebase }

#-------------------------
#
#   C O N D A
#
#-------------------------
function a { activate.ps1 $args[0] }

#------------------------
#
#   N A V I G A T I O N
#
#------------------------

function cdg { cd $github_dir }
# MVP 
function cdm { a ov; cdg; cd MVP }

# backend 
function cdb { a ov; cdg; cd backend }

# scratch
function cds { a ov; cdg; cd scratch }

# backend packages
function cdbp { cdb; cd packages }

# Go workspace
function cdgo { cd $go_src_dir }

提示

PowerShell使您可以自定义命令提示符。 您需要定义一个名为prompt()的函数。 您可以看到内置的提示功能:

PS C:\Users\the_g> gc function:prompt

"PS $($executionContext.SessionState.Path.CurrentLocation)$('>' * ($nestedPromptLevel + 1)) ";
# .Link
# http://go.microsoft.com/fwlink/?LinkID=225750
# .ExternalHelp System.Management.Automation.dll-help.xml


PS C:\Users\the_g>

这是一个自定义提示功能,除了显示当前目录外,还显示当前时间:

PS C:\Users\the_g> function prompt {"$(get-date) $(get-location) > "}

10/09/2016 12:42:36 C:\Users\the_g >

当然,您可以疯狂,添加颜色并检查各种条件,例如您是否在特定的git存储库中,或者您是管理员。

别名:阴暗面

我认为,PowerShell在两个不同的方面错了别名。 首先, alias命令仅允许重命名命令。 您不能添加通用标志或选项来通过对自身进行别名来使命令更有用。

例如,如果要逐行搜索文本,则可以使用Select-String cmdlet:

# Create a little text file with 3 lines
"@
ab
cd
ef
@" > 1.txt

# Search for a line containing d
Get-Content 1.txt | Select-String d 

cd

可以,但是许多人想将Select-String重命名为grep 。 但是grep默认情况下区分大小写,而Select-String不区分大小写。 -CaseSensitive ,我们只需添加-CaseSensitive标志,如下所示:

Set-Alias -Name grep -Value "Select-String -CaseSensitive"

不幸的是,这不起作用:

16:19:26 C:\Users\the_g> Get-Content 1.txt | grep D
grep : The term 'Select-String -CaseSensitive' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or
if a path was included, verify that the path is correct and try again.
At line:1 char:21
+ Get-Content 1.txt | grep D
+                     ~~~~
    + CategoryInfo          : ObjectNotFound: (Select-String -CaseSensitive:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException

别名的值必须是cmdlet,函数,脚本或程序。 不允许使用标志或参数。

现在,您可以在PowerShell中非常轻松地执行此操作,但是您必须使用函数而不是别名。 这几乎将别名限制为简单的重命名,这也可以通过函数来​​完成。

PowerShell与Bash

在交互式外壳程序方面,PowerShell和Bash相当。 Bash默认情况下更为简洁,但是PowerShell的对象管道使复杂的管道更易于管理。 ,

就是说,您可以用任何一个完成任何事情,如果您是高级用户,那么您将拥有自己的别名,函数和用于常见任务的快捷方式。 在脚本方面,PowerShell远远超过了Bash,并且出于系统管理的目的,它甚至击败了Python,Ruby和朋友。

一个重要方面是可用性。 Bash预先安装了包括MacOS在内的大多数* nix发行版(除非特别删除)。 也可以通过cygwin,git-bash或msys将其安装在Windows上。 PowerShell预先安装在Windows上,最近才在Mac和Linux上可用。

结论

如果将Windows用作开发计算机或管理Windows计算机,那么PowerShell是必不可少的工具。 它确实是经过深思熟虑的Unix shell的超集,并且已预先安装。

PowerShell是出色的软件工程。 它经过十多年的发展,在保持原始概念完整性的同时不断创新。 最近转向开源和跨平台的信号表明,还有更多的事情要等待。

翻译自: https://code.tutsplus.com/tutorials/the-power-of-powershell-part-2--cms-27420

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值