01.理解powershell的特性
001.输出是对象
可以使用Get-Member查看输出的对象有那些成员,比如
Get-Process | Get-Member
TypeName: System.Diagnostics.Process
Name MemberType Definition
---- ---------- ----------
Handles AliasProperty Handles = Handlecount
Name AliasProperty Name = ProcessName
NPM AliasProperty NPM = NonpagedSystemMemorySize64
PM AliasProperty PM = PagedMemorySize64
SI AliasProperty SI = SessionId
VM AliasProperty VM = VirtualMemorySize64
WS AliasProperty WS = WorkingSet64
Parent CodeProperty System.Object Parent{get=GetParentProcess;}
Disposed Event System.EventHandler Disposed(System.Object, System.EventArgs)
ErrorDataReceived Event System.Diagnostics.DataReceivedEventHandler ErrorDataReceived(System.Object, System.Diagnostics.DataReceivedEventArgs) Exited Event System.EventHandler Exited(System.Object, System.EventArgs)
OutputDataReceived Event System.Diagnostics.DataReceivedEventHandler OutputDataReceived(System.Object, System.Diagnostics.DataReceivedEventArgs) BeginErrorReadLine Method void BeginErrorReadLine()
BeginOutputReadLine Method void BeginOutputReadLine()
CancelErrorRead Method void CancelErrorRead()
CancelOutputRead Method void CancelOutputRead()
Close Method void Close()
CloseMainWindow Method bool CloseMainWindow()
Dispose Method void Dispose(), void IDisposable.Dispose()
Equals Method bool Equals(System.Object obj)
GetHashCode Method int GetHashCode()
GetLifetimeService Method System.Object GetLifetimeService()
GetType Method type GetType()
InitializeLifetimeService Method System.Object InitializeLifetimeService()
Kill Method void Kill(), void Kill(bool entireProcessTree)
Refresh Method void Refresh()
Start Method bool Start()
ToString Method string ToString()
WaitForExit Method void WaitForExit(), bool WaitForExit(int milliseconds)
WaitForInputIdle Method bool WaitForInputIdle(), bool WaitForInputIdle(int milliseconds)
__NounName NoteProperty string __NounName=Process
BasePriority Property int BasePriority {get;}
Container Property System.ComponentModel.IContainer Container {get;}
EnableRaisingEvents Property bool EnableRaisingEvents {get;set;}
ExitCode Property int ExitCode {get;}
ExitTime Property datetime ExitTime {get;}
Handle Property System.IntPtr Handle {get;}
HandleCount Property int HandleCount {get;}
HasExited Property bool HasExited {get;}
Id Property int Id {get;}
MachineName Property string MachineName {get;}
MainModule Property System.Diagnostics.ProcessModule MainModule {get;}
MainWindowHandle Property System.IntPtr MainWindowHandle {get;}
MainWindowTitle Property string MainWindowTitle {get;}
MaxWorkingSet Property System.IntPtr MaxWorkingSet {get;set;}
MinWorkingSet Property System.IntPtr MinWorkingSet {get;set;}
Modules Property System.Diagnostics.ProcessModuleCollection Modules {get;}
NonpagedSystemMemorySize Property int NonpagedSystemMemorySize {get;}
NonpagedSystemMemorySize64 Property long NonpagedSystemMemorySize64 {get;}
PagedMemorySize Property int PagedMemorySize {get;}
PagedMemorySize64 Property long PagedMemorySize64 {get;}
PagedSystemMemorySize Property int PagedSystemMemorySize {get;}
PagedSystemMemorySize64 Property long PagedSystemMemorySize64 {get;}
PeakPagedMemorySize Property int PeakPagedMemorySize {get;}
PeakPagedMemorySize64 Property long PeakPagedMemorySize64 {get;}
PeakVirtualMemorySize Property int PeakVirtualMemorySize {get;}
PeakVirtualMemorySize64 Property long PeakVirtualMemorySize64 {get;}
PeakWorkingSet Property int PeakWorkingSet {get;}
PeakWorkingSet64 Property long PeakWorkingSet64 {get;}
PriorityBoostEnabled Property bool PriorityBoostEnabled {get;set;}
PriorityClass Property System.Diagnostics.ProcessPriorityClass PriorityClass {get;set;}
PrivateMemorySize Property int PrivateMemorySize {get;}
PrivateMemorySize64 Property long PrivateMemorySize64 {get;}
PrivilegedProcessorTime Property timespan PrivilegedProcessorTime {get;}
ProcessName Property string ProcessName {get;}
ProcessorAffinity Property System.IntPtr ProcessorAffinity {get;set;}
Responding Property bool Responding {get;}
SafeHandle Property Microsoft.Win32.SafeHandles.SafeProcessHandle SafeHandle {get;}
SessionId Property int SessionId {get;}
Site Property System.ComponentModel.ISite Site {get;set;}
StandardError Property System.IO.StreamReader StandardError {get;}
StandardInput Property System.IO.StreamWriter StandardInput {get;}
StandardOutput Property System.IO.StreamReader StandardOutput {get;}
StartInfo Property System.Diagnostics.ProcessStartInfo StartInfo {get;set;}
StartTime Property datetime StartTime {get;}
SynchronizingObject Property System.ComponentModel.ISynchronizeInvoke SynchronizingObject {get;set;}
Threads Property System.Diagnostics.ProcessThreadCollection Threads {get;}
TotalProcessorTime Property timespan TotalProcessorTime {get;}
UserProcessorTime Property timespan UserProcessorTime {get;}
VirtualMemorySize Property int VirtualMemorySize {get;}
VirtualMemorySize64 Property long VirtualMemorySize64 {get;}
WorkingSet Property int WorkingSet {get;}
WorkingSet64 Property long WorkingSet64 {get;}
PSConfiguration PropertySet PSConfiguration {Name, Id, PriorityClass, FileVersion}
PSResources PropertySet PSResources {Name, Id, Handlecount, WorkingSet, NonPagedMemorySize, PagedMemorySize, PrivateMemorySize, VirtualMemorySize, … Company ScriptProperty System.Object Company {get=$this.Mainmodule.FileVersionInfo.CompanyName;}
CPU ScriptProperty System.Object CPU {get=$this.TotalProcessorTime.TotalSeconds;}
Description ScriptProperty System.Object Description {get=$this.Mainmodule.FileVersionInfo.FileDescription;}
FileVersion ScriptProperty System.Object FileVersion {get=$this.Mainmodule.FileVersionInfo.FileVersion;}
Path ScriptProperty System.Object Path {get=$this.Mainmodule.FileName;}
Product ScriptProperty System.Object Product {get=$this.Mainmodule.FileVersionInfo.ProductName;}
ProductVersion ScriptProperty System.Object ProductVersion {get=$this.Mainmodule.FileVersionInfo.ProductVersion;}
002.命令家族可扩展
不同于cmd,你编写的的powershell脚本也可以被powershell识别。可以用Get-Help查看你写的帮助文档。就和使用官方自带的cmdlet没什么区别。
003.powershell处理控制台输入和显示
powershell自己有一套机制控制控制台输出。对所有的cmdlet具有高度一致性。
比如命令行解析,不需要你自己去写了,powershell自带一套很方便的解析机制。
输出格式化也是,自带一套解析机制
比如传统shell不同命令行工具的打印帮助的参数可能不一样,有的是/?有的是-?,但是在powershell里面,所有cmdlet统一是-?.
当在powershell中运行图形程序的时候,只有当接受数输入的或者应用程序有返回的时候powershell才进行干涉。不会影响应用程序的内部工作方式。
02.理解powershell的命名
001.cmdlet是动词-名词的构成形式
方便记忆命令,并且很容易从名字了解命令的作用。
比如说只要记10个动词和10个名字(20个单词的记忆量),就可以组成100个命令了。
可以使用Get-Command
分别查询有相关动词或名词的命令
PS> Get-Command -Verb Get
CommandType Name Definition
----------- ---- ----------
Cmdlet Get-Acl Get-Acl [[-Path] <String[]>]...
Cmdlet Get-Alias Get-Alias [[-Name] <String[]...
Cmdlet Get-AuthenticodeSignature Get-AuthenticodeSignature [-...
Cmdlet Get-ChildItem Get-ChildItem [[-Path] <Stri...
...
PS> Get-Command -Noun Service
CommandType Name Definition
----------- ---- ----------
Cmdlet Get-Service Get-Service [[-Name] <String...
Cmdlet New-Service New-Service [-Name] <String>...
Cmdlet Restart-Service Restart-Service [-Name] <Str...
Cmdlet Resume-Service Resume-Service [-Name] <Stri...
Cmdlet Set-Service Set-Service [-Name] <String>...
Cmdlet Start-Service Start-Service [-Name] <Strin...
Cmdlet Stop-Service Stop-Service [-Name] <String...
Cmdlet Suspend-Service Suspend-Service [-Name] <Str...
...
002.cmdlets 使用标准化参数
powershell自带命令行参数解析,定义变量接受参数,会自动把-
开头的参数导入变量。
所以在powershell中使用命令行参数,只要定义变量,然后使用就可以了。
有一些参数是所有cmdlet共用的,比如WhatIf, Confirm, Verbose, Debug, Warn, ErrorAction, ErrorVariable, OutVariable, and OutBuffer
推荐使用标准的参数名字,编写脚本的时候参考powershell自带的cmdlet命名就好了。比如 Force, Exclude, Include, PassThru, Path, and CaseSensitive.
03.使用已经熟悉的命令名
powershell支持别名,并且已经内置了一些别名,这样其他shell的使用者可以用他们熟悉的命令名了,虽然部分powershell的命令虽然名字一样,功能有差别。下面是一些支持的cmd和unix命令别名
cat | dir | mount | rm |
cd | echo | move | rmdir |
chdir | erase | popd | sleep |
clear | h | ps | sort |
cls | history | pushd | tee |
copy | kill | pwd | type |
del | lp | r | write |
diff | ls | ren |
适用Get-Alias
cmdlet可以通过别名获取命令在powershell中的真名。
例子:
PS> Get-Alias cls
CommandType Name Version Source
----------- ---- ------- ------
Alias cls -> Clear-Host
001.解释标准别名
之前描述的是为了兼容其他shell的命令别名,powershell大多数的别名只是为了使命令更简短,更容易打出。但是你如果不只要别名指向的命令名就很难读懂。
powershell内置的别名权衡了简洁性和清晰性。
例子:
Noun or Verb | Abbreviation |
---|---|
Get | g |
Set | s |
Item | i |
Location | l |
Command | cm |
Alias | al |
Cmdlet name | Alias |
---|---|
Get-Item |
gi |
Set-Item |
si |
Get-Location |
gl |
Set-Location |
sl |
Get-Command |
gcm |
Get-Alias |
gal |
002.创建新别名
使用Set-ALias
可以给命令定义新的别名
但是已经内置的别名你是不能定义新别名覆盖的,不然会报错。
举例
PS> Set-Alias -Name gi -Value Get-Item
Set-Alias : Alias is not writeable because alias gi is read-only or constant and cannot be written to.
At line:1 char:10
+ Set-Alias <<<< -Name gi -Value Get-Item
这样定义的别名只在当前会话有效,可以把别名写在自定义的$PROFILE文件中,这样每次打开终端都会执行一次设置别名的操作。实现自定义别名功能
04.获取详细帮助信息
001.获取关于cmd-let的帮助
Get-Help
cmdlet命令,可以获得关于cmdlet的信息
有以下两种方式获得帮助
比如:
Get-Help Get-ChildItem
或者:
Get-ChildItem -?
你也可以获得帮助的帮助,加上-Detailed(显示详细参数) -Full(显示所有信息) 选项可以获得更详细的信息。也可以只获得使用例子
-parameter选项查询制定参数
Get-Help Get-Help -Full
NAME
Get-Help
SYNOPSIS
Displays information about PowerShell commands and concepts.
SYNTAX
Get-Help [[-Name] <String>] [-Category {Alias | Cmdlet | Provider | General | FAQ | Glossary | HelpFile | ScriptCo
mmand | Function | Filter | ExternalScript | All | DefaultHelp | Workflow | DscResource | Class | Configuration}]
[-Component <String[]>] -Detailed [-Functionality <String[]>] [-Path <String>] [-Role <String[]>] [<CommonParamete
rs>]
Get-Help [[-Name] <String>] [-Category {Alias | Cmdlet | Provider | General | FAQ | Glossary | HelpFile | ScriptCo
mmand | Function | Filter | ExternalScript | All | DefaultHelp | Workflow | DscResource | Class | Configuration}]
[-Component <String[]>] -Examples [-Functionality <String[]>] [-Path <String>] [-Role <String[]>] [<CommonParamete
rs>]
Get-Help [[-Name] <String>] [-Category {Alias | Cmdlet | Provider | General | FAQ | Glossary | HelpFile | ScriptCo
mmand | Function | Filter | ExternalScript | All | DefaultHelp | Workflow | DscResource | Class | Configuration}]
[-Component <String[]>] [-Full] [-Functionality <String[]>] [-Path <String>] [-Role <String[]>] [<CommonParameters
>]
Get-Help [[-Name] <String>] [-Category {Alias | Cmdlet | Provider | General | FAQ | Glossary | HelpFile | ScriptCo
mmand | Function | Filter | ExternalScript | All | DefaultHelp | Workflow | DscResource | Class | Configuration}]
[-Component <String[]>] [-Functionality <String[]>] -Online [-Path <String>] [-Role <String[]>] [<CommonParameters
>]
Get-Help [[-Name] <String>] [-Category {Alias | Cmdlet | Provider | General | FAQ | Glossary | HelpFile | ScriptCo
mmand | Function | Filter | ExternalScript | All | DefaultHelp | Workflow | DscResource | Class | Configuration}]
[-Component <String[]>] [-Functionality <String[]>] -Parameter <String> [-Path <String>] [-Role <String[]>] [<Comm
onParameters>]
Get-Help [[-Name] <String>] [-Category {Alias | Cmdlet | Provider | General | FAQ | Glossary | HelpFile | ScriptCo
mmand | Function | Filter | ExternalScript | All | DefaultHelp | Workflow | DscResource | Class | Configuration}]
[-Component <String[]>] [-Functionality <String[]>] [-Path <String>] [-Role <String[]>] -ShowWindow [<CommonParame
ters>]
DESCRIPTION
The `Get-Help` cmdlet displays information about PowerShell concepts and commands, including cmdlets, functions, C
ommon Information Model (CIM) commands, workflows, providers, aliases, and scripts.
To get help for a PowerShell cmdlet, type `Get-Help` followed by the cmdlet name, such as: `Get-Help Get-Process`.
Conceptual help articles in PowerShell begin with about_ , such as about_Comparison_Operators . To see all about_
articles, type `Get-Help about_*`. To see a particular article, type `Get-Help about_<article-name>`, such as `Get
-Help about_Comparison_Operators`.
To get help for a PowerShell provider, type `Get-Help` followed by the provider name. For example, to get help for
the Certificate provider, type `Get-Help Certificate`.
You can also type `help` or `man`, which displays one screen of text at a time. Or, `<cmdlet-name> -?`, that is id
entical to `Get-Help`, but only works for cmdlets.
`Get-Help` gets the help content that it displays from help files on your computer. Without the help files, `Get-H
elp` displays only basic information about cmdlets. Some PowerShell modules include help files. Beginning in Power
Shell 3.0, the modules that come with the Windows operating system don't include help files. To download or update
the help files for a module in PowerShell 3.0, use the `Update-Help` cmdlet.
You can also view the PowerShell help documents online in the Microsoft Docs. To get the online version of a help
file, use the Online parameter, such as: `Get-Help Get-Process -Online`. To read all the PowerShell documentation,
see the Microsoft Docs PowerShell Documentation (/powershell).
If you type `Get-Help` followed by the exact name of a help article, or by a word unique to a help article, `Get-H
elp` displays the article's content. If you enter a word or word pattern that appears in several help article titl
es, `Get-Help` displays a list of the matching titles. If you enter a word that doesn't appear in any help article
titles, `Get-Help` displays a list of articles that include that word in their contents.
`Get-Help` can get help articles for all supported languages and locales. `Get-Help` first looks for help files in
the locale set for Windows, then in the parent locale, such as pt for pt-BR , and then in a fallback locale. Begi
nning in PowerShell 3.0, if `Get-Help` doesn't find help in the fallback locale, it looks for help articles in Eng
lish, en-US , before it returns an error message or displaying autogenerated help.
For information about the symbols that `Get-Help` displays in the command syntax diagram, see about_Command_Syntax
(./About/about_Command_Syntax.md). For information about parameter attributes, such as Required and Position , se
e about_Parameters (./About/about_Parameters.md).
>[!NOTE] > In PowerShell 3.0 and PowerShell 4.0, `Get-Help` can't find About articles in modules unless > the modu
le is imported into the current session. This is a known issue. To get About articles > in a module, import the mo
dule, either by using the `Import-Module` cmdlet or by running a cmdlet > that's included in the module.
PARAMETERS
-Category <String[]>
Displays help only for items in the specified category and their aliases. Conceptual articles are in the HelpF
ile category.
The acceptable values for this parameter are as follows:
- Alias
- Cmdlet
- Provider
- General
- FAQ
- Glossary
- HelpFile
- ScriptCommand
- Function
- Filter
- ExternalScript
- All
- DefaultHelp
- Workflow
- DscResource
- Class
- Configuration
Required? false
Position? named
Default value None
Accept pipeline input? False
Accept wildcard characters? false
-Component <String[]>
Displays commands with the specified component value, such as Exchange . Enter a component name. Wildcard char
acters are permitted. This parameter has no effect on displays of conceptual ( About_ ) help.
Required? false
Position? named
Default value None
Accept pipeline input? False
Accept wildcard characters? true
-Detailed [<SwitchParameter>]
Adds parameter descriptions and examples to the basic help display. This parameter is effective only when the
help files are installed on the computer. It has no effect on displays of conceptual ( About_ ) help.
Required? true
Position? named
Default value False
Accept pipeline input? False
Accept wildcard characters? false
-Examples [<SwitchParameter>]
Displays only the name, synopsis, and examples. To display only the examples, type `(Get-Help <cmdlet-name>).E
xamples`.
This parameter is effective only when the help files are installed on the computer. It has no effect on displa
ys of conceptual ( About_ ) help.
Required? true
Position? named
Default value False
Accept pipeline input? False
Accept wildcard characters? false
-Full [<SwitchParameter>]
Displays the entire help article for a cmdlet. Full includes parameter descriptions and attributes, examples,
input and output object types, and additional notes.
This parameter is effective only when the help files are installed on the computer. It has no effect on displa
ys of conceptual ( About_ ) help.
Required? false
Position? named
Default value False
Accept pipeline input? False
Accept wildcard characters? false
-Functionality <String[]>
Displays help for items with the specified functionality. Enter the functionality. Wildcard characters are per
mitted. This parameter has no effect on displays of conceptual ( About_ ) help.
Required? false
Position? named
Default value None
Accept pipeline input? False
Accept wildcard characters? true
-Name <String>
Gets help about the specified command or concept. Enter the name of a cmdlet, function, provider, script, or w
orkflow, such as `Get-Member`, a conceptual article name, such as `about_Objects`, or an alias, such as `ls`.
Wildcard characters are permitted in cmdlet and provider names, but you can't use wildcard characters to find
the names of function help and script help articles.
To get help for a script that isn't located in a path that's listed in the `$env:Path` environment variable, t
ype the script's path and file name.
If you enter the exact name of a help article, `Get-Help` displays the article contents.
If you enter a word or word pattern that appears in several help article titles, `Get-Help` displays a list of
the matching titles.
If you enter a word that doesn't match any help article titles, `Get-Help` displays a list of articles that in
clude that word in their contents.
The names of conceptual articles, such as `about_Objects`, must be entered in English, even in non-English ver
sions of PowerShell.
Required? false
Position? 0
Default value None
Accept pipeline input? True (ByPropertyName)
Accept wildcard characters? true
-Online [<SwitchParameter>]
Displays the online version of a help article in the default browser. This parameter is valid only for cmdlet,
function, workflow, and script help articles. You can't use the Online parameter with `Get-Help` in a remote
session.
For information about supporting this feature in help articles that you write, see about_Comment_Based_Help (.
/About/about_Comment_Based_Help.md), and Supporting Online Help (/powershell/scripting/developer/module/suppor
ting-online-help), and Writing Help for PowerShell Cmdlets (/powershell/scripting/developer/help/writing-help-
for-windows-powershell-cmdlets).
Required? true
Position? named
Default value False
Accept pipeline input? False
Accept wildcard characters? false
-Parameter <String>
Displays only the detailed descriptions of the specified parameters. Wildcards are permitted. This parameter h
as no effect on displays of conceptual ( About_ ) help.
Required? true
Position? named
Default value None
Accept pipeline input? False
Accept wildcard characters? true
-Path <String>
Gets help that explains how the cmdlet works in the specified provider path. Enter a PowerShell provider path.
This parameter gets a customized version of a cmdlet help article that explains how the cmdlet works in the sp
ecified PowerShell provider path. This parameter is effective only for help about a provider cmdlet and only w
hen the provider includes a custom version of the provider cmdlet help article in its help file. To use this p
arameter, install the help file for the module that includes the provider.
To see the custom cmdlet help for a provider path, go to the provider path location and enter a `Get-Help` com
mand or, from any path location, use the Path parameter of `Get-Help` to specify the provider path. You can al
so find custom cmdlet help online in the provider help section of the help articles.
For more information about PowerShell providers, see about_Providers (./About/about_Providers.md).
Required? false
Position? named
Default value None
Accept pipeline input? False
Accept wildcard characters? true
-Role <String[]>
Displays help customized for the specified user role. Enter a role. Wildcard characters are permitted.
Enter the role that the user plays in an organization. Some cmdlets display different text in their help files
based on the value of this parameter. This parameter has no effect on help for the core cmdlets.
Required? false
Position? named
Default value None
Accept pipeline input? False
Accept wildcard characters? true
-ShowWindow [<SwitchParameter>]
Displays the help topic in a window for easier reading. The window includes a Find search feature and a Settin
gs box that lets you set options for the display, including options to display only selected sections of a hel
p topic.
The ShowWindow parameter supports help topics for commands (cmdlets, functions, CIM commands, scripts) and con
ceptual About articles. It does not support provider help.
This parameter was reintroduced in PowerShell 7.0.
Required? true
Position? named
Default value False
Accept pipeline input? False
Accept wildcard characters? false
<CommonParameters>
This cmdlet supports the common parameters: Verbose, Debug,
ErrorAction, ErrorVariable, WarningAction, WarningVariable,
OutBuffer, PipelineVariable, and OutVariable. For more information, see
about_CommonParameters (https://go.microsoft.com/fwlink/?LinkID=113216).
INPUTS
None
You can't send objects down the pipeline to `Get-Help`.
OUTPUTS
ExtendedCmdletHelpInfo
If you run `Get-Help` on a command that doesn't have a help file, `Get-Help` returns an ExtendedCmdletHelpInfo
object that represents autogenerated help.
System.String
If you get a conceptual help article, `Get-Help` returns it as a string.
MamlCommandHelpInfo
If you get a command that has a help file, `Get-Help` returns a MamlCommandHelpInfo object.
NOTES
PowerShell 3.0 doesn't include help files. To download and install the help files that `Get-Help` reads, use t
he `Update-Help` cmdlet. You can use the `Update-Help` cmdlet to download and install help files for the core
commands that come with PowerShell and for any modules that you install. You can also use it to update the hel
p files so that the help on your computer is never outdated.
You can also read the help articles about the commands that come with PowerShell online starting at Getting St
arted with Windows PowerShell (/powershell/scripting/getting-started/getting-started-with-windows-powershell).
`Get-Help` displays help in the locale set for the Windows operating system or in the fallback language for th
at locale. If you don't have help files for the primary or fallback locale, `Get-Help` behaves as if there are
no help files on the computer. To get help for a different locale, use Region and Language in Control Panel t
o change the settings. On Windows 10, Settings , Time & Language .
The full view of help includes a table of information about the parameters. The table includes the following f
ields:
- Required . Indicates whether the parameter is required (true) or optional (false).
- Position . Indicates whether the parameter is named or positional (numeric). Positional parameters must ap
pear in a specified place in the command.
- Named indicates that the parameter name is required, but that the parameter can appear anywhere in the com
mand.
- Numeric indicates that the parameter name is optional, but when the name is omitted, the parameter must be
in the place specified by the number. For example, `2` indicates that when the parameter name is omitted, t
he parameter must be the second or only unnamed parameter in the command. When the parameter name is used, t
he parameter can appear anywhere in the command.
- Default value . The parameter value or default behavior that PowerShell uses if you don't include the para
meter in the command.
- Accepts pipeline input. Indicates whether you can (true) or can't (false) send objects to the parameter th
rough a pipeline. By Property Name means that the pipelined object must have a property that has the same na
me as the parameter name.
- Accepts wildcard characters . Indicates whether the value of a parameter can include wildcard characters,
such as an asterisk (`*`) or question mark (`?`).
--- Example 1: Display basic help information about a cmdlet ---
Get-Help Format-Table
Get-Help -Name Format-Table
Format-Table -?
`Get-Help <cmdlet-name>` is the simplest and default syntax of `Get-Help` cmdlet. You can omit the Name parameter.
The syntax `<cmdlet-name> -?` works only for cmdlets.
--- Example 2: Display basic information one page at a time ---
help Format-Table
man Format-Table
Get-Help Format-Table | Out-Host -Paging
`help` is a function that runs `Get-Help` cmdlet internally and displays the result one page at a time.
`man` is an alias for the `help` function.
`Get-Help Format-Table` sends the object down the pipeline. `Out-Host -Paging` receives the output from the pipeli
ne and displays it one page at a time. For more information, see Out-Host (Out-Host.md).
------- Example 3: Display more information for a cmdlet -------
Get-Help Format-Table -Detailed
Get-Help Format-Table -Full
The Detailed parameter displays the help article's detailed view that includes parameter descriptions and examples
.
The Full parameter displays the help article's full view that includes parameter descriptions, examples, input and
output object types, and additional notes.
The Detailed and Full parameters are effective only for the commands that have help files installed on the compute
r. The parameters aren't effective for the conceptual ( about_ ) help articles.
Example 4: Display selected parts of a cmdlet by using parameters
Get-Help Format-Table -Examples
Get-Help Format-Table -Parameter *
Get-Help Format-Table -Parameter GroupBy
The Examples parameter displays the help file's NAME and SYNOPSIS sections, and all the Examples. You can't specif
y an Example number because the Examples parameter is a switch parameter.
The Parameter parameter displays only the descriptions of the specified parameters. If you specify only the asteri
sk (`*`) wildcard character, it displays the descriptions of all parameters. When Parameter specifies a parameter
name such as GroupBy , information about that parameter is shown.
These parameters aren't effective for the conceptual ( about_ ) help articles.
---------- Example 5: Display online version of help ----------
Get-Help Format-Table -Online
-------- Example 6: Display help about the help system --------
Get-Help
---------- Example 7: Display available help articles ----------
Get-Help *
------- Example 8: Display a list of conceptual articles -------
Get-Help about_*
--------- Example 9: Search for a word in cmdlet help ---------
Get-Help Add-Member -Full | Out-String -Stream | Select-String -Pattern Clixml
the Export-Clixml cmdlet to save the instance of the object, including the additional members...
can use the Import-Clixml cmdlet to re-create the instance of the object from the information...
Export-Clixml
Import-Clixml
`Get-Help` uses the Full parameter to get help information for `Add-Member`. The MamlCommandHelpInfo object is sen
t down the pipeline. `Out-String` uses the Stream parameter to convert the object into a string. `Select-String` u
ses the Pattern parameter to search the string for Clixml .
-- Example 10: Display a list of articles that include a word --
Get-Help -Name remoting
Name Category Module Synopsis
---- -------- ------ --------
Install-PowerShellRemoting.ps1 External Install-PowerShellRemoting.ps1
Disable-PSRemoting Cmdlet Microsoft.PowerShell.Core Prevents remote users...
Enable-PSRemoting Cmdlet Microsoft.PowerShell.Core Configures the computer...
---------- Example 11: Display provider-specific help ----------
Get-Help Get-Item -Path SQLSERVER:\DataCollection
NAME
Get-Item
SYNOPSIS
Gets a collection of Server objects for the local computer and any computers
to which you have made a SQL Server PowerShell connection.
...
Set-Location SQLSERVER:\DataCollection
SQLSERVER:\DataCollection> Get-Help Get-Item
NAME
Get-Item
SYNOPSIS
Gets a collection of Server objects for the local computer and any computers
to which you have made a SQL Server PowerShell connection.
...
------------ Example 12: Display help for a script ------------
Get-Help -Name C:\PS-Test\MyScript.ps1
RELATED LINKS
Online Version: https://docs.microsoft.com/powershell/module/microsoft.powershell.core/get-help?view=powershell-7&
WT.mc_id=ps-gethelp
about_Command_Syntax
about_Comment_Based_Help
Get-Command
Supporting Updatable Help
Update-Help
Writing Comment-Based Help Topics
Writing Help for PowerShell Cmdlets
002.获取概念上的帮助
Get-Help
命令也内置了一些关于语法概念之类的文章,这些帮助文档会以about_开头
执行下面的命令
Get-Help about_*
我们发现有很多使用的帮助文档。我之前买书就买亏了,这么详细的文档,学起来就不需要别的书了
Name Category Module Synopsis
---- -------- ------ --------
about_PSReadLine HelpFile
about_Aliases HelpFile
about_Alias_Provider HelpFile
about_Arithmetic_Operators HelpFile
about_Arrays HelpFile
about_Assignment_Operators HelpFile
about_Automatic_Variables HelpFile
about_Break HelpFile
about_Certificate_Provider HelpFile
about_CimSession HelpFile
about_Classes HelpFile
about_Command_Precedence HelpFile
about_Command_Syntax HelpFile
about_Comment_Based_Help HelpFile
about_CommonParameters HelpFile
about_Comparison_Operators HelpFile
about_Continue HelpFile
about_Core_Commands HelpFile
about_Data_Sections HelpFile
about_Debuggers HelpFile
about_Do HelpFile
about_Enum HelpFile
about_Environment_Provider HelpFile
about_Environment_Variables HelpFile
about_Execution_Policies HelpFile
about_Experimental_Features HelpFile
about_FileSystem_Provider HelpFile
about_For HelpFile
about_Foreach HelpFile
about_Format.ps1xml HelpFile
about_Functions HelpFile
about_Functions_Advanced HelpFile
about_Functions_Advanced_Methods HelpFile
about_Functions_Advanced_Paramet… HelpFile
about_Functions_CmdletBindingAtt… HelpFile
about_Functions_OutputTypeAttrib… HelpFile
about_Function_Provider HelpFile
about_Group_Policy_Settings HelpFile
about_Hash_Tables HelpFile
about_Hidden HelpFile
about_History HelpFile
about_If HelpFile
about_Jobs HelpFile
about_Job_Details HelpFile
about_Join HelpFile
about_Language_Keywords HelpFile
about_Language_Modes HelpFile
about_Line_Editing HelpFile
about_Locations HelpFile
about_Logging_Non-Windows HelpFile
about_Logging_Windows HelpFile
about_Logical_Operators HelpFile
about_Methods HelpFile
about_Modules HelpFile
about_Numeric_Literals HelpFile
about_Objects HelpFile
about_Object_Creation HelpFile
about_Operators HelpFile
about_Operator_Precedence HelpFile
about_PackageManagement HelpFile
about_Parameters HelpFile
about_Parameters_Default_Values HelpFile
about_Parameter_Sets HelpFile
about_Parsing HelpFile
about_Path_Syntax HelpFile
about_Pipelines HelpFile
about_Pipeline_Chain_Operators HelpFile
about_PowerShell_Config HelpFile
about_PowerShell_Editions HelpFile
about_Preference_Variables HelpFile
about_Profiles HelpFile
about_Prompts HelpFile
about_Properties HelpFile
about_Providers HelpFile
about_PSConsoleHostReadLine HelpFile
about_PSSessions HelpFile
about_PSSession_Details HelpFile
about_Pwsh HelpFile
about_Quoting_Rules HelpFile
about_Redirection HelpFile
about_Ref HelpFile
about_Registry_Provider HelpFile
about_Regular_Expressions HelpFile
about_Remote HelpFile
about_Remote_Disconnected_Sessio… HelpFile
about_Remote_FAQ HelpFile
about_Remote_Jobs HelpFile
about_Remote_Output HelpFile
about_Remote_Requirements HelpFile
about_Remote_Troubleshooting HelpFile
about_Remote_Variables HelpFile
about_Requires HelpFile
about_Reserved_Words HelpFile
about_Return HelpFile
about_Run_With_PowerShell HelpFile
about_Scopes HelpFile
about_Scripts HelpFile
about_Script_Blocks HelpFile
about_Script_Internationalization HelpFile
about_Session_Configurations HelpFile
about_Session_Configuration_Files HelpFile
about_Signing HelpFile
about_Simplified_Syntax HelpFile
about_Special_Characters HelpFile
about_Splatting HelpFile
about_Split HelpFile
about_Switch HelpFile
about_Telemetry HelpFile
about_Thread_Jobs HelpFile
about_Throw HelpFile
about_Trap HelpFile
about_Try_Catch_Finally HelpFile
about_Types.ps1xml HelpFile
about_Type_Operators HelpFile
about_Updatable_Help HelpFile
about_Update_Notifications HelpFile
about_Using HelpFile
about_Variables HelpFile
about_Variable_Provider HelpFile
about_While HelpFile
about_Wildcards HelpFile
about_Windows_PowerShell_Compati… HelpFile
about_WSMan_Provider HelpFile
about_BeforeEach_AfterEach HelpFile performed at the beginning and end of every It …
about_Mocking HelpFile Pester provides a set of Mocking functions maki…
about_Pester HelpFile Pester is a BDD based test runner for PowerShel…
about_should HelpFile Provides assertion convenience methods for comp…
about_TestDrive HelpFile A PSDrive for file activity limited to the scop…
about_Scheduled_Jobs HelpFile Describes scheduled jobs and explains how to us…
about_Scheduled_Jobs_Advanced HelpFile Explains advanced scheduled job topics, includi…
about_Scheduled_Jobs_Basics HelpFile Explains how to create and manage scheduled job…
about_Scheduled_Jobs_Troubleshoo… HelpFile Explains how to resolve problems with scheduled…
about_ActivityCommonParameters HelpFile Describes the parameters that Windows PowerShell
about_Checkpoint-Workflow HelpFile Describes the Checkpoint-Workflow activity, whi…
about_ForEach-Parallel HelpFile Describes the ForEach -Parallel language constr…
about_InlineScript HelpFile Describes the InlineScript activity, which runs…
about_Parallel HelpFile Describes the Parallel keyword, which runs the
about_Sequence HelpFile Describes the Sequence keyword, which runs sele…
about_Suspend-Workflow HelpFile Describes the Suspend-Workflow activity, which …
about_WorkflowCommonParameters HelpFile This topic describes the parameters that are va…
about_Workflows HelpFile Provides a brief introduction to the Windows
003.获取provider相关信息
provider是基于.net的程序帮助你管理powrershell中存储的信息
你可以像访问磁盘驱动器访问目录访问文件一样访问他们,可以使用cd ls 命令查看
有一些内置的provider
Built-in providers
PowerShell includes a set of built-in providers that you can use to access
the different types of data stores.
Provider Drive Data store
------------- -------------- --------------------------------------------
Alias Alias: PowerShell aliases
Certificate Cert: x509 certificates for digital signatures
Environment Env: Windows environment variables
FileSystem (*) File system drives, directories, and files
Function Function: PowerShell functions
Registry HKLM:, HKCU: Windows registry
Variable Variable: PowerShell variables
WSMan WSMan: WS-Management configuration information
获取注册表相关帮助
Get-Help registry
004.获取脚本和函数的帮助
有些脚本或函数也有帮助文档,可以用Get-Help
显示
005.获取网上的帮助文档
最好的帮助文档是网上的,因为是实时更新的。使用Get-Help
命令的时候记得加上online选项。
05.获取命令相关信息
Get-Command
命令可以显示当前存在的命令。
执行这个命令后会显示类似下面的输出
CommandType Name Version Source
----------- ---- ------- ------
Cmdlet Add-Computer 3.1.0.0 Microsoft.PowerShell.Management
Cmdlet Add-Content 3.1.0.0 Microsoft.PowerShell.Management
Cmdlet Add-History 3.0.0.0 Microsoft.PowerShell.Core
Cmdlet Add-JobTrigger 1.1.0.0 PSScheduledJob
Cmdlet Add-LocalGroupMember 1.0.0.0 Microsoft.PowerShell.LocalAccounts
Cmdlet Add-Member 3.1.0.0 Microsoft.PowerShell.Utility
Cmdlet Add-PSSnapin 3.0.0.0 Microsoft.PowerShell.Core
Cmdlet Add-Type 3.1.0.0 Microsoft.PowerShell.Utility
...
有一个syntax选项可以帮助显示每个cmdlet命令的语法
比如执行西面这行命令。
Get-Command Get-Help -Syntax
命令分为以下几种类型:
- Aliases
- Functions
- Scripts
我们可以用命令类型来获取命令
Get-Command -CommandType Function
06.使用变量来存储对象
powershell中的变量名由英文字母,数字和下划线组成。当在powershell
中使用变量,需要在变量名前加上$
符号
创建一个变量很简单,此时变量没有值,所以不会有输出
$loc
下面是创建并赋值。
$loc = Get-Location
然后就有输出了
PS> $loc
Path
----
C:\temp
可以使用Get-Member
命令获取一个变量的相关信息
PS> $loc | Get-Member -MemberType Property
TypeName: System.Management.Automation.PathInfo
Name MemberType Definition
---- ---------- ----------
Drive Property System.Management.Automation.PSDriveInfo Drive {get;}
Path Property System.String Path {get;}
Provider Property System.Management.Automation.ProviderInfo Provider {...
ProviderPath Property System.String ProviderPath {get;}
001.变量操作
powershell提供了一些变量操作的命令,输入下面这条命令来查看
Get-Command -Noun Variable | Format-Table -Property Name,Definition -AutoSize -Wrap
Name Definition
---- ----------
Clear-Variable
Clear-Variable [-Name] <string[]> [-Include <string[]>] [-Exclude <string[]>] [-Force] [-PassThru] [-S
cope <string>] [-WhatIf] [-Confirm] [<CommonParameters>]
Get-Variable
Get-Variable [[-Name] <string[]>] [-ValueOnly] [-Include <string[]>] [-Exclude <string[]>] [-Scope <st
ring>] [<CommonParameters>]
New-Variable
New-Variable [-Name] <string> [[-Value] <Object>] [-Description <string>] [-Option <ScopedItemOptions>
] [-Visibility <SessionStateEntryVisibility>] [-Force] [-PassThru] [-Scope <string>] [-WhatIf] [-Confi
rm] [<CommonParameters>]
Remove-Variable
Remove-Variable [-Name] <string[]> [-Include <string[]>] [-Exclude <string[]>] [-Force] [-Scope <strin
g>] [-WhatIf] [-Confirm] [<CommonParameters>]
Set-Variable
Set-Variable [-Name] <string[]> [[-Value] <Object>] [-Include <string[]>] [-Exclude <string[]>] [-Desc
ription <string>] [-Option <ScopedItemOptions>] [-Force] [-Visibility <SessionStateEntryVisibility>] [
-PassThru] [-Scope <string>] [-WhatIf] [-Confirm] [<CommonParameters>]
powershell 也存在系统定义的变量(不能被这几个变量命令控制),可以使用 Remove-Variable
来移除。
输入下面的命令来移除所有变量
Remove-Variable -Name * -Force -ErrorAction SilentlyContinue
此时执行Get-Variable
命令看到的都是系统变量
powershell也创建了一个变量驱动器,可以使用下面的命令显示所有powershell变量
Get-ChildItem variable:
002.使用环境变量
powershell和所有其他windows进程共用一套环境变量,包括cmd。
可以使用env驱动器进行查看
执行下面的命令查看所有的环境变量
Get-ChildItem env:
上面提到的*-Variable
命令并不能用于处理环境变量
环境变量只能够通过env驱动器访问,比如访问%SystemRoot%
变量
PS> $env:SystemRoot
C:\WINDOWS
你也可以使用powershell创建和修改环境变量
比如
$env:LIB_PATH='/usr/local/lib'
07.理解powershell管道
001.powershell管道
管道可能是命令行接口中中最有价值的概念之一。使用得当,可以减少复杂的命令,看清命令工作流程。每个管道中的命令行都把他的输出传送给下一个命令。逐个项目处理,管道不需要处理超过一个项目。
举个例子,使用Out-Host
命令分页输出其他命令的输出
Get-ChildItem -Path C:\WINDOWS\System32 | Out-Host -Paging
会输出类似下面的内容:
Directory: C:\WINDOWS\system32
Mode LastWriteTime Length Name
---- ------------- ------ ----
d----- 4/12/2018 2:15 AM 0409
d----- 5/13/2018 11:31 PM 1033
d----- 4/11/2018 4:38 PM AdvancedInstallers
d----- 5/13/2018 11:13 PM af-ZA
d----- 5/13/2018 11:13 PM am-et
d----- 4/11/2018 4:38 PM AppLocker
d----- 5/13/2018 11:31 PM appmgmt
d----- 7/11/2018 2:05 AM appraiser
d---s- 4/12/2018 2:20 AM AppV
d----- 5/13/2018 11:10 PM ar-SA
d----- 5/13/2018 11:13 PM as-IN
d----- 8/14/2018 9:03 PM az-Latn-AZ
d----- 5/13/2018 11:13 PM be-BY
d----- 5/13/2018 11:10 PM BestPractices
d----- 5/13/2018 11:10 PM bg-BG
d----- 5/13/2018 11:13 PM bn-BD
d----- 5/13/2018 11:13 PM bn-IN
d----- 8/14/2018 9:03 PM Boot
d----- 8/14/2018 9:03 PM bs-Latn-BA
d----- 4/11/2018 4:38 PM Bthprops
d----- 4/12/2018 2:19 AM ca-ES
d----- 8/14/2018 9:03 PM ca-ES-valencia
d----- 5/13/2018 10:46 PM CatRoot
d----- 8/23/2018 5:07 PM catroot2
<SPACE> next page; <CR> next line; Q quit
...
这样可以减少资源占用,因为,Out-Host命令只有当完整的一页准备好的时候才会输出,管道前面的命令会停止执行直到下一页加载完成。
你可以使用任务管理器,比较下面两个命令的资源占用,包括cpu和内存
Get-ChildItem C:\Windows -Recurse
Get-ChildItem C:\Windows -Recurse | Out-Host -Paging
002.管道中的对象
当你在powershell中执行一个cmdlet,你会看到文本输出,因为需要用文本表示对象,以便在控制台窗口中显示出来。文本输出可能不会显示所有输出对象的属性。
举个例子,
PS> Get-Location
Path
----
C:\
当你使用Get-Location命令时,你只得到了一个信息的总结,而不是是对象的完整描述。
当你使用管道把结果传递给Get-Member
命令式,你将会得到这个对象的信息。
Get-Location | Get-Member
TypeName: System.Management.Automation.PathInfo
Name MemberType Definition
---- ---------- ----------
Equals Method bool Equals(System.Object obj)
GetHashCode Method int GetHashCode()
GetType Method type GetType()
ToString Method string ToString()
Drive Property System.Management.Automation.PSDriveInfo Drive {get;}
Path Property string Path {get;}
Provider Property System.Management.Automation.ProviderInfo Provider {get;}
ProviderPath Property string ProviderPath {get;}
08.可移植模块
windows下自带的powershell是基于 .NET Framework,另外有一套跨平台的powershell,叫做PowerShell Core是基于 .NET Core.编写的。
可移植模块指的是在这两种powershell中都能运行的模块。
两套powershell的api高度兼容,但是也有一些api是有所不同的,编写可移植模块的时候要注意这些不同
下面的内容主要是用.net编写powershell模块的,因为暂时用不到,所以先跳过
001.移植一个已经存在的模块
002.创建一个新模块
003..NET标准库
09.powershell远程操作
暂时用不到,跳过。
10.powershell术语表
Term | Definition |
---|---|
binary module | A Windows PowerShell module whose root module is a binary module file (.dll). A binary module may or may not include a module manifest. |
common parameter | A parameter that is added to all cmdlets, advanced functions, and workflows by the Windows PowerShell engine. |
dot source | In Windows PowerShell, to start a command by typing a dot and a space before the command. Commands that are dot sourced run in the current scope instead of in a new scope. Any variables, aliases, functions, or drives that command creates are created in the current scope and are available to users when the command is completed. |
dynamic module | A module that exists only in memory. The New-Module and Import-PSSession cmdlets create dynamic modules. |
dynamic parameter | A parameter that is added to a Windows PowerShell cmdlet, function, or script under certain conditions. Cmdlets, functions, providers, and scripts can add dynamic parameters. |
formatting file | A Windows PowerShell XML file that has the .format.ps1xml extension and that defines how Windows PowerShell displays an object based on its .NET Framework type. |
global session state | The session state that contains the data that is accessible to the user of a Windows PowerShell session. |
host | The interface that the Windows PowerShell engine uses to communicate with the user. For example, the host specifies how prompts are handled between Windows PowerShell and the user. |
host application | A program that loads the Windows PowerShell engine into its process and uses it to perform operations. |
input processing method | A method that a cmdlet can use to process the records it receives as input. The input processing methods include the BeginProcessing method, the ProcessRecord method, the EndProcessing method, and the StopProcessing method. |
manifest module | A Windows PowerShell module that has a manifest and whose RootModule key is empty. |
module manifest | A Windows PowerShell data file (.psd1) that describes the contents of a module and that controls how a module is processed. |
module session state | The session state that contains the public and private data of a Windows PowerShell module. The private data in this session state is not available to the user of a Windows PowerShell session. |
non-terminating error | An error that does not stop Windows PowerShell from continuing to process the command. |
noun | The word that follows the hyphen in a Windows PowerShell cmdlet name. The noun describes the resources upon which the cmdlet acts. |
parameter set | A group of parameters that can be used in the same command to perform a specific action. |
pipe | In Windows PowerShell, to send the results of the preceding command as input to the next command in the pipeline. |
pipeline | A series of commands connected by pipeline operators (|) (ASCII 124). Each pipeline operator sends the results of the preceding command as input to the next command. |
PSSession | A type of Windows PowerShell session that is created, managed, and closed by the user. |
root module | The module specified in the RootModule key in a module manifest. |
runspace | In Windows PowerShell, the operating environment in which each command in a pipeline is executed. |
script block | In the Windows PowerShell programming language, a collection of statements or expressions that can be used as a single unit. A script block can accept arguments and return values. |
script module | A Windows PowerShell module whose root module is a script module file (.psm1). A script module may or may not include a module manifest. |
script module file | A file that contains a Windows PowerShell script. The script defines the members that the script module exports. Script module files have the .psm1 file name extension. |
shell | The command interpreter that is used to pass commands to the operating system. |
switch parameter | A parameter that does not take an argument. |
terminating error | An error that stops Windows PowerShell from processing the command. |
transaction | An atomic unit of work. The work in a transaction must be completed as a whole; if any part of the transaction fails, the entire transaction fails. |
types file | A Windows PowerShell XML file that has the .ps1xml extension and that extends the properties of Microsoft .NET Framework types in Windows PowerShell. |
verb | The word that precedes the hyphen in a Windows PowerShell cmdlet name. The verb describes the action that the cmdlet performs. |
Windows PowerShell | A command-line shell and task-based scripting technology that provides IT administrators comprehensive control and automation of system administration tasks. |
Windows PowerShell command | The elements in a pipeline that cause an action to be carried out. Windows PowerShell commands are either typed at the keyboard or invoked programmatically. |
Windows PowerShell data file | A text file that has the .psd1 file name extension. Windows PowerShell uses data files for various purposes such as storing module manifest data and storing translated strings for script internationalization. |
Windows PowerShell drive | A virtual drive that provides direct access to a data store. It can be defined by a Windows PowerShell provider or created at the command line. Drives created at the command line are session-specific drives and are lost when the session is closed. |
Windows PowerShell Integrated Scripting Environment (ISE) | A Windows PowerShell host application that enables you to run commands and to write, test, and debug scripts in a friendly, syntax-colored, Unicode-compliant environment. |
Windows PowerShell module | A self-contained reusable unit that allows you to partition, organize, and abstract your Windows PowerShell code. A module can contain cmdlets, providers, functions, variables, and other types of resources that can be imported as a single unit. |
Windows PowerShell provider | A Microsoft .NET Framework-based program that makes the data in a specialized data store available in Windows PowerShell so that you can view and manage it. |
Windows PowerShell script | A script that is written in the Windows PowerShell language. |
Windows PowerShell script file | A file that has the .ps1 extension and that contains a script that is written in the Windows PowerShell language. |
Windows PowerShell snap-in | A resource that defines a set of cmdlets, providers, and Microsoft .NET Framework types that can be added to the Windows PowerShell environment. |
Windows PowerShell Workflow | A workflow is a sequence of programmed, connected steps that perform long-running tasks or require the coordination of multiple steps across multiple devices or managed nodes. Windows PowerShell Workflow lets IT pros and developers author sequences of multi-device management activities, or single tasks within a workflow, as workflows. Windows PowerShell Workflow lets you adapt and run both Windows PowerShell scripts and XAML files as workflows. |