简体   繁体   English

具有功能和开关的PowerShell Native Cmdlet Set-Alias

[英]PowerShell Native Cmdlet Set-Alias with Function and Switch

Question: Is it possible to set an alias that calls both a function and a switch? 问题:是否可以设置同时调用函数和开关的别名?

Here is an example I am working with. 这是我正在使用的一个例子。

Set-Alias -Name myidea -Value 'Test-FunctionIdea -SwitchIdea' 
function Test-FunctionIdea {
  param(
    [switch]$SwitchIdea
  )
  if($SwitchIdea)
  {
    Write-Host 'Good Idea'
  }
}

Here is the error I am having: 这是我遇到的错误:

myidea : The term 'Test-FunctionIdea -SwitchIdea' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if 
a path was included, verify that the path is correct and try again.
At line:1 char:1
+ myidea
+ ~~~~~~
    + CategoryInfo          : ObjectNotFound: (Test-FunctionIdea -SwitchIdea:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException

If it is possible please let me know how it's done. 如果有可能请告诉我它是如何完成的。 I've searched the internet for this and came up with no results. 我在互联网上搜索了这个并没有得到任何结果。

You can check $MyInvocation.InvocationName and adjust the parameters inside the function: 您可以检查$MyInvocation.InvocationName并调整函数内的参数:

function Some-Function([switch] $foo) {
     if ($MyInvocation.InvocationName -eq 'foo') { $foo = $true }
}

Set-Alias foo Some-Function

The [usually negligible] advantage is that it doesn't create an additional execution context for the new function scope. [通常可以忽略不计]的优点是它不会为新的函数范围创建额外的执行上下文。

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

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