繁体   English   中英

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

[英]In Powershell, how do I pass a variable to a command to be added to an array?

这里是业余脚本编写者,试图将计算机名称列表传递给命令,以便它在它们之间循环,并仅给我提供其名称,操作系统和操作系统版本。

$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)

我感觉好像缺少一些简单的东西,但是我的尝试和在线帮助搜索都没有结果。 很简单,在运行命令之前将变量输入数组,但是对于代码本身以及对我的知识追求,我想知道我想做的事情是否可行。
谢谢!

正如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的新手,但是学习它不是很有趣吗?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM