簡體   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