需要一点帮助来完成我的第一个 Powershell 脚本......
我想为 AD 域中的所有 XP PC(约 3,000 台)创建一个 CSV 文件,并记录所有连接的打印机。最终我想知道我们有多少台本地连接的打印机。
我的“Googled”脚本会很乐意使用 WMI 扫描所有 PC 的打印机,并将结果输出到屏幕上。但是,我似乎无法重构代码以将结果输出到 CSV(通过Export-CSV
),这样就不会一直覆盖文件。我希望它附加到文件中。
# Get the list of computer names from AD
$strCategory = "computer"
$objDomain = New-Object System.DirectoryServices.DirectoryEntry
$objSearcher = New-Object System.DirectoryServices.DirectorySearcher
$objSearcher.SearchRoot = $objDomain
$objSearcher.CacheResults = -1
$objSearcher.PageSize = 5000
$objSearcher.SizeLimit = 5000
$objSearcher.Filter = ("(&(operatingSystemVersion=5*)(objectCategory=$strCategory)(operatingSystem=Windows XP*))")
$wmiPrinterClass = "win32_printer"
$colProplist = "name"
foreach ($i in $colPropList)
{$objSearcher.PropertiesToLoad.Add($i)}
$colResults = $objSearcher.FindAll()
$colResults.count
# for each computer, use WMI to scan for printers
foreach ($objComputer in $colResults)
{
$machine = $objComputer.Properties.name
$machine
get-WmiObject -class $wmiPrinterClass -computername $machine | `
ft systemName, name, shareName, Local -auto | `
Export-CSV "c:\printers.csv" #<<< HOW DO I STOP THIS FROM OVERWRITING???
}
该脚本将扫描所有 XP PC 的 AD,然后执行远程 WMI 搜索Win32_Printer
。如何将所有这些信息放入单个 CSV 文件中?
答案1
您需要将“-noClobber”选项用于 ExportCSV。
http://ss64.com/ps/export-csv.html
我还提出了一个可能有效的替代解决方案:
# Get the list of computer names from AD
$objDomain = New-Object System.DirectoryServices.DirectoryEntry
$objSearcher = New-Object System.DirectoryServices.DirectorySearcher
$objSearcher.SearchRoot = $objDomain
$objSearcher.CacheResults = -1
$objSearcher.PageSize = 5000
$objSearcher.SizeLimit = 5000
$objSearcher.PropertiesToLoad.Add("name")
$objSearcher.Filter = ("(&(operatingSystemVersion=5*)(objectCategory=computer)(operatingSystem=Windows XP*))")
$output = @()
# for each computer, use WMI to scan for printers
foreach ($objComputer in $objSearcher.FindAll())
{
$output += get-WmiObject -class "win32_printer" -computername $objComputer.Properties.name | ft systemName, name, shareName, Local -auto
}
Export-CSV "c:\printers.csv" -inputObject $output