简体   繁体   English

向Powershell脚本添加两个选项

[英]Adding two options to a Powershell script

Forgive me as I'm still learning powershell so this might be a silly question, but how do I add an options to a .ps1? 原谅我,因为我仍在学习Powershell,所以这可能是一个愚蠢的问题,但是如何为.ps1添加选项? For example, I have currently have a script that downloads a file and runs it, but if it cant run it, it will look for the file locally and run it then. 例如,我目前有一个脚本来下载文件并运行它,但是如果它无法运行,它将在本地查找文件然后运行它。 How do I separate these two so the user can pick either to download or just run locally? 我如何分开这两个,以便用户可以选择下载还是直接在本地运行? eg: './script.ps1 local ' Will look for the file locally and run it './script.ps1 external' will download the file and run it I'm not sure if functions will be appropriate for this because the point of the script isn't to import it into the modules, I just want it so you run the .ps1. 例如:'./script.ps1 local'将在本地查找文件并运行'./script.ps1 external'将下载文件并运行它我不确定函数是否适合此操作,因为该脚本不是将其导入模块,我只想要它,因此您可以运行.ps1。

At the top of your file add; 在文件顶部添加;

Param(
  [Parameter(Position=1)][string]$option
)

Switch ($option)
{
   'local' { RunLocal }
   'other' { RunOther }
   default { RunDefault }
}

Would look something like 看起来像

Param(
  [Parameter(Position=1)][string]$option
)

function RunLocal {
 Write-Host "RunLocal"
}

function RunOther {
 Write-Host "RunOther"
}

function RunDefault {
 Write-Host "RunDefault"
}

Switch ($option)
{
   'local' { RunLocal }
   'other' { RunOther }
   default { RunDefault }
}

If you need to constrain the values passed to a parameter to a fixed set of values , use the [ValidateSet(...)] parameter attribute : 如果需要将传递给参数的值限制为一组固定值 ,请使用[ValidateSet(...)]参数属性

[CmdletBinding()]
Param(
  [ValidateSet('Local', 'External')]
  [string] $Option = 'Local'
)

Switch ($Option)
{
   'local' { 
      # ...
      break
    }
   'external' { 
      # ... 
      break
   }
}

The above defaults -Option (and thus parameter variable $Option ) to 'Local' , while allowing to pass either Local or External explicitly to -Option - no other values are permitted. 上面的默认值-Option (因此参数变量$Option )默认为'Local' ,同时允许将LocalExternal显式传递给-Option不允许其他值。

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

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