excel - Making a list of computers and their rdp settings
问题描述
I'm trying to use Powershell to compile a simple excel spreadsheet that lists my computer's ping status's, RPD settings, and Hostnames.
I'm frustrated with the portion of the code that uses excel. I'm not really sure why, but when I run this code I'm getting an multiple errors for calling a method on a null value expression.
$ComputerList = Get-Content C:\Users\\Desktop\RDPSTATUS\ComputerList.txt
$excel_file_path = 'C:\Users\\Desktop\RDPSTATUS\RDPSTATUS.xlsx'
# instantiate EXCEL object
$Excel = New-Object -ComObject Excel.Application
$ExcelWorkBook = $Excel.Workbooks.Open($excel_file_path)
$ExcelWorkSheet = $Excel.Worksheets.item("sheet1")
$ExcelWorksheet.activate()
$row = 0
$col = 0
$ExcelWorkSheet.Cells.Item($row , $col) = "Device Name"
$ExcelWorkSheet.Cells.Item($row , $col++) = "RDP Status"
$ExcelWorkSheet.Cells.Item($row , $col+2) = "ping Status"
$row = 1
foreach ($computername in $ComputerList){
$ExcelWorkSheet.Cells.Item($row , $col) = $computername
$PingStatus = Gwmi Win32_PingStatus -Filter "Address = '$computername'" | Select-Object StatusCode
If ($PingStatus.StatusCode -eq 0)
{
$reg = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey('LocalMachine', $computername )
$regKey= $reg.OpenSubKey("System\\CurrentControlSet\\Control\\Terminal Server" ,$true)
$Value = $regkey.GetValue("fDenyTSConnections")
$ExcelWorkSheet.Cells.Item($row , $col+2) = "PING"
}
else {
$ExcelWorkSheet.Cells.Item($row , $col+2) = "NO PING"
}
If ($Value -eq 1){
$ExcelWorkSheet.Cells.Item($row , $col++) = "RDP is Disabled"
}
If ($Value -eq 0){
$ExcelWorkSheet.Cells.Item($row , $col++) = "RDP is Enabled"
}
}
$ExcelWorkBook.Save()
$ExcelWorkBook.Close()
$Excel.Quit([System.Runtime.Interopservices.Marshal]::ReleaseComObject($Excel))
Stop-Process -Name EXCEL -Force
解决方案
你有几个直接的问题,我可以看到:
$ExcelWorkSheet = $Excel.Worksheets.item("sheet1")
应该是$ExcelWorkbook.Worksheets.item("sheet1")
。工作表是工作簿的属性,而不是 Excel 应用程序的属性。$row
并且$col
起始值应该是1
,而不是0
。$ExcelWorksheet.activate()
没有必要。
推荐阅读
- java - 如何在 Java 中打开 Excel 工作簿并删除所有只有标题行的工作表
- jquery - :active 伪类无法正常工作
- java - 有什么方法可以避免在 java map-struct 中使用原始字符串?
- javascript - 基于昨天在 Firestore 中的“何处”条件?
- python - tkinter 中的 button_press_event(仅左键单击)
- ios - 如何根据 UISwitch 所在的单元格更改 UISwitch 的功能
- javascript - 在 Angular 中使用 push 方法更新对象数组
- c - 遍历单链表不起作用,为什么?
- python - 使用`pathlib.Path().glob()`迭代文件时如何将文件名提取为字符串?
- chilkat-email - Chilkat:如何检查给定电子邮件的回复 - Original-Envelope-Id