关于方法About methods

简短说明Short description

描述如何使用方法对 PowerShell 中的对象执行操作。Describes how to use methods to perform actions on objects in PowerShell.

长说明Long description

PowerShell 使用对象来表示数据存储区中的项或计算机的状态。PowerShell uses objects to represent the items in data stores or the state of the computer. 例如,FileInfo 对象表示文件系统驱动器中的文件,ProcessInfo 对象表示计算机上的进程。For example, FileInfo objects represent the files in file system drives and ProcessInfo objects represent the processes on the computer.

对象具有属性,这些属性存储有关对象的数据,以及用于更改对象的方法。Objects have properties, which store data about the object, and methods that let you change the object.

"方法" 是指定可对对象执行的操作的一组指令。A "method" is a set of instructions that specify an action you can perform on the object. 例如, FileInfo 对象包括 CopyTo 复制该对象所表示的文件的方法 FileInfoFor example, the FileInfo object includes the CopyTo method that copies the file that the FileInfo object represents.

若要获取任何对象的方法,请使用 Get-Member cmdlet。To get the methods of any object, use the Get-Member cmdlet. 使用值为 "Method" 的 MemberType 属性。Use its MemberType property with a value of "Method". 以下命令获取进程对象的方法。The following command gets the methods of process objects.

Get-Process | Get-Member -MemberType Method
TypeName: System.Diagnostics.Process

Name                      MemberType Definition
----                      ---------- ----------
BeginErrorReadLine        Method     System.Void BeginErrorReadLine()
BeginOutputReadLine       Method     System.Void BeginOutputReadLine()
...
Kill                      Method     System.Void Kill()
Refresh                   Method     System.Void Refresh()
Start                     Method     bool Start()
ToString                  Method     string ToString()
WaitForExit               Method     bool WaitForExit(int milliseconds), ...
WaitForInputIdle          Method     bool WaitForInputIdle(int millisecon...

若要执行或 "调用" 对象的方法,请键入 ( 点 ) 、方法名称和一组圆括号 " () "。To perform or "invoke" a method of an object, type a dot (.), the method name, and a set of parentheses "()". 如果该方法具有参数,请将参数值放在括号内。If the method has arguments, place the argument values inside the parentheses. 每个方法调用都需要括号,即使没有参数时也是如此。The parentheses are required for every method call, even when there are no arguments. 如果该方法采用多个参数,则应使用逗号分隔它们。If the method takes multiple arguments, they should be separated by commas.

例如,以下命令将调用进程的 Kill 方法,以结束计算机上的记事本进程。For example, the following command invokes the Kill method of processes to end the Notepad process on the computer.

$notepad = Get-Process notepad
$notepad.Kill()

可以通过组合以上语句来缩短此示例。This example can be shortened by combining the above statements.

(Get-Process Notepad).Kill()

Get-Process命令括在括号中,以确保在调用 Kill 方法之前运行该命令。The Get-Process command is enclosed in parentheses to ensure that it runs before the Kill method is invoked. Kill然后,在返回的对象上调用方法 ProcessThe Kill method is then invoked on the returned Process object.

另一种非常有用的方法是 Replace 字符串的方法。Another very useful method is the Replace method of strings. Replace方法将替换字符串中的文本。The Replace method, replaces text within a string. 在下面的示例中,点 (。 ) 可以紧跟在字符串的右引号之后。In the example below, the dot (.) can be placed immediately after the end quote of the string.

'this is rocket science'.Replace('rocket', 'rock')
this is rock science

如前面的示例所示,您可以对通过使用命令、变量中的对象或导致对象 (如引号) 中的字符串的任何内容的对象调用方法。As shown in the previous examples, you can invoke a method on an object that you get by using a command, an object in a variable, or anything that results in an object (like a string in quotes).

从 PowerShell 4.0 开始,支持通过使用动态方法名称进行方法调用。Starting in PowerShell 4.0, method invocation by using dynamic method names is supported.

了解方法Learning about methods

若要查找对象的方法的定义,请参阅对象类型的 "帮助" 主题,并查找其 "方法" 页。To find definitions of the methods of an object, go to help topic for the object type and look for its methods page. 例如,下面的页描述进程对象的处理方法。For example, the following page describes the methods of process objects System.Diagnostics.Process.

若要确定方法的参数,请查看方法定义,它类似于 PowerShell cmdlet 的语法关系图。To determine the arguments of a method, review the method definition, which is like the syntax diagram of a PowerShell cmdlet.

方法定义可能有一个或多个方法签名,如 PowerShell cmdlet 的参数集。A method definition might have one or more method signatures, which are like the parameter sets of PowerShell cmdlets. 签名显示了用于调用方法的所有有效命令格式。The signatures show all of the valid formats of commands to invoke the method.

例如,类的 CopyTo 方法 FileInfo 包含以下两个方法签名:For example, the CopyTo method of the FileInfo class contains the following two method signatures:

    CopyTo(String destFileName)
    CopyTo(String destFileName, Boolean overwrite)

第一种方法签名采用目标文件名 (,路径) 。The first method signature takes the destination file name (and a path). 下面的示例使用第一 CopyTo 种方法将 Final.txt 文件复制到 C:\Bin 目录。The following example uses the first CopyTo method to copy the Final.txt file to the C:\Bin directory.

(Get-ChildItem c:\final.txt).CopyTo("c:\bin\final.txt")

备注

与 PowerShell 的 参数 模式不同,对象方法以 表达式 模式执行,后者是对生成 PowerShell 的 .net framework 的传递。Unlike PowerShell's argument mode, object methods execute in expression mode, which is a pass-through to the .NET framework that PowerShell is built on. 表达式 模式中的 bareword 参数 (不允许使用不带引号的字符串) 。In expression mode bareword arguments (unquoted strings) are not allowed. 使用路径作为参数,而将路径用作参数时,可以看到这种差异。You can see this difference when using a the path as a parameter, versus the path as an argument. 可以在about_Parsing中详细了解分析模式You can read more about parsing modes in about_Parsing

第二个方法签名采用目标文件名和确定是否应覆盖目标文件(如果该文件已存在)的布尔值。The second method signature takes a destination file name and a Boolean value that determines whether the destination file should be overwritten, if it already exists.

下面的示例使用第二 CopyTo 种方法将 Final.txt 文件复制到 C:\Bin 目录,并覆盖现有文件。The following example uses the second CopyTo method to copy the Final.txt file to the C:\Bin directory, and to overwrite existing files.

(Get-ChildItem c:\final.txt).CopyTo("c:\bin\final.txt", $true)

标量对象和集合的方法Methods of Scalar objects and Collections

一个特定类型 ( "标量" ) 对象的方法通常不同于同一类型的对象集合的方法。The methods of one ("scalar") object of a particular type are often different from the methods of a collection of objects of the same type.

例如,每个进程都有一 Kill 种方法,但进程集合没有 Kill 方法。For example, every process has a Kill method, but a collection of processes does not have a Kill method.

从 PowerShell 3.0 开始,PowerShell 将尝试防止标量对象和集合的不同方法导致的脚本错误。Beginning in PowerShell 3.0, PowerShell tries to prevent scripting errors that result from the differing methods of scalar objects and collections.

如果提交集合,但请求仅存在于单个 ( "标量" ) 对象中的方法,则 PowerShell 将对集合中的每个对象调用方法。If you submit a collection, but request a method that exists only on single ("scalar") objects, PowerShell invokes the method on every object in the collection.

如果方法存在于单个对象和集合上,则只调用集合的方法。If the method exists on the individual objects and on the collection, only the collection's method is invoked.

此功能也适用于标量对象和集合的属性。This feature also works on properties of scalar objects and collections. 有关详细信息,请参阅 about_PropertiesFor more information, see about_Properties.

示例Examples

下面的示例在对象集合中运行单个进程对象的 Kill 方法。The following example runs the Kill method of individual process objects in a collection of objects.

第一条命令启动记事本进程的三个实例。The first command starts three instances of the Notepad process. Get-Process 获取记事本进程的所有三个实例,并将它们保存在 $p 变量中。Get-Process gets all three instance of the Notepad process and saves them in the $p variable.

Notepad; Notepad; Notepad
$p = Get-Process Notepad
$p.Count
3

下一个命令对变量中的所有三个进程运行 Kill 方法 $pThe next command runs the Kill method on all three processes in the $p variable. 即使进程集合没有方法,此命令也有效 KillThis command works even though a collection of processes does not have a Kill method.

$p.Kill()
Get-Process Notepad

Get-Process命令确认 Kill 方法是否有效。The Get-Process command confirms that the Kill method worked.

Get-Process : Cannot find a process with the name "notepad". Verify the proc
ess name and call the cmdlet again.
At line:1 char:12
+ Get-Process <<<<  notepad
    + CategoryInfo          : ObjectNotFound: (notepad:String) [Get-Process]
, ProcessCommandException
    + FullyQualifiedErrorId : NoProcessFoundForGivenName,Microsoft.PowerShel
l.Commands.GetProcessCommand

此示例在功能上等效于使用 Foreach-Object cmdlet 对集合中的每个对象运行方法。This example is functionally equivalent to using the Foreach-Object cmdlet to run the method on each object in the collection.

$p | ForEach-Object {$_.Kill()}

ForEach 和 Where 方法ForEach and Where methods

从 PowerShell 4.0 开始,支持使用方法语法的集合筛选。Beginning in PowerShell 4.0, collection filtering using a method syntax is supported. 这允许在处理集合和时使用两种新 ForEach 方法 WhereThis allows use of two new methods when dealing with collections ForEach and Where.

可阅读 about_arrays 了解有关这些方法的详细信息You can read more about these methods in about_arrays

当存在多个重载时调用特定方法Calling a specific method when multiple overloads exist

调用 .NET 方法时,请考虑以下方案。Consider the following scenario when calling .NET methods. 如果某个方法接受一个对象,但通过使用更具体的类型的接口具有重载,则 PowerShell 将选择接受该对象的方法,除非你将其显式转换为该接口。If a method takes an object but has an overload via an interface taking a more specific type, PowerShell chooses the method that accepts the object unless you explicitly cast it to that interface.

Add-Type -TypeDefinition @'

   // Interface
   public interface IFoo {
     string Bar(int p);
   }

   // Type that implements the interface
   public class Foo : IFoo {

   // Direct member method named 'Bar'
   public string Bar(object p) { return $"object: {p}"; }

   // *Explicit* implementation of IFoo's 'Bar' method().
   string IFoo.Bar(int p) {
       return $"int: {p}";
   }

}
'@

在此示例中,选择的是更少的 object Bar 方法重载。In this example the less specific object overload of the Bar method was chosen.

[Foo]::new().Bar(1)
object: 1

在此示例中,我们将方法强制转换为接口 IFoo ,以选择更具体的 Bar 方法重载。In this example we cast the method to the interface IFoo to select the more specific overload of the Bar method.

([IFoo] [Foo]::new()).Bar(1)
int: 1

使用采用文件系统路径的 .NET 方法Using .NET methods that take filesystem paths

PowerShell 支持每个进程运行多个运行空间。PowerShell supports multiple runspaces per process. 每个运行空间都有其自己的 当前目录Each runspace has its own current directory. 这与当前进程的工作目录不同: [System.Environment]::CurrentDirectoryThis is not the same as the working directory of the current process: [System.Environment]::CurrentDirectory.

.NET 方法使用进程工作目录。.NET methods use the process working directory. PowerShell cmdlet 使用运行空间位置。PowerShell cmdlets use the Runspace location. 此外,.NET 方法仅适用于本机文件系统路径,而不适用于 PowerShell 路径对象。Also, .NET methods only work with native filesystem paths, not PowerShell Path objects. 若要将 PowerShell 路径与 .NET 方法一起使用,必须先解析 filesystem 本地路径的路径,然后再将其传递到 .NET 方法。To use PowerShell paths with .NET methods, you must resolve the path to a filesystem-native path before passing it to the .NET method.

另请参阅See Also

about_Objectsabout_Objects

about_Propertiesabout_Properties

Get-MemberGet-Member