在Powershell中,如何将变量传递给要添加到数组的命令?

时间:2016-11-29 00:06:59

标签: powershell

这里是业余脚本编写者,试图将计算机名称列表传递给命令,以便它循环遍历它们并给我他们的名字,操作系统和操作系统版本。

$Lab01comps = Get-ADComputer -SearchBase 'OU=Lab01,DC=domain,DC=domain,DC=domain' -Filter '*' | Select -Exp Name | sort
$Lab02comps = Get-ADComputer -SearchBase 'OU=Lab02,DC=domain,DC=domainstate,DC=edu' -Filter '*' | Select -Exp Name | sort

#This first one is more focused on just using a computer name in position 1. Example below code.
function Get-OS {
  [CmdletBinding(DefaultParameterSetName="Remote")]
    Param(
    [Parameter(Position=1,ParameterSetName="Local")]
    [Parameter(Position=2,ParameterSetName="Remote")]
    [string]$ComputerName,

    [System.Management.Automation.PSCredential]$Credential,

    [switch]$Raw
    )
  If (! $ComputerName) {
    $ComputerName = $env:COMPUTERNAME
  }
  foreach ($comp in $ComputerName) {
    Get-ADComputer $ComputerName -cred $cred -prop OperatingSystem,OperatingSystemVersion | select name,OperatingSystem,OperatingSystemVersion
  }
}
#Example
PS C:\> Get-OS LAB01COMP1
Name       OperatingSystem      OperatingSystemVersion
----       ---------------      ----------------------
LAB01COMP1 Windows 7 Enterprise 6.1 (7601)

#Attempt 2: This one works, but it requires adding to the $osq array before running just the command, with no parameters. Example below code.
$osq = @()
function Get-OS2 {
  foreach ($ComputerName in $osq) {
    Get-ADComputer $ComputerName -cred $cred -prop OperatingSystem,OperatingSystemVersion | select name,OperatingSystem,OperatingSystemVersion
  }
}
#Example
PS C:\> $osq += $Lab01comps
PS C:\> $osq
LAB01COMP1
LAB01COMP2
LAB01COMP3
PS C:\> Get-OS2
Name       OperatingSystem      OperatingSystemVersion
----       ---------------      ----------------------
LAB01COMP1 Windows 7 Enterprise 6.1 (7601)
LAB01COMP2 Windows 7 Enterprise 6.1 (7601)
LAB01COMP3 Windows 7 Enterprise 6.1 (7601)

我知道这可能是在这里发布的相当大的代码块,但我想展示我到目前为止所做的所有事情。我希望能做的是这样的事情:

PS C:\> Get-OS $Lab01comps
Name       OperatingSystem      OperatingSystemVersion
----       ---------------      ----------------------
LAB01COMP1 Windows 7 Enterprise 6.1 (7601)
LAB01COMP2 Windows 7 Enterprise 6.1 (7601)
LAB01COMP3 Windows 7 Enterprise 6.1 (7601)

我觉得我有一些简单的事情,但是我的尝试和在线帮助搜索都没有结果。在运行命令之前将变量提供给数组是一件简单的事情,但是对于代码本身和对我的知识追求,我想知道我是否做了什么。我想做的事情是可能的 谢谢!

1 个答案:

答案 0 :(得分:1)

正如PetSerAl所说,将空括号添加到字符串将起作用。

[string]$ComputerName becomes  [string[]]$ComputerName

这允许将数据视为数组,而不仅仅是字符串。请看下面的例子。

#Using just [String]
[string]$data = 'this','is','my','array'
$data[0]

这将只输出字母t,因为它取第一个位置即字母t。

但是,我们正在使用数组,而不仅仅是一串字母。所以当我们添加空括号

[string[]]$data = 'this','is','my','array'
$data[0]

现在输出单词'this',因为它被视为一个数组,该数组中的第一项是“this”。

还值得一提的是,您的第二个脚本有效,因为您使用= @()

将其声明为数组

没有它,它只是一个字符串变量。

希望这有帮助!我也是PowerShell的新手,但男孩学习它并不好玩吗?