Powershell基础和应用

2022-09-23-10-40-23-image

这本书,重点是教会我们如何 通过自学掌握所有这些可以通过 PowerShell 操作的服务器级别产品。Exchange Server、SQL Server、System Center

而不是告诉我们每个产品怎么使用

自学的技巧

不要害怕失败,希望你有一台虚拟机,然后在虚拟里实验 PowerShell。学生们经常会问类似这类问题:“如果我做了这个和那个,会发生什么?”我们的回答往往是“不知道,自己试试”。在虚拟机做实验是一个好办法,最坏的情况也只不过是将虚拟机回滚到某个快照点,对吧?所以无论做什么,都请试一试。

不要害怕使用帮助并确保阅读示例。我们不止一次强调过这一点,但好像没人愿意听。我们仍然会看到很多学生在我们眼皮底下使用 Google 寻找示例。为什么那么害怕帮助文档?如果你都愿意读别人的博客了,为什么不先尝试在帮助文档中阅读示例?

请注意,在屏幕上,每一点信息可能都非常重要——请不要跳过不是你目前正在寻找的信息。你很容易这样做,但请不要这么做。要查看每一部分信息,并尝试发现该信息的用处,以及使用该信息能够推算出什么。

如果尝试一种方法不奏效,不要挠墙——请尝试其他方法。

终端

2022-09-23-10-46-59-image

PS C:\Windows\system32>

PS: powershell, 后面是当前工作目录

命令

认识命令

powershell 中叫 cmdlet,例如一个简单的列出当前目录下的所有文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
PS C:\Windows\system32> cd c:/
PS C:\> ls


目录: C:\


Mode LastWriteTime Length Name
---- ------------- ------ ----
d----- 2022/9/19 9:22 2020-09-16-myblog
d----- 2022/4/29 13:48 pcwlenv
d-r--- 2022/9/21 8:43 Program Files
d-r--- 2022/7/14 9:30 Program Files (x86)
d----- 2022/7/19 8:34 Temp
d-r--- 2022/9/21 12:27 Users
d----- 2022/7/29 8:21 Windows
-a---- 2022/4/29 13:42 0 dcdspdbg.log
-a---- 2022/7/12 11:31 12288 DumpStack.log
-a---- 2022/8/11 12:56 2637 priv.pfx


PS C:\> ls -name
2020-09-16-myblog
pcwlenv
Program Files
Program Files (x86)
Temp
Users
Windows
dcdspdbg.log
DumpStack.log
priv.pfx

或者

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
PS C:\> Get-ChildItem


目录: C:\


Mode LastWriteTime Length Name
---- ------------- ------ ----
d----- 2022/9/19 9:22 2020-09-16-myblog
d----- 2022/4/29 13:48 pcwlenv
d-r--- 2022/9/21 8:43 Program Files
d-r--- 2022/7/14 9:30 Program Files (x86)
d----- 2022/7/19 8:34 Temp
d-r--- 2022/9/21 12:27 Users
d----- 2022/7/29 8:21 Windows
-a---- 2022/4/29 13:42 0 dcdspdbg.log
-a---- 2022/7/12 11:31 12288 DumpStack.log
-a---- 2022/8/11 12:56 2637 priv.pfx


PS C:\> Get-ChildItem -Name
2020-09-16-myblog
pcwlenv
Program Files
Program Files (x86)
Temp
Users
Windows
dcdspdbg.log
DumpStack.log
priv.pfx

注意,这里,可以发现命令lsGet-ChildItem是一样的作用,这里和 Linux 不一样

  1. windows 中,为了兼容 linux 命令,部分与 linux 一样的命令, 例如 ls, 只是 windows 命令的别名(windows 别名只能引用命令本身,不能引用命令+选项。ls 只能对应 get-childitem)

  2. windows 中, 字符不区分大小写。LS, Ls, lS, 均是 ls 命令。get-childitem 还是 Get-CHILDITEM 均一样。为了方便书写,统一小写。

  3. windows 中也支持 tab 键补全命令,选项,目录路径

  4. windows 中终端也支持 ctrl + a, ctrl + e, ctrl + l。需要打开终端功能。Set-PSReadLineOption -EditMode emacs, 这个命令在会话中执行只是当前会话有效,终端重启之后就无效了,所以需要写在配置文件中,windows 在会话启动时,会读取的配置文件. $PSHOME -> $PROFILE

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    $PSHOME
    profile.ps1
    Microsoft.PowerShell_profile.ps1

    (SPLIT-PATH $PROFILE)
    profile.ps1
    Microsoft.PowerShell_profile.ps1

    # 验证方式

    ## 会话启动时,定义变量

    set-content $PSHOME/Microsoft.PowerShell_profile.ps1 -value "'PSHOME MPS'`n[System.Environment]::SetEnvironmentVariable('PATH',`$Env:PATH+';;C:\Users\slc\apps\go-ipfs-v0.12.2\go-ipfs')"

    ## 会话启动时,定义别名。

    set-content $PSHOME/profile.ps1 -value "'PSHOME PS'`nNew-Alias ifconfig ipconfig"

    ## 会话启动时,定义变量

    set-content "$(Split-Path $PROFILE -Parent)/Microsoft.PowerShell_profile.ps1" -value "'profile MPS'`n[System.Environment]::SetEnvironmentVariable('PATH',`$Env:PATH+';;C:\Users\slc\apps\go-ipfs-v0.12.2\go-ipfs')"

    ## 会话启动时,也可以定义PS提示符变量,运行命令等等

    set-content "$(Split-Path $PROFILE -Parent)/profile.ps1" -value "'profile PS'`nSet-PSReadLineOption -EditMode emacs`nfunction prompt() { (get-date).ToShortTimeString() + ' [PS] ' + (Get-Location) + ' :> ' }`nNew-NetFirewallRule -DisplayName '9000 django test' -Direction Inbound -LocalPort 9000 -Protocol tcp -Action Allow`n"

    2022-09-23-11-16-12-image

  5. 由 4 中给配置文件,会话启动前会加载一些文件.

我们配置配置环境变量时,引用当前命令读的环境变量不是$path 而是$env:path

我们在文本中,需要换行,linux 是\n, \e, \t 。windows 对应

1
2
3
4
`n
`e
`t
...

从以上示例,我们可以看出 windows 命令的格式

Get-ChildItem -Name

  • 命令: get-childitem, 动词-名词

    • 获取 windows 支持哪些动作get-verb, 常用的动作就是 C (new) U (set) R (get) D (remove)
  • 选项: -name, 帮助中获取

命令帮助

如何知道 windows 上有哪些命令,show-command,会显示所有模块所有命令。

搜索命令, powershell 有文档维护自己的所有命令和模块对应的命令。即使你的系统没有安装这个命令,我们也可以搜索到命令及帮助。

首先,一个系统我们需要安装帮助文件,或者是系统的帮助文件是需要定时更新的。

1
Update-Help

帮助可以自己手工联网更新,也可以离线更新。

更新帮助后,我们可以搜索一些命令相关的帮助的主题。例如:

user, privilege 权限,process 进程,net 网络,常用的关键字

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# 进程相关
12:13 [PS] C:\Windows\system32 :> help *process*

Name Category Module Synopsis
---- -------- ------ --------
Enter-PSHostProcess Cmdlet Microsoft.PowerShell.Core Connects to and enters into an interactive session with a local process.
Exit-PSHostProcess Cmdlet Microsoft.PowerShell.Core Closes an interactive session with a local process.
Get-PSHostProcessInfo Cmdlet Microsoft.PowerShell.Core Gets process information about the PowerShell host.
Debug-Process Cmdlet Microsoft.PowerShell.M... Debugs one or more processes running on the local computer.
Get-Process Cmdlet Microsoft.PowerShell.M... Gets the processes that are running on the local computer or a remote computer.
Start-Process Cmdlet Microsoft.PowerShell.M... Starts one or more processes on the local computer.
Stop-Process Cmdlet Microsoft.PowerShell.M... Stops one or more running processes.
Wait-Process Cmdlet Microsoft.PowerShell.M... Waits for the processes to be stopped before accepting more input.
Get-AppvVirtualProcess Function AppvClient ...
Start-AppvVirtualProcess Function AppvClient ...
ConvertTo-ProcessMitigationPolicy Cmdlet ProcessMitigations ConvertTo-ProcessMitigationPolicy...
Get-ProcessMitigation Cmdlet ProcessMitigations Get-ProcessMitigation...
Set-ProcessMitigation Cmdlet ProcessMitigations Set-ProcessMitigation...
  • name, process 相关的命令

  • category,命令类型。windows 中一般有 cmdlet 命令,函数命令,….

    • cmdlet 命令,原生的 ps 命令,由.net 编写,google 搜索 cmdlet 关键字,返回结果主要关于 powershell 的。

    • Function 函数,其实使用方式和 cmdlet 命令一样,只是不由.net 编写,而且 powershell 自己的脚本语言编写。

    • Application: windows 的应用程序

  • Module,命令属于哪些模块

    • 查看所有模块 Get-Module -ListAvailable ,查看安装的模块Get-Module

      命令是属于模块的,所以安装的模块对应的命令就是我们可以使用的 cmdlet 命令。

      1
      2
      3
      4
      5
      6
      7
      8
      12:48 [PS] C:\Windows\system32 :>  Get-Module

      ModuleType Version Name ExportedCommands
      ---------- ------- ---- ----------------
      Manifest 3.1.0.0 Microsoft.PowerShell.Management {Add-Computer, Add-Content, Checkpoint-Computer, Clear-Content...}
      Manifest 3.1.0.0 Microsoft.PowerShell.Utility {Add-Member, Add-Type, Clear-Variable, Compare-Object...}
      Manifest 2.0.0.0 NetSecurity {Get-DAPolicyChange, New-NetIPsecAuthProposal, New-NetIPsecMainModeCryptoProposal, New-NetIPsecQuickModeCryptoProposal...}
      Script 2.0.0 PSReadline {Get-PSReadLineKeyHandler, Get-PSReadLineOption, Remove-PSReadLineKeyHandler, Set-PSReadLineKeyHandler...}

      12:49 [PS] C:\Windows\system32 :> Get-Command -Module Microsoft.PowerShell.Management

      1

  • Synops,就是描述。

现在我们可以看到,动作及命令,我们现在需要看看有哪些进程

1
2
3
4
5
6
7
8
 Get-Process
Handles NPM(K) PM(K) WS(K) CPU(s) Id SI ProcessName
------- ------ ----- ----- ------ -- -- -----------
424 33 18192 21976 14.94 12280 1 360EntMsgCenter
3167 235 448632 73704 571.95 9948 1 360tray
284 14 15136 19204 93.17 5236 0 audiodg
345 26 29412 32084 0.19 5172 1 CefSharp.BrowserSubprocess
481 32 124300 38740 0.22 12404 1 CefSharp.BrowserSubprocess

如何拿到 notepad 相关的进程?

linux 中,ps -ef | grep get-process ,对于过滤,我们使用文本处理三剑客 grep/awk/sed,进行过滤处理,即可。 linux 的输出 是文本。

而 windows 中,过滤,我们不需要这些文本处理工具。他的输出是一个个对象的集合。所以以上 get-process 的输出其实是一行行对象(不看第 1 列),列就是对象的属性。所以过滤其实就是过滤对象的属性值。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# 先启动一个notepad, powershell中运行
notepad

# 过滤对象的属性,这里的name,就是对象的属性。 ?表示匹配, name属性。-match正则匹配。notepad是值
12:18 [PS] C:\Windows\system32 :> Get-Process | ? name -Match notepad

Handles NPM(K) PM(K) WS(K) CPU(s) Id SI ProcessName
------- ------ ----- ----- ------ -- -- -----------
684 35 47252 65960 0.48 17848 1 Notepad
676 35 47476 60208 1.27 21288 1 Notepad


# 如何知道这1行行对象的属性有哪些 ?
12:19 [PS] C:\Windows\system32 :> Get-Process | gm


TypeName:System.Diagnostics.Process

Name MemberType Definition
---- ---------- ----------
Handles AliasProperty Handles = Handlecount
Name AliasProperty Name = ProcessName

过滤某个进程,可以按对象过滤,还有一种方式,就是命令自带的过滤。一般 windows 命令均会自带过滤的参数。

如何看命令的选项及参数?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# 命令的帮助
# help command
12:20 [PS] C:\Windows\system32 :> help Get-Process

名称
Get-Process

摘要
Gets the processes that are running on the local computer or a remote computer.


语法
Get-Process [[-Name] <System.String[]>] [-ComputerName <System.String[]>] [-FileVersionInfo] [-Module] [<CommonParameters>]

Get-Process [-ComputerName <System.String[]>] [-FileVersionInfo] -Id <System.Int32[]> [-Module] [<CommonParameters>]

Get-Process [-ComputerName <System.String[]>] [-FileVersionInfo] -InputObject <System.Diagnostics.Process[]> [-Module] [<CommonParameters>]

Get-Process -Id <System.Int32[]> -IncludeUserName [<CommonParameters>]

Get-Process [[-Name] <System.String[]>] -IncludeUserName [<CommonParameters>]

Get-Process -IncludeUserName -InputObject <System.Diagnostics.Process[]> [<CommonParameters>]


说明
The `Get-Process` cmdlet gets the processes on a local or remote computer.

Without parameters, this cmdlet gets all of the processes on the local computer. You can also specify a particular process by process name or process ID (PID) or pass a process object through the pipeline to this cmdlet.

By default, this cmdlet returns a process object that has detailed information about the process and supports methods that let you start and stop the process. You can also use the parameters of the `Get-Process` cmdlet to get file v
ersion information for the program that runs in the process and to get the modules that the process loaded.


相关链接
Online Version: https://docs.microsoft.com/powershell/module/microsoft.powershell.management/get-process?view=powershell-5.1&WT.mc_id=ps-gethelp
Debug-Process
Get-Process
Start-Process
Stop-Process
Wait-Process

备注
若要查看示例,请键入: "get-help Get-Process -examples".
有关详细信息,请键入: "get-help Get-Process -detailed".
若要获取技术信息,请键入: "get-help Get-Process -full".
有关在线帮助,请键入: "get-help Get-Process -online"

在帮助中,我们可以看到有几个段

  • 名称

  • 摘要,命令的功能

  • 语法,命令的使用方式

  • 说明

  • 相关链接

  • 备注,获取其他帮助**

这几个段和 Linux 是类似的,一般我们着重看摘要和语法。语法部分,我们只需要注意[] 是可以省略的。<>是必给的。string[]表示数组,元素为一个个字符串。number[], 数组,元素为一个个数字。[<Common-Parameters>] 表示所有 powershell 命令通用的参数。 help about_CommonParameters 这样获取相关的参数。

还有一个重点,是备注。一般一个命令不会使用,可以以下步骤

1
2
3
4
5
6
7
8
# 看看命令的功能和语法
help Get-Process

# 看看命令的示例
help Get-Process -Examples

# 示例不够详细,也可以看看在线的文档。会自动打开网页,进入命令的帮助页。还是中文
help Get-Process -Online

例如,我们看到的在线文档的帮助。这个合作怎么使用,已相当完整了。

2022-09-23-12-26-43-image

模块命令

一般使用一个产品,会提供 powershell 相应模块,我们只需要加载模块,就可以看到模块的命令。

powershell 获取命令帮助的第 2 种方法get-command,他有 2 个可选参数对应动作-verb, 名称-noun 支持通配。帮助的种类-CommandType。哪些模块-module

先看看帮助help get-command

1
2
3
Get-Command [[-Name] <System.String[]>] [[-ArgumentList] <System.Object[]>] [-All] [-CommandType {Alias | Function | Filter | Cmdlet | ExternalScript | Application | Script | Workflow | Configuration | All}] [-FullyQualifiedModule <
Microsoft.PowerShell.Commands.ModuleSpecification[]>] [-ListImported] [-Module <System.String[]>] [-ParameterName <System.String[]>] [-ParameterType <System.Management.Automation.PSTypeName[]>] [-ShowCommandInfo] [-Syntax] [-TotalCo
unt <System.Int32>] [<CommonParameters>]
1
2
Get-Command [[-ArgumentList] <System.Object[]>] [-All] [-FullyQualifiedModule <Microsoft.PowerShell.Commands.ModuleSpecification[]>] [-ListImported] [-Module <System.String[]>] [-Noun <System.String[]>] [-ParameterName <System.Strin
g[]>] [-ParameterType <System.Management.Automation.PSTypeName[]>] [-ShowCommandInfo] [-Syntax] [-TotalCount <System.Int32>] [-Verb <System.String[]>] [<CommonParameters>]

这里有 2 个语法,

get-command string[] 表示获取字符串列表的所有命令

get-command object[]

例如,获取 ls, cat 命令

1
2
3
4
5
6
7
8
9
10
11
12
13
12:54 [PS] C:\Windows\system32 :>  Get-Command ls,cat

CommandType Name Version Source
----------- ---- ------- ------
Alias ls -> Get-ChildItem
Alias cat -> Get-Content


12:55 [PS] C:\Windows\system32 :> Get-Command ls

CommandType Name Version Source
----------- ---- ------- ------
Alias ls -> Get-ChildItem

windows 中,兼容 linux 的命令,可以从这里看出是别名,如何知道 windows 有哪些别名?

1
2
3
4
5
6
7
8
9
10
11
12
13
# 别名相关的主题?
12:56 [PS] C:\Windows\system32 :> help *alias*

Name Category Module Synopsis
---- -------- ------ --------
Export-Alias Cmdlet Microsoft.PowerShell.U... Exports information about currently defined aliases to a file.
Get-Alias Cmdlet Microsoft.PowerShell.U... Gets the aliases for the current session.
Import-Alias Cmdlet Microsoft.PowerShell.U... Imports an alias list from a file.
New-Alias Cmdlet Microsoft.PowerShell.U... Creates a new alias.
Set-Alias Cmdlet Microsoft.PowerShell.U... Creates or changes an alias for a cmdlet or other command in the current PowerShell session.
Get-ModuleAliases Function AdminToolbox ...
about_Aliases HelpFile
about_Alias_Provider HelpFile
1
2
3
4
5
6
7
8
9
10
11
12
13
14
# 可以看到 get-alias
12:57 [PS] C:\Windows\system32 :> help get-alias

名称
Get-Alias

摘要
Gets the aliases for the current session.


语法
Get-Alias [-Definition <System.String[]>] [-Exclude <System.String[]>] [-Scope <System.String>] [<CommonParameters>]

Get-Alias [[-Name] <System.String[]>] [-Exclude <System.String[]>] [-Scope <System.String>] [<CommonParameters>]
1
2
3
4
5
6
7
8
9
10
11
12
13
12:57 [PS] C:\Windows\system32 :>  get-alias

CommandType Name Version Source
----------- ---- ------- ------
Alias % -> ForEach-Object
Alias ? -> Where-Object
Alias ac -> Add-Content
Alias asnp -> Add-PSSnapin
Alias cat -> Get-Content
Alias cd -> Set-Location
Alias CFS -> ConvertFrom-String 3.1.0.0 Microsoft.PowerShell.Utility
Alias chdir -> Set-Location
Alias clc -> Clear-Content

这样我们就拿到了 powershell 会话的所有别名

现在获取 get-childitem 命令

  1. 直接给命令

  2. 给动作,匹配相关的名称

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
12:58 [PS] C:\Windows\system32 :>  Get-Command get-childitem

CommandType Name Version Source
----------- ---- ------- ------
Cmdlet Get-ChildItem 3.1.0.0 Microsoft.PowerShell.Management


12:59 [PS] C:\Windows\system32 :> Get-Command -Verb get -Noun *item*

CommandType Name Version Source
----------- ---- ------- ------
Function Get-DAEntryPointTableItem 1.0.0.0 DirectAccessClientComponents
Function Get-SFTPChildItem 3.0.6 Posh-SSH
Function Get-TestDriveItem 3.4.0 Pester
Cmdlet Get-ChildItem 3.1.0.0 Microsoft.PowerShell.Management
Cmdlet Get-ControlPanelItem 3.1.0.0 Microsoft.PowerShell.Management
Cmdlet Get-Item 3.1.0.0 Microsoft.PowerShell.Management
Cmdlet Get-ItemProperty 3.1.0.0 Microsoft.PowerShell.Management
Cmdlet Get-ItemPropertyValue 3.1.0.0 Microsoft.PowerShell.Management
Cmdlet Get-SCPItem 3.0.6 Posh-SSH
Cmdlet Get-SFTPItem 3.0.6 Posh-SSH

这里可以看出,get-childitem 命令来自Microsoft.PowerShell.Management 模块。

查看这个模块对应的命令

1
Get-Command -Module Microsoft.PowerShell.Management

查看这个模块对应的 get 命令

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
13:01 [PS] C:\Windows\system32 :>  Get-Command -Module Microsoft.PowerShell.Management -Verb get

CommandType Name Version Source
----------- ---- ------- ------
Cmdlet Get-ChildItem 3.1.0.0 Microsoft.PowerShell.Management
Cmdlet Get-Clipboard 3.1.0.0 Microsoft.PowerShell.Management
Cmdlet Get-ComputerInfo 3.1.0.0 Microsoft.PowerShell.Management
Cmdlet Get-ComputerRestorePoint 3.1.0.0 Microsoft.PowerShell.Management
Cmdlet Get-Content 3.1.0.0 Microsoft.PowerShell.Management
Cmdlet Get-ControlPanelItem 3.1.0.0 Microsoft.PowerShell.Management
Cmdlet Get-EventLog 3.1.0.0 Microsoft.PowerShell.Management
Cmdlet Get-HotFix 3.1.0.0 Microsoft.PowerShell.Management
Cmdlet Get-Item 3.1.0.0 Microsoft.PowerShell.Management
Cmdlet Get-ItemProperty 3.1.0.0 Microsoft.PowerShell.Management
Cmdlet Get-ItemPropertyValue 3.1.0.0 Microsoft.PowerShell.Management
Cmdlet Get-Location 3.1.0.0 Microsoft.PowerShell.Management
Cmdlet Get-Process 3.1.0.0 Microsoft.PowerShell.Management
Cmdlet Get-PSDrive 3.1.0.0 Microsoft.PowerShell.Management
Cmdlet Get-PSProvider 3.1.0.0 Microsoft.PowerShell.Management
Cmdlet Get-Service 3.1.0.0 Microsoft.PowerShell.Management
Cmdlet Get-TimeZone 3.1.0.0 Microsoft.PowerShell.Management
Cmdlet Get-Transaction 3.1.0.0 Microsoft.PowerShell.Management
Cmdlet Get-WmiObject 3.1.0.0 Microsoft.PowerShell.Management

查看这个模块 get 命令,其中时间相关的命令

1
2
3
4
5
13:02 [PS] C:\Windows\system32 :>  Get-Command -Module Microsoft.PowerShell.Management -Verb get -Noun *time*

CommandType Name Version Source
----------- ---- ------- ------
Cmdlet Get-TimeZone 3.1.0.0 Microsoft.PowerShell.Management

安装命令

仓库

1
2
3
4
5
13:03 [PS] C:\Windows\system32 :>  Get-PSRepository

Name InstallationPolicy SourceLocation
---- ------------------ --------------
PSGallery Trusted https://www.powershellgallery.com/api/v2
  • 这个 psrepo 相关的操作,通过以上的帮助来探索即可

  • 配置仓库,修改仓库,删除仓库….

搜索软件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
13:05 [PS] C:\Windows\system32 :>  help *module*                                                                                                                                                                                                                                                                                                                                                                                                                                          Name                              Category  Module                    Synopsis
---- -------- ------ --------
ImportSystemModules Function ...
Find-Module Function PowerShellGet ...
Get-InstalledModule Function PowerShellGet ...
Install-Module Function PowerShellGet ...
Publish-Module Function PowerShellGet ...
Save-Module Function PowerShellGet ...
Uninstall-Module Function PowerShellGet ...
Update-Module Function PowerShellGet ...
Update-ModuleManifest Function PowerShellGet ...
Export-ModuleMember Cmdlet Microsoft.PowerShell.Core Specifies the module members that are exported.
Get-Module Cmdlet Microsoft.PowerShell.Core List the modules imported in the current session or that can be imported from the PSModulePath.
Import-Module Cmdlet Microsoft.PowerShell.Core Adds modules to the current session.
New-Module Cmdlet Microsoft.PowerShell.Core Creates a new dynamic module that exists only in memory.
New-ModuleManifest Cmdlet Microsoft.PowerShell.Core Creates a new module manifest.
Remove-Module Cmdlet Microsoft.PowerShell.Core Removes modules from the current session.
Test-ModuleManifest Cmdlet Microsoft.PowerShell.Core Verifies that a module manifest file accurately describes the contents of a module.
Get-ModuleAliases Function AdminToolbox ...
Get-CPowerShellModuleInstallPath Function Carbon ...
Test-ModuleLoaded Function core ...
InModuleScope Function Pester ...
about_Modules HelpFile
about_Module_Manifests HelpFile
about_PSModulePath HelpFile 

可以看到有一个 find 命令,应该是查找命令相关的.

install,就表示安装命令

获取相应的帮助

1
help Find-Module -online

查找 powershell 相关的模块

1
Find-Module  PowerShell*

查找指定版本

1
find-module PowerShellGet -RequiredVersion 1.6.5

在指定仓库内查找

1
Find-Module  PowerShellGet -Repository PSGallery

基于 name, description, and tags 搜索相关的模块

1
Find-Module -Filter net

基于 tag 搜索

1
Find-Module -Tag CrescendoBuilt

例如我们搜索 kubernetes 搜索

1
2
3
4
5
6
7
8
13:20 [PS] C:\Windows\system32 :>  Find-Module kubernetes

Version Name Repository Description
------- ---- ---------- -----------
1.0.0 Kubernetes PSGallery Kubernetes


13:24 [PS] C:\Windows\system32 :> Install-Module Kubernetes

查看安装的模块

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
13:25 [PS] C:\Windows\system32 :>  Get-InstalledModule

Version Name Repository Description
------- ---- ---------- -----------
11.0.3 AdminToolbox PSGallery Master module for a collection of modules. These modules are varied in their tasks. The overall purpose of them being to provide a powerfull Toolset to improve IT Ad...
1.8.0 AdminToolbox.ActiveDirectory PSGallery Functions for Active Directory
4.8.0 AdminToolbox.EndpointManagement PSGallery Functions for management of endpoints
1.9.0 AdminToolbox.Exchange PSGallery Functions for Exchange Management
4.12.0 AdminToolbox.FFTools PSGallery Expedite simple ffmpeg actions
1.13.0 AdminToolbox.FileManagement PSGallery File Management Functions
2.15.0 AdminToolbox.FortiWizard PSGallery Functions that generate configuration scripts and manage FortiOS.
1.6.0 AdminToolbox.Fun PSGallery Functions that have no purpose
1.2.0 AdminToolbox.MSGraph PSGallery Microsoft Graph interactive API Functions
2.13.0 AdminToolbox.Networking PSGallery Network Troubleshooting Functions
2.10.0 AdminToolbox.Office365 PSGallery Functions for working with Office365 and Azure modules
1.9.0 AdminToolbox.Remoting PSGallery Functions for remote management and access.
4.8.0 AdminToolbox.VMWareAutomate PSGallery Functions to Automate Bulk VMWare Tasks
2.11.3 Carbon PSGallery Carbon is a PowerShell module for automating the configuration Windows 7, 8, 2008, and 2012 and automation the installation and configuration of Windows applications...
1.9 core PSGallery Module with various generic functions that could be used in any script
1.0.2 Get-IPInfo PSGallery Quickly look up IP Information including location, ISP and Organization
7.8.0 ImportExcel PSGallery PowerShell module to import/export Excel spreadsheets, without Excel....
1.1.1 IPTools PSGallery This module offers a set of tools to manage IP networks and devices.
1.0.0 Kubernetes PSGallery Kubernetes
3.0.6 Posh-SSH PSGallery Provide SSH and SCP functionality for executing commands against remote hosts.
0.3.0.0 PoshPrivilege PSGallery Module designed to use allow easier access to work with User Rights (privileges)
1.3.1 ProgramManagement PSGallery This Module makes it easier to Install/Uninstall programs on Windows, regardless of the method of installation (PSGet, Chocolatey CmdLine, .msi, etc). GitHub: https:...
1.0.22 PSEventViewer PSGallery Simple module allowing parsing of event logs. Has its own quirks...
0.9.3 ud-netmon PSGallery Web-based GUI (PowerShell Universal Dashboard) that pings specified Remote Hosts on your Domain every 5 seconds. GitHub: https://github.com/pldmgg/UD-NetMon
2.1.1 WindowsKeyboardManagement PSGallery Allows keys on the physical keyboard to be remapped, and redefine programs associated with multimedia keys. For example, you can remap the "Scroll Lock" key to the

导入模块

1
2
3
4
5
6
13:25 [PS] C:\Windows\system32 :>  Import-Module Kubernetes
13:25 [PS] C:\Windows\system32 :> Get-Module

ModuleType Version Name ExportedCommands
---------- ------- ---- ----------------
Manifest 1.0.0 Kubernetes

获取模块相关的命令

1
13:26 [PS] C:\Windows\system32 :>  Get-Command -Module Kubernetes

远程执行命令

打开远程功能,

1
13:27 [PS] C:\Windows\system32 :>  Enable-PSRemoting

功能打开后,会侦听  5985 端口

1
2
3
4
5
13:31 [PS] C:\Windows\system32 :>  Get-NetTCPConnection -State Listen -LocalPort 5985

LocalAddress LocalPort RemoteAddress RemotePort State AppliedSetting OwningProcess
------------ --------- ------------- ---------- ----- -------------- -------------
:: 5985 :: 0 Listen 4

远程连接

1
Invoke-Command -ComputerName "192.168.13.103" -Credential (Get-Credential) { Get-ComputerInfo }

提供者

psprovider,本质上是一个适配器,把一切都模拟成文件操作。统一使用 get-item, new-item, remove-item 来操作,适配器负责将这些操作转换成对应适配器后的操作。

1
2
3
4
5
6
7
8
9
10
11
12
13:35 [PS] C:\Windows\system32 :>  Get-PSProvider

Name Capabilities Drives
---- ------------ ------
Registry ShouldProcess, Transactions {HKLM, HKCU}
Alias ShouldProcess {Alias}
Environment ShouldProcess {Env}
FileSystem Filter, ShouldProcess, Credentials {C, D, E, F...}
Function ShouldProcess {Function}
Variable ShouldProcess {Variable}
WSMan Credentials {WSMan}
Certificate ShouldProcess {Cert}

这里,有很多适配器,均可以通过一套接口操作。操作每个适配器,可以有多个操作入口,例如下面的文件系统,有 CDEFG,这些入口。注册表有 HKCU/HKLM。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
14:02 [PS] C:\Windows\system32 :>  Get-PSDrive

Name Used (GB) Free (GB) Provider Root CurrentLocation
---- --------- --------- -------- ---- ---------------
Alias Alias
C 112.18 8.23 FileSystem C:\ Windows\system32
Cert Certificate \
D 71.20 50.80 FileSystem D:\
E 40.41 81.59 FileSystem E:\
Env Environment
F 0.09 100.94 FileSystem F:\
Function Function
G 50.93 396.19 FileSystem G:\
HKCU Registry HKEY_CURRENT_USER
HKLM Registry HKEY_LOCAL_MACHINE
Variable Variable
WSMan WSMan

例如查看 C:/盘的文件

1
2
3
4
5
6
7
8
9
10
11
14:05 [PS] C:\Windows\system32 :>  ls -Name c:/
2020-09-16-myblog
pcwlenv
Program Files
Program Files (x86)
Temp
Users
Windows
dcdspdbg.log
DumpStack.log
priv.pfx

查看 hkcu 下的内容

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
14:05 [PS] C:\Windows\system32 :>  ls hkcu:/ -name
AppEvents
Console
Control Panel
Environment
EUDC
Keyboard Layout
Layout
Network
Printers
Software
System
Uninstall
Volatile Environment
wdsafeloadat

2022-09-23-14-06-14-image

刚刚好,一一对应。

item 属性

一个项对应的属性。比如只读、项创建时间、长度等。

一般这个 item 是只读的,当提供是注册表时,是可以修改的。

1
2
3
4
5
6
7
8
9
10
11
12
14:29 [PS] C:\Windows\system32 :>  Get-Item HKCU:\Console\


Hive: HKEY_CURRENT_USER


Name Property
---- --------
Console ColorTable00 : 789516
ColorTable01 : 14300928
ColorTable02 : 958739
ColorTable03 : 14521914

查看属性

1
2
3
4
5
6
7
8
9
10
11
12
13
14:30 [PS] C:\Windows\system32 :>  Get-ItemProperty HKCU:\Console\


ColorTable00 : 789516
ColorTable01 : 14300928
ColorTable02 : 958739
ColorTable03 : 14521914
ColorTable04 : 2035653
ColorTable05 : 9967496
ColorTable06 : 40129
ColorTable07 : 13421772
ColorTable08 : 7763574
ColorTable09 : 16742459

修改属性

1
Set-ItemProperty -Path "HKLM:\Software\ContosoCompany" -Name "NoOfEmployees" -Value 824

item 操作

以 filesystem 为例

添加文件或目录

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
14:32 [PS] C:\Windows\system32 :>  new-item d:/test-2022-9-23


目录: D:\


Mode LastWriteTime Length Name
---- ------------- ------ ----
-a---- 2022/9/23 14:38 0 test-2022-9-23


14:38 [PS] C:\Windows\system32 :> new-item -Type Directory d:/test-d


目录: D:\


Mode LastWriteTime Length Name
---- ------------- ------ ----
d----- 2022/9/23 14:38 test-d

注意,在行首的-, d,用来区别文件类型的。创建目录另一个mkdir

删除目录或目录

1
2
14:38 [PS] C:\Windows\system32 :>  Remove-Item d:/test-d
14:39 [PS] C:\Windows\system32 :> Remove-Item D:\test-2022-9-23

进程管理

1
2
3
4
5
6
7
8
9
14:39 [PS] C:\Windows\system32 :>  Get-Command -Noun Process

CommandType Name Version Source
----------- ---- ------- ------
Cmdlet Debug-Process 3.1.0.0 Microsoft.PowerShell.Management
Cmdlet Get-Process 3.1.0.0 Microsoft.PowerShell.Management
Cmdlet Start-Process 3.1.0.0 Microsoft.PowerShell.Management
Cmdlet Stop-Process 3.1.0.0 Microsoft.PowerShell.Management
Cmdlet Wait-Process 3.1.0.0 Microsoft.PowerShell.Management

服务管理

1
2
3
4
5
6
7
8
9
10
11
12
13
14:40 [PS] C:\Windows\system32 :>  Get-Command -Noun Service

CommandType Name Version Source
----------- ---- ------- ------
Alias Remove-Service 2.11.3 Carbon
Cmdlet Get-Service 3.1.0.0 Microsoft.PowerShell.Management
Cmdlet New-Service 3.1.0.0 Microsoft.PowerShell.Management
Cmdlet Restart-Service 3.1.0.0 Microsoft.PowerShell.Management
Cmdlet Resume-Service 3.1.0.0 Microsoft.PowerShell.Management
Cmdlet Set-Service 3.1.0.0 Microsoft.PowerShell.Management
Cmdlet Start-Service 3.1.0.0 Microsoft.PowerShell.Management
Cmdlet Stop-Service 3.1.0.0 Microsoft.PowerShell.Management
Cmdlet Suspend-Service 3.1.0.0 Microsoft.PowerShell.Management

管道

由于 powershell 输出的均为对象,管道传递的是对象。linux 的管道传递的是字符串。

管道的对象修改仅在使用 ft/fl 之后

使用 select 可以将输出结果显示更少,或更多。默认显示有限,但是对象有很多的属性,为了完全显示,可以使用| select *

1
Get-Process notepad  | select *

当选择所有字段,就会显示对象所有属性,一行显示不下,就会纵向显示。也可以显示更少的

1
2
3
4
5
6
14:49 [PS] C:\Windows\system32 :>  Get-Process notepad  | select name,id,cpu,VirtualMemorySize

Name Id CPU VirtualMemorySize
---- -- --- -----------------
Notepad 17848 0.5625 560594944
Notepad 21288 1.390625 564748288

这里显示的改变了,但是每行还是对象。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
14:50 [PS] C:\Windows\system32 :>  Get-Process notepad  | select name,id,cpu,VirtualMemorySize | gm


TypeName:Selected.System.Diagnostics.Process

Name MemberType Definition
---- ---------- ----------
Equals Method bool Equals(System.Object obj)
GetHashCode Method int GetHashCode()
GetType Method type GetType()
ToString Method string ToString()
CPU NoteProperty System.Double CPU=0.5625
Id NoteProperty int Id=17848
Name NoteProperty string Name=Notepad
VirtualMemorySize NoteProperty int VirtualMemorySize=560594944

注意输出是TypeName:Selected.System.Diagnostics.Proc

更少的字段输出的是表格,我们显示列

1
2
3
4
5
6
7
8
9
10
11
12
14:51 [PS] C:\Windows\system32 :>  Get-Process notepad  | select name,id,cpu,VirtualMemorySize | fl


Name : Notepad
Id : 17848
CPU : 0.5625
VirtualMemorySize : 560594944

Name : Notepad
Id : 21288
CPU : 1.390625
VirtualMemorySize : 564748288

显示列之后,对象就不存在了

1
2
3
4
14:51 [PS] C:\Windows\system32 :>  Get-Process notepad  | select name,id,cpu,VirtualMemorySize | fl | gm


TypeName:Microsoft.PowerShell.Commands.Internal.Format.FormatStartData

ft/fl 均一样

当 select 之后,我们还可以使用对象的操作,ft/fl 之后,就不能使用对象的操作了

select 之后,期望 name 显示为 processname

1
2
3
4
5
6
15:12 [PS] C:\Windows\system32 :>  Get-Process notepad  | select name,id,cpu,VirtualMemorySize

Name Id CPU VirtualMemorySize
---- -- --- -----------------
Notepad 17848 0.578125 560594944
Notepad 21288 1.390625 564748288
1
2
3
4
5
6
15:14 [PS] C:\Windows\system32 :>  Get-Process notepad  | select @{L='ProcessName';E={$_.name} },id,cpu,VirtualMemorySize

ProcessName Id CPU VirtualMemorySize
----------- -- --- -----------------
Notepad 17848 0.578125 560594944
Notepad 21288 1.390625 564748288

这里的修改显示字段名的语法可以使用在 select 中,@{L='ProcessName';E={$_.name} } L 是显示的名,E 是表达式,可以求值。值就是每行这个字段显示的值。

格式化

之前我们显示的表格,可以通过 select 来显示更少或更多字段

有 ft,可以显示为表格,fl 显示为列。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
14:54 [PS] C:\Windows\system32 :>  Get-Service

Status Name DisplayName
------ ---- -----------
Stopped AarSvc_503ac AarSvc_503ac
Stopped AJRouter AllJoyn Router Service
Stopped ALG Application Layer Gateway Service
Stopped AppIDSvc Application Identity
Running Appinfo Application Information
Stopped AppMgmt Application Management
Stopped AppReadiness App Readiness
Stopped AppVClient Microsoft App-V Client
Stopped AppXSvc AppX Deployment Service (AppXSVC)
Stopped AssignedAccessM... AssignedAccessManager 服务
Running AudioEndpointBu... Windows Audio Endpoint Builder
Running Audiosrv Windows Audio
Stopped autotimesvc 手机网络时间

这里可以看出有...省略,说明没有显示完。我们可以添加选项显示完

1
2
3
4
5
6
7
8
9
10
11
12
13
14
14:54 [PS] C:\Windows\system32 :>  Get-Service | ft -AutoSize -Wrap

Status Name DisplayName
------ ---- -----------
Stopped AarSvc_503ac AarSvc_503ac
Stopped AJRouter AllJoyn Router Service
Stopped ALG Application Layer Gateway Service
Stopped AppIDSvc Application Identity
Running Appinfo Application Information
Stopped AppMgmt Application Management
Stopped AppReadiness App Readiness
Stopped AppVClient Microsoft App-V Client
Stopped AppXSvc AppX Deployment Service (AppXSVC)
Stopped AssignedAccessManagerSvc AssignedAccessManager 服务

powershell 脚本编程

循环

1
2
3
4
5
for (($i = 0), ($j = 0); $i -lt 10; $i++, $j++)
{
"`$i:$i"
"`$j:$j"
}

命令直接循环

1
2
3
4
5
6
7
8
9
10
11
14:46 [PS] C:\Windows\system32 :>  Get-Process notepad

Handles NPM(K) PM(K) WS(K) CPU(s) Id SI ProcessName
------- ------ ----- ----- ------ -- -- -----------
655 33 47000 52196 0.56 17848 1 Notepad
676 35 47476 57476 1.39 21288 1 Notepad


14:46 [PS] C:\Windows\system32 :> Get-Process notepad | %{ $_.name }
Notepad
Notepad
  • 这里的%是 foreach 的别名,会遍历 每个对象。 {} 是语句块,是循环每个对象,其中引用每一个对象使用$_

选择

1
help about_If

判断文件时,我们使用 test 表达式

1
2
3
4
5
6
7
14:56 [PS] C:\Windows\system32 :>  Get-Command -Verb test -Module Microsoft.PowerShell.Management

CommandType Name Version Source
----------- ---- ------- ------
Cmdlet Test-ComputerSecureChannel 3.1.0.0 Microsoft.PowerShell.Management
Cmdlet Test-Connection 3.1.0.0 Microsoft.PowerShell.Management
Cmdlet Test-Path 3.1.0.0 Microsoft.PowerShell.Management
1
2
14:57 [PS] C:\Windows\system32 :>  if(test-path d:/test) { '123' } else { 'not exist' }
not exist

字符串替换

1
help about_Comparison_Operators
1
2
14:57 [PS] C:\Windows\system32 :>  "hello world" -replace 'll\S\s','123'
he123world
  • 正则匹配,目标字符串

算术运算

1
help about_Arithmetic_Operators

命令行可以直接进行一些算术操作

1
2
15:09 [PS] C:\Windows\system32 :>  1+2+3+4
10

编写脚本

脚本策略

1
Set-ExecutionPolicy RemoteSigned

RemoteSigned 表示 PowerShell可以运行本地任何脚本,同时也可以执行受信任的 CA 签发的数字证书签名之后的远程脚本。“远程脚本”是指存在于远端计算机上的脚本,经常通过通用命名规则(UNC)方式访问这些脚本。我们也会将那些来自于网络上的脚本称为“远程脚本”。Internet Explorer、Firefox 和 Outlook 中提供的可下载的脚本,我们均可视为来自网络的脚本。在某些版本的 Windows 中,会区分网络路径以及 UNC 路径。在这些场景中,本地网络中的 UNC 都不会认为是“远程”。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
<#
.SYNOPSIS
从1个或多个计算机获取逻辑磁盘信息
.DESCRIPTION
使用WMI接口从1或多个主机获取, 可用空间大于50%的win32_logicaldisk实例。 显示磁盘驱动,空间空间,总大小,空闲百分比
.PARAMETER drivetype
磁盘类型,默认3
.PARAMETER gtfree
可用空间百分比
.PARAMETER computername
远程计算机名
.EXAMPLE
get-disk -computername localhost -drivetype 3 -gtfree 80
#>
[cmdletbinding()]
param (
[int]$drivetype = 3,
[int]$gtfree=50,
[Parameter(Mandatory=$true,HelpMessage="enter a or a set computer to query")]
[string]$computername
)

Get-WmiObject win32_logicaldisk -com $computername -filter "drivetype=$drivetype" | ? { ($_.freespace / $_.size * 100 ) -gt $gtfree} | select deviceid,
@{L='freesize(gb)';E={$_.freespace / 1gb -as [int]}},
@{L='size(gb)';E={$_.size / 1gb -as [int]}},
@{L='%free';E={ $_.freespace / $_.size *100 -as [int]}}
  1. <# #> 定义脚本的帮助。.KEYWORD 定义语法,变量对应的参数和值,和描述。 示例。powershell 会自动解析为, 帮助的各部分

  2. 参数段

    1
    2
    3
    4
    5
    6
    7
    [cmdletbinding()]
    param (
    [int]$drivetype = 3,
    [int]$gtfree=50,
    [Parameter(Mandatory=$true,HelpMessage="enter a or a set computer to query")]
    [string]$computername
    )

[cmdletbinding()] 固定语法在param()

$drivetype = 3 这个是定义变量,powershell 会自动解析为命令行参数,忽略大小写。 -drivetype, -drive, 可以简短格式,要求惟一

[int] [string]

[Parameter(Mandatory=$true,HelpMessage="enter a or a set computer to query")] 是参数检验,要求字符,要求整整型。要求必给,不给,交互式提示输入。

  1. 脚本内容部分

    1
    2
    3
    4
    Get-WmiObject win32_logicaldisk -com $computername -filter "drivetype=$drivetype" | ? { ($_.freespace / $_.size * 100 ) -gt $gtfree} | select deviceid,
    @{L='freesize(gb)';E={$_.freespace / 1gb -as [int]}},
    @{L='size(gb)';E={$_.size / 1gb -as [int]}},
    @{L='%free';E={ $_.freespace / $_.size *100 -as [int]}}

这里就是命令,只是可变的部分已抽成参数。

执行

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
15:23 [PS] D:\ :>  .\test.ps1 -?

名称
D:\test.ps1

摘要
1个或多个计算机获取逻辑磁盘信息


语法
D:\test.ps1 [[-drivetype] <Int32>] [[-gtfree] <Int32>] [-computername] <St
ring> [<CommonParameters>]


说明
使用WMI接口从1或多个主机获取, 可用空间大于50%的win32_logicaldisk实例。 显
示磁盘驱动,空间空间,总大小,空闲百分比


相关链接

备注
若要查看示例,请键入: "get-help D:\test.ps1 -examples".
有关详细信息,请键入: "get-help D:\test.ps1 -detailed".
若要获取技术信息,请键入: "get-help D:\test.ps1 -full".
1
2
D:\test.ps1 [[-drivetype] <Int32>] [[-gtfree] <Int32>] [-computername] <St
ring> [<CommonParameters>]

说明每个参数均可以按位置传递参数。

1
2
3
4
5
6
7
8
9
10
11
12
15:23 [PS] D:\ :>  .\test.ps1

位于命令管道位置 1 的 cmdlet test.ps1
请为以下参数提供值:
(请键入 !? 以查看帮助。)
computername: localhost

deviceid freesize(gb) size(gb) %free
-------- ------------ -------- -----
E: 82 122 67
F: 101 101 100
G: 396 447 89

本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!