2017-03-02 131 views
1

問題: 是否可以設置一個別名,同時調用一個函數和開關?PowerShell原生Cmdlet設置別名與功能和開關

這是我正在使用的示例。

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

這是我遇到的錯誤:

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 

如果可能的話,請讓我知道它是如何做。我已經在網上搜索了這個,並沒有得出任何結果。

+5

'function myidea {Test-FunctionIdea -SwitchIdea}'。 *「在Bash中,建議」對於幾乎所有目的而言,shell函數都優先於別名「...並且該建議對於PowerShell來說更加強大。PowerShell」alias「是一個真正的別名 - 它只是另一個名稱一個命令,腳本,函數等,它不支持傳遞參數或製作小腳本。「 - - https://web.archive.org/web/20120213013609/http://huddledmasses.org/ powershell-power-user-tips-bash-style-alias-command – TessellatingHeckler

+0

我第二個:) – 4c74356b41

+0

@TessellatingHeckler謝謝!像魅力一樣工作,你想回答這個問題,所以我可以給你適當的信用? –

回答

3

您可以檢查$MyInvocation.InvocationName和調節功能裏面的參數:

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

Set-Alias foo Some-Function 

的[通常可以忽略]優點是它不會創建新的功能範圍的附加執行上下文。

+2

我永遠不會在生產代碼中使用它,而是在有趣的方法中使用+1! – briantist