How to alias a parameterized function as a flag in powershell script?

邮差的信 提交于 2019-12-11 07:57:43

问题


I have a PS script which has a few functions in it. What I need is that I should be able to pass the specific function to the PS script as an alias or a variable flag.

For Eg: Suppose I have a TestFunc.ps1 file having 2 functions as below

$XmlFilePath = "C:\XmlPath\file1.xml
Function ParseXml($XmlFilePath)
{
#Do Something
}

Function CreateReport($XmlFilePath)
{
#Do Something
}

Now how can I create an alias for both the functions (ParseXml and CreateReport) so that I could pass each of them as a flag (using their alias) to the script? For Eg: I should be able to do something like:

. .\TestFunc.ps1 -Xml #This must be able to execute the ParseXml($XmlFilePath) function for me
. .\TestFunc.ps1 -Report #This must execute CreateReport($XmlFilePath) function

Any help would be greatly appreciated. I have been struggling in this for a while now.

Thanks! Ashu


回答1:


You can add some switch parameter to your script and test if they are sets:

param( [switch]$xml, [switch]$Report)    

Function ParseXml($XmlPath)
{
  "Parse"
}

Function CreateReport($XmlPath)
{
  "Report"
}

 $XmlPath = "C:\XmlPath\file1.xml"

if ($xml) 
    { 
        ParseXml $XmlPath 
    } 
if ($Report)
    {    
        CreateReport $xmlPath     
    }


来源:https://stackoverflow.com/questions/12895099/how-to-alias-a-parameterized-function-as-a-flag-in-powershell-script

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!