2016-01-20 61 views
1

我的腳本時提示的$ args:如何丟失

$computername=$args[0] 
if ($args -eq $null) { $computername = Read-Host "enter computer name" } 
Get-ADComputer -Id $computername -Properties * | select name,description 

如果我傳遞參數的腳本即:

get-ComputerName.ps1 computer01

它工作正常。但是,如果我跳過電腦,我希望它提示我,但我得到這個錯誤:

Get-ADComputer : Cannot validate argument on parameter 'Identity'. The argument 
is null. Provide a valid value for the argument, and then try running the 
command again. 
At U:\get-ADComputer-assigned-user.ps1:9 char:20 
+ Get-ADComputer -Id $computername -Properties * | select name,description 
+     ~~~~~~~~~~~~~ 
    + CategoryInfo   : InvalidData: (:) [Get-ADComputer], ParameterBindingValidationException 
    + FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.ActiveDirectory.Management.Commands.GetADComputer

我想不出如何使其工作。

+4

閱讀[高級功能幫助](https://technet.microsoft.com/en-us/library/hh847806.aspx)並使用強制參數 –

回答

3

不要使用automatic variable$args,而是定義一個特定的強制參數的計算機名:

[CmdletBinding()] 
Param(
    [Parameter(Mandatory=$true, Position=0)] 
    [string]$ComputerName 
) 

Get-ADComputer -Id $ComputerName -Properties * | Select-Object Name, Description 

這將讓你像這樣運行腳本:

./Get-ComputerName.ps1 -ComputerName computer01 

或類似這樣的:

./Get-ComputerName.ps1 computer01 

如果參數丟失,您將成爲pro mpted它:有關參數處理的進一步信息

[CmdletBinding()] 
Param(
    [Parameter(Mandatory=$false, Position=0)] 
    [string]$ComputerName = $(throw 'Parameter missing!') 
) 

Get-ADComputer -Id $ComputerName -Properties * | Select-Object Name, Description 

Checkthedocumentation

PS C:\>./Get-ComputerName.ps1 

cmdlet test.ps1 at command pipeline position 1 
Supply values for the following parameters: 
ComputerName: _

如果您希望腳本拋出,而不是提示缺少參數錯誤,你可以做這樣的在PowerShell中。