簡體   English   中英

如果腳本具有必需參數,PowerShell會調用函數

[英]Powershell calling a function if script has mandatory parameters

我對PowerShell還是很陌生,但是喜歡它可以自動執行Windows計算機上的任務負載。 我喜歡您可以從其他腳本中調用函數,但是我編寫的所有腳本都使用了用戶可以提供的參數(因此,同事更容易使用它們)。

特別是有一個參數,在我的腳本中通常是必需的。 我面臨的問題是從具有強制參數的腳本中調用函數。

這是一個簡單的例子:

Param(

 [Parameter()]
 [ValidateNotNullOrEmpty()]
 [string]$VirtualMachine=$(throw "Machine name missing!"),

 [int]$Attempts = 150

 )

Function DoSomething($VirtualMachine, $Attempts){

    write("$VirtualMachine and $Attempts")

 }

將其作為腳本運行,將提供-VirtualMachine "VMnameHere" -Attempts 123 運行此命令將生成VMnameHere and 123 完善! 但是..如果我嘗試從另一個腳本將此函數作為函數調用。

這里的例子:

. ".\Manage-Machine.ps1"

DoSomething -VirtualMachine "nwb-thisisamachine" -Attempts 500

這產生了一個錯誤:

Machine name missing!
At C:\Users\something\Desktop\Dump\play\Manage-Machine.ps1:33 char:28
+  [string]$VirtualMachine=$(throw "Machine name missing!"),
+                            ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : OperationStopped: (Machine name missing!:String) [], RuntimeException
    + FullyQualifiedErrorId : Machine name missing!

這顯然是因為該字段是必填字段。 在這種情況下,我在調用函數時是否做錯了什么? 如果該函數所屬的腳本具有強制性參數,是否有另一種方法來調用該函數,因為如果刪除該參數的驗證,則所有方法都可以工作。

希望有一些投入,

謝謝!

我將使用[parameter(Mandatory = $true)]並刪除=$(throw "Machine name missing!")

然后,您可以使用-NonInteractive標志( 文檔鏈接 )運行powershell,任何缺少的必需參數都將導致錯誤,並且將返回非零退出代碼。

此返回碼應由CI流程獲取,它本身將處理錯誤。

我不確定這樣做是否是個好主意,但聽起來以下方法可行:

Param(

  [ValidateNotNullOrEmpty()]
  # Do NOT use = $(Throw ...) or [Parameter(Mandatory)].
  [string]$VirtualMachine, 

  [int]$Attempts = 150

)

# Determine if the script is being "dot-sourced".
# Note: The `$MyInvocation.Line -eq ''` part detects being run from the
#       ISE or Visual Studio Code, which implicitly perform sourcing too.
$isDotSourced = $MyInvocation.InvocationName -eq '.' -or $MyInvocation.Line -eq ''

# NOT sourced? Enforce mandatory parameters.
if (-not $isDotSourced) {
  if (-not $VirtualMachine) { Throw "Machine name missing!" }
}

Function DoSomething($VirtualMachine, $Attempts) {
  "$VirtualMachine and $Attempts"
}


# NOT sourced? Call the default function or
# do whatever you want the script to do when invoked as a whole.
if (-not $isDotSourced) {
  DoSomething $VirtualMachine $Attempts
}
  • . .\\Manage-Machine.ps1 . .\\Manage-Machine.ps1將僅定義函數 (在本例中為DoSomething ),以供以后調用;
    由於從技術上講沒有一個腳本參數被聲明為強制性的,因此不帶參數的調用將成功(與您嘗試的情況一樣, throw語句總是插入-無論是直接調用還是點源)。

  • 相比之下, .\\Manage-Machine.ps1將強制存在$VirtualMachine參數值,並立即調用DoSomething ,將參數值傳遞通過。

請注意,當然,您的函數也可以從鍵入參數和添加驗證屬性中受益。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM