簡體   English   中英

參數的變量類型問題? - 電源外殼

[英]Variable Type Issue For Parameter? - Powershell

我正在嘗試運行以下代碼來搜索 OU 中的非活動用戶帳戶。 似乎我使用的變量類型可能無法與參數一起使用。 這看起來正確嗎?如果正確,我應該使用什么類型的變量?

$scope = "-UsersOnly" 

$accounts = Search-ADAccount -SearchBase "OU=Users,OU=testLab02,DC=test,DC=local" -AccountInactive -TimeSpan ([timespan]7D) $scope
    foreach($account in $accounts){
        If ($noDisable -notcontains $account.Name) {
            Write-Host $account
            #Disable-ADAccount -Identity $account.DistinguishedName -Verbose $whatIf | Export-Csv $logFile
        }
    }

我收到以下錯誤:

在此處輸入圖片說明

Search-ADAccount :找不到接受參數“-UsersOnly”的位置參數。 在 C:\\Users\\Administrator\\Documents\\Disable-ADAccounts.ps1:63 char:21 + ... $accounts = Search-ADAccount -SearchBase $OU.DistinguishedName -Accou ... + ~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : InvalidArgument: (:) [Search-ADAccount], ParameterBindingException +fullyQualifiedErrorId : PositionalParameterNotFound,Microsoft.ActiveDirectory.Management.Commands.SearchADAccount

但是,如果我在沒有變量的情況下手動運行命令,它會按預期工作:

Search-ADAccount -SearchBase "OU=Users,OU=testLab02,DC=test,DC=local" -AccountInactive -TimeSpan ([timespan]7D) -UsersOnly

在此處輸入圖片說明

$scope = "-UsersOnly"

您不能以這種方式傳遞存儲在變量中的 (switch)參數- 它總是會被視為 (positional) argument ,這解釋了您看到的錯誤; 對於直接傳遞的參數,只有不帶引號的文字標記(例如-UsersOnly被識別為參數名稱。

您可以使用splatting通過變量傳遞參數,在您的情況下,這意味着:

# Define a hash table of parameter values.
# This hash table encodes switch parameter -UsersOnly
$scope = @{ UsersOnly = $true } # [switch] parameters are represented as Booleans

# Note the use of sigil @ instead of $ to achieve splatting
Search-ADAccount @scope -SearchBase "OU=Users,OU=testLab02,DC=test,DC=local" -AccountInactive -TimeSpan ([timespan]7D) 
  • $scope被定義為一個hash table@{ ... } ),其條目表示參數名稱-值對

    • 這里只定義了一個參數名-值對:
      • 參數名稱-UsersOnly (必須在沒有- -UsersOnly情況下定義輸入鍵)...
      • ... 值為$true ,對於[switch] (flag) 參數相當於傳遞參數; $false通常[1]相當於省略它。
  • 通過由散列表所表示的參數值$scope經由到命令splatting ,印記@代替$必須使用的,即, @scope在這種情況下。


[1] 命令可以從技術上區分被省略的開關和它以$false值傳遞,有時會導致不同的行為,特別是使用通用的-Confirm參數,其中-Confirm:$false覆蓋$ConfirmPreference首選項多變的。

暫無
暫無

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

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