简体   繁体   中英

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

How to pass a cmdlet or function name as a parameter:

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.

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, $ .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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