简体   繁体   English

如何在 powershell 中将 cmdlet 或 function 名称作为参数传递

[英]How to pass a cmdlet or function name as a parameter in powershell

How to pass a cmdlet or function name as a parameter:如何将 cmdlet 或 function 名称作为参数传递:

Write-Host "hi" | get-help <write-host>
# or
My-Custom-Function -arguments $some_arg | get-help <My-Custom-Function>

The most popular way to pass parameters into a function is to build a hashtable with all of the params you want to provide.将参数传递到 function 的最流行的方法是使用您要提供的所有参数构建一个哈希表。

Take this one for instance, to list all of the drives of a particular type on my computer.以这个为例,列出我计算机上特定类型的所有驱动器。

Get-CimInstance -Namespace root\cimv2 `
  -ClassName Win32_DiskDrive `
  -Filter "Caption='Samsung SSD 960 EVO 500GB'"

Kind of a lengthy command, right?有点冗长的命令,对吧? I can make a hashtable to include all of those values.我可以制作一个哈希表来包含所有这些值。

$params = @{
    Namespace = "root\cimv2"; 
    ClassName = "Win32_DiskDrive";
    Filter= "Caption='Samsung SSD 960 EVO 500GB'"
}

Then we go to invoke it, pay attention to the @ character, used in place of the normal variable character, $ .然后我们 go 来调用它,注意@字符,用于代替普通变量字符$

Get-CimInstance @params

If you're asking Why would I want to do this?如果你问我为什么要这样做? , well you see this very commonly done in functions which offer remote functionality. ,好吧,您会在提供远程功能的功能中看到这很常见。 A hashtable will be built and then modified based on the parameters provided or specified in the PowerShell envrionment and then handed off to an acting cmdlet to perform the actual function.将构建一个哈希表,然后根据 PowerShell 环境中提供或指定的参数进行修改,然后将其移交给执行的 cmdlet 以执行实际的 function。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM