我正在尝试获取计算机的名称、制造商和型号,以便在AD中区分哪些计算机超出保修范围。
我试图通过获取计算机名称并将信息放入相应的.csv文件来实现这一点,但这失败了,将1个ou放入多个.csv文件,然后移动到第二个ou,并做同样的事情?
$myMultiArray = @(("OU=Domain Controllers,DC=FABRIKAM,DC=COM"),
("OU=Computers,DC=FABRIKAM,DC=COM"))
$myFileArray = @(("D:VS-CodePowershellAD_Computer_ManagementOUsDomain
Controllers.csv"),("D:VS-
CodePowershellAD_Computer_ManagementOUsComputers.csv"))
foreach ($MultiOU in $myMultiArray) {
Get-ADComputer -Filter * -SearchBase $MultiOU -SearchScope 2 | Select-object Name | Out-File -FilePath "D:VS-CodePowershellAD_Computer_ManagementOUsgarbage.csv"
For ($i = 0; $i – $myFileArray.Length - 1; $i++) {
Write-Host $myMultiArray[$i]
[string[]]$cnArray = Get-Content -Path 'D:VS-CodePowershellAD_Computer_ManagementOUsgarbage.csv'
Write-Host $OU
if ($i -eq $i) {
foreach($CN in $cnArray){
Get-WmiObject -Class:Win32_ComputerSystem -ComputerName $OU | Format-List -Property Name, Manufacturer, Model | Out-File -FilePath $myFileArray[$1]
}
}
}
}
我尝试过不同循环和if语句的多种变体。
我认为有两件事:
输出文件-文件路径$myFileArray〔$1〕
应该是:
Out-File -FilePath $myFileArray[$i]
此外,您可能需要附加:
Out-File -FilePath $myFileArray[$i] -Append
您的代码中有一些错误,比如$i – $myFileArray.Length
,它应该是$i –lt $myFileArray.Length
然后是Bernard Moeskops已经提到的Out-File -FilePath $myFileArray[$1]
此外,您的代码似乎希望创建Domain Controllers.csv
和Computers.csv
文件,而不考虑您当前所在的组织单位。
最后,您使用Out-File
创建CSV文件,为了获得正确的CSV输出,您应该使用Export-CSV cmdlet。
下面的代码应该做你想做的:
$myOUArray = "OU=Domain Controllers,DC=FABRIKAM,DC=COM", "OU=Computers,DC=FABRIKAM,DC=COM"
$myFilePath = "D:VS-CodePowershellAD_Computer_ManagementOUs" # just the path for the output files is needed
foreach ($OU in $myOUArray) {
# determine the file name from the OU we're in
$fileName = if ($OU -match 'OU=Domain Controllers') { 'Domain Controllers.csv' } else { 'Computers.csv'}
$filePath = Join-Path -Path $myFilePath -ChildPath $fileName
Write-Host "Getting computer info from OU '$OU'"
# get a string array of the computernames found in the OU
$computers = Get-ADComputer -Filter * -SearchBase $OU -SearchScope Subtree | Select-Object -ExpandProperty Name
# loop through this array to get the properties you want for
# each computer and store that as objects in the $result variable
$result = foreach($machine in $computers){
Get-WmiObject -Class:Win32_ComputerSystem -ComputerName $machine | Select-Object -Property Name, Manufacturer, Model
}
Write-Host "Creating file '$filePath'"
# save the CSV file to disk
$result | Export-Csv -Path $filePath -NoTypeInformation -Force
}