
我寫了一個PS腳本來尋找機器上次啟動的時間(實際上是開機的,而不是剛剛啟動的,因為我們在Win10中啟用了快速啟動)。腳本似乎完成了它的工作,它返回了啟動日期/時間、最後一個使用者和主機名稱。但是,我將其作為 SCCM 中的腳本運行,並且不確定大規模處理輸出的最佳方法。
目前,腳本輸出到哈希表,這樣我就可以為最終讀取結果的每個值分配一個鍵。但我想如果你在 50 台機器上運行這個程序,你會希望能夠將結果放入電子表格或其他東西中進行排序/過濾。但複製匆忙的結果並不能很好地適應多種設備。
有人對如何最好地實現這一目標有任何建議嗎?值得注意的是,我遠非 PowerShell 專家,以下的內容很多很可能是低效或多餘的。另請忽略全名「(」上的分割。這與我們使用者帳戶的格式有關。
提前致謝。以下腳本的目前形式。
$LastBoot = Get-CimInstance -Class win32_operatingsystem | select lastbootuptime
$LastBoot = $LastBoot | Select -ExpandProperty "lastbootuptime"
$LastBoot = $LastBoot.ToString()
$LastBootDate = $LastBoot.split(" ")[0]
$LastBootTime = $LastBoot.split(" ")[1]
$LocalMachine = Get-CimInstance -ClassName win32_operatingsystem | select csname
$LocalMachine = $LocalMachine | Select -ExpandProperty "csname"
$Username = Get-CimInstance -Class win32_networkloginprofile | Sort-Object -Property LastLogon -Descending | Select -ExpandProperty "name" -First 1
$Username = $Username.split("\")[1]
$Domain = $env:userdomain
$Friendly = Get-CimInstance -Class win32_networkloginprofile | Sort-Object -Property LastLogon -Descending | Select -ExpandProperty "FullName" -First 1
$Friendly = $Friendly.split("(")[0]
$Results = @{
Hostname = $LocalMachine;
BootDate = $LastBootDate;
BootTime = $LastBootTime;
Username = $Username;
User = $Friendly
}
Write-Output $Results | Format-Table
答案1
如果要將結果匯出到 CSV 檔案中,請使用下列命令:
$result.GetEnumerator() | Export-CSV "filepath.csv" -NoTypeInformation
或者,如果您想將其放入 Excel 電子表格中:
$excel = new-Object -comobject Excel.Application
$excel.visible = $true # set it to $false if you don't need monitoring the actions...
$workBook = $excel.Workbooks.Add()
$sheet = $workBook.Sheets.Item(1)
$sheet.Name = "Result"
$sheet.Range("A1","A2").ColumnWidth = 40
$sheet.range('A:A').VerticalAlignment = -4160 #align is center (TOP -4108 Bottom -4107 Normal)
$sheet.Cells.Item(1,1) = " "
$sheet.cells.Item(1,2) = " "
$index = 2
$result.keys | ForEach {
$sheet.Cells.Item($index,1) = $_
$sheet.Cells.Item($index,2) = $result.item($_)
$index++
}
$workBook.SaveAs("C:\mylist.xls")
$excel.Quit()