使用不同参数的选项

时间:2017-06-23 20:52:05

标签: powershell

我正在寻找一种在foreach循环中选择列表或单个计算机名的方法。

如果用户输入单个计算机名,我希望脚本为该计算机名执行 但如果该用户想要使用计算机列表的路径,我怎么能用用户想要的路径替换$ computername?

function Get-OSInfo {
[CmdletBinding()]
param (
    #[Parameter(ValueFromPipeline=$True,
    #           ValueFromPipelineByPropertyName=$True)]
    [string]$computername,

    [string]$errorlog = 'c:\errors.txt',

    [switch]$logerrors
)


PROCESS {
    foreach ($computer in $computername) {
        Try {
            $os = Get-WmiObject -EA Stop –Class Win32_OperatingSystem –ComputerName $computer 
            $cs = Get-WmiObject -EA Stop –Class Win32_ComputerSystem –ComputerName $computer 
            $bios = Get-WmiObject -EA Stop –Class Win32_BIOS –ComputerName $computer
            $cpu = Get-WmiObject -EA Stop -class Win32_processor -ComputerName $computer 
            $props = @{'ComputerName'=$computer;
                       'OSVersion'=$os.version;
                       'SPVersion'=$os.servicepackmajorversion;
                       'OSBuild'=$os.buildnumber;
                       'OSArchitecture'=$os.osarchitecture;
                       'Manufacturer'=$cs.manufacturer;
                       'Model'=$cs.model;
                       'BIOSSerial'=$bios.serialnumber
                       'CPU Count'=$CPU.Count
                       'Memory'= [Math]::round(($cs.TotalPhysicalMemory/1gb),2) 
                       'CPU Speed'= $CPU.MaxClockSpeed[0]}

            $obj = New-Object -TypeName PSOBject -Property $props
            $obj.PSObject.TypeNames.Insert(0,'Get-OS.OSInfo')
            #Write-Output $obj
            $obj | Export-Csv c:\test4.csv -Append

        } Catch {
            if ($logerrors) {
                $computer | Out-File $errorlog -append
            }
            Write-Warning "$computer failed"
        }

    }


}

}

1 个答案:

答案 0 :(得分:2)

$ComputerName参数的类型更改为字符串 array ,而不只是单个字符串:

param(
    [string[]]$ComputerName,

    [string]$errorlog = 'c:\errors.txt',

    [switch]$logerrors
)

注意类型名称后面的[],这表示一个字符串数组,而不是一个字符串。

现在你可以做到:

PS C:\> $computers = Get-Content C:\computers.txt
PS C:\> Get-OSInfo -ComputerName $computers

如果您希望能够指定包含目标计算机的文件的路径作为该函数的参数,则可以使用多个参数集:

[CmdletBinding(DefaultParameterSetName='ByName')]
param(
    [Parameter(ParameterSetName='ByName',ValueFromPipeline)]
    [string[]]$ComputerName,

    [Parameter(ParameterSetName='ByFile')]
    [string]$InputFile
)

begin {
    if($PSCmdlet.ParameterSetName -eq 'ByFile'){
        try{
            $ComputerName = Get-Content -LiteralPath $InputFile
        }
        catch{
            throw 
            return
        }
    }
}

process {
    foreach($Computer in $ComputerName){
        # Work with $Computer here...
    }
}