简体   繁体   中英

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

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

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     
    }

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