我想設計一個Powershell的代碼是想可以自動去一個網址然後截圖畫面再開一個Word檔並放進裡面,最終目的是可以去十個網址截圖再貼上一個Word裡面
我有個類似的代碼
Add-Type -AssemblyName Microsoft.Office.Interop.Word
Add-Type -AssemblyName System.Windows.Forms
function Test-ChromeInstalled {
$chromePath = (Get-ItemProperty 'HKLM:\Software\Microsoft\Windows\CurrentVersion\App Paths\chrome.exe' -ErrorAction SilentlyContinue).'(Default)'
return [bool]$chromePath
}
function Take-Screenshot {
param ($filePath)
$bitmap = New-Object System.Drawing.Bitmap([System.Windows.Forms.Screen]::PrimaryScreen.Bounds.Width, [System.Windows.Forms.Screen]::PrimaryScreen.Bounds.Height)
$graphics = [System.Drawing.Graphics]::FromImage($bitmap)
$graphics.CopyFromScreen(0, 0, 0, 0, $bitmap.Size)
$bitmap.Save($filePath, [System.Drawing.Imaging.ImageFormat]::Png)
$graphics.Dispose()
$bitmap.Dispose()
}
$desktopPath = [Environment]::GetFolderPath("Desktop")
$wordDocPath = Join-Path $desktopPath "Screenshots_of_Links.docx"
if (-not (Test-ChromeInstalled)) {
Write-Host "Error: Google Chrome is not installed. Please install it and try again."
exit
}
try {
$wordApp = New-Object -ComObject Word.Application
$wordApp.Visible = $true
$doc = if (Test-Path $wordDocPath) {
$wordApp.Documents.Open($wordDocPath)
} else {
$wordApp.Documents.Add()
}
} catch {
Write-Host "Error: Could not open Microsoft Word. Ensure it is installed."
exit
}
$urls = Read-Host "Enter multiple URLs (separated by commas)"
$urlsArray = $urls -split "," | ForEach-Object { $.Trim() }
foreach ($url in $urlsArray) {
if (-not ($url -match "^https?://")) {
Write-Host "Invalid URL: $url. Please include 'http://' or 'https://'."
continue
}
try {
Write-Host "Opening $url in Chrome..."
$chromeProcess = Start-Process "chrome.exe" -ArgumentList "--start-fullscreen $url" -PassThru
Start-Sleep -Seconds 5
$screenshotPath = Join-Path $desktopPath ("Screenshot" + [DateTime]::Now.ToString("yyyyMMdd_HHmmss") + ".png")
Write-Host "Capturing screenshot..."
Take-Screenshot -filePath $screenshotPath
Write-Host "Adding screenshot to Word document..."
$selection = $wordApp.Selection
$selection.TypeText("$url")
$selection.TypeParagraph()
$selection.InlineShapes.AddPicture($screenshotPath) | Out-Null
$selection.TypeParagraph()
Stop-Process -Id $chromeProcess.Id -Force -ErrorAction SilentlyContinue
} catch {
Write-Host "Error processing URL: $_"
}
}
$doc.SaveAs([ref]$wordDocPath)
$doc.Close()
$wordApp.Quit()
Write-Host "Word document saved at $wordDocPath"
這個是需要後面手動再輸入URL,但我想做到在裡面就已經可以預先打好URL再自己瀏覽,這能做到嗎?
程式碼是問AI來的嗎?
改這兩行原始碼就可以了
$urls = Read-Host "Enter multiple URLs (separated by commas)"
$urlsArray = $urls -split "," | ForEach-Object { $.Trim() }
你的原始碼已經針對URL陣列做迴圈處理了,有幾個網址就會截圖幾張圖片
用兩個網址資料測試