diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000..64ecd25 --- /dev/null +++ b/.editorconfig @@ -0,0 +1,26 @@ +# EditorConfig - https://editorconfig.org +# Menyeragamkan gaya penulisan antar editor tanpa memaksa alat tertentu. +root = true + +[*] +charset = utf-8 +insert_final_newline = true +trim_trailing_whitespace = true +indent_style = space +indent_size = 4 + +[*.{cmd,bat}] +# File batch harus CRLF agar aman dijalankan cmd.exe (terutama label/goto). +end_of_line = crlf + +[*.ps1] +# PowerShell 2.0 (Windows 7) salah membaca karakter non-ASCII tanpa BOM, +# jadi script toolkit disimpan sebagai UTF-8 ber-BOM. +charset = utf-8-bom + +[*.{yml,yaml,json,psd1}] +indent_size = 2 + +[*.md] +# Markdown memakai dua spasi di akhir baris sebagai pemisah baris. +trim_trailing_whitespace = false diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index a0eb27f..a9b36b8 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -23,3 +23,21 @@ jobs: - name: Run script checks shell: pwsh run: ./tools/dev/Test-Scripts.ps1 + + test: + name: Pester tests + runs-on: windows-latest + + steps: + - name: Checkout + uses: actions/checkout@v4 + + - name: Install Pester + shell: pwsh + run: | + Set-PSRepository -Name PSGallery -InstallationPolicy Trusted -ErrorAction SilentlyContinue + Install-Module Pester -Force -Scope CurrentUser -SkipPublisherCheck + + - name: Run tests + shell: pwsh + run: ./tests/Run-Tests.ps1 diff --git a/.gitignore b/.gitignore index 5292519..e930479 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1,2 @@ -logs/ \ No newline at end of file +logs/ +tests/_tmp_negative/ diff --git a/CHANGELOG.md b/CHANGELOG.md index 2f6e969..f98bba4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,19 @@ dan proyek ini memakai [Semantic Versioning](https://semver.org/lang/id/). ## [Unreleased] +### Added + +- **Menu interaktif** diperluas: + - **LOG** - melihat daftar log/backup terbaru, membuka foldernya, dan menampilkan isi log. + - **BANTUAN** - panduan singkat dan tombol untuk membuka README. + - **BAHASA** - berganti bahasa Indonesia/English; pilihan disimpan. + - **Unshare** - berhenti membagikan printer langsung dari menu HOST. + - Status printer yang sedang dibagikan ditampilkan di header menu. +- **Test Pester** (`tests/`) untuk logika menu, kelengkapan struktur repositori, + dan pemeriksa kualitas, plus runner `tests/Run-Tests.ps1`. +- **`.editorconfig`** untuk menyeragamkan encoding, indentasi, dan akhir baris antar editor. +- CI kini juga menjalankan test Pester (`test` job) selain lint. + ## [1.0.0] - 2026-11-17 Rilis publik pertama. diff --git a/Menu.ps1 b/Menu.ps1 index 4bd59cc..d3716c3 100644 --- a/Menu.ps1 +++ b/Menu.ps1 @@ -1,12 +1,12 @@ #Requires -Version 2.0 <# .SYNOPSIS - Menu interaktif Printer Sharing Toolkit. + Menu interaktif Printer Sharing Toolkit (dwibahasa ID/EN). .DESCRIPTION Pembungkus ramah pengguna untuk seluruh script toolkit: - HOST (bagikan printer), KLIEN (sambung), DIAGNOSA, PERBAIKAN, dan ROLLBACK. - Pengguna cukup memilih nomor - tidak perlu mengetik parameter panjang. + HOST (bagikan), KLIEN (sambung), DIAGNOSA, PERBAIKAN, ROLLBACK, + LOG, BANTUAN, dan ganti BAHASA. Jalankan lewat Menu.cmd (otomatis meminta hak Administrator). @@ -15,16 +15,19 @@ .NOTES Script ini HANYA memanggil script asli di folder host\, client\, dan tools\. Script asli tidak diubah, jadi tetap bisa dipakai manual seperti sebelumnya. + + Saat di-dot-source (untuk pengujian), menu tidak dijalankan; hanya + fungsi dan variabelnya yang dimuat. #> $ErrorActionPreference = 'Continue' # --------------------------------------------------------------------------- -# Lokasi script (PowerShell 2.0 tidak punya $PSScriptRoot) +# Lokasi script (PowerShell 2.0 tidak punya variabel otomatis PSScriptRoot) # --------------------------------------------------------------------------- $Script:Root = Split-Path -Parent $MyInvocation.MyCommand.Definition -# Versi aplikasi (dibaca dari file VERSION; tetap kompatibel PS 2.0) +# Versi aplikasi (dibaca dari file VERSION) $Script:Version = '1.0.0' $Script:VersionFile = Join-Path $Script:Root 'VERSION' if (Test-Path -LiteralPath $Script:VersionFile) { @@ -35,6 +38,291 @@ if (Test-Path -LiteralPath $Script:VersionFile) { catch { } } +# --------------------------------------------------------------------------- +# Bahasa (ID / EN) +# --------------------------------------------------------------------------- +$Script:Lang = 'id' +$Script:LangFile = Join-Path $env:ProgramData 'PrinterShare\lang.txt' + +$Script:Strings = @{ + id = @{ + title = 'PRINTER SHARING TOOLKIT' + osLine = 'OS ini' + shareStatus = 'Printer dibagikan' + statusNone = 'belum ada' + itemHost = 'HOST - Bagikan printer dari PC ini' + itemClient = 'KLIEN - Sambungkan ke printer yang dibagikan' + itemDiag = 'DIAGNOSA - Cek masalah sharing (read-only)' + itemFix = 'PERBAIKAN - Fix kompatibilitas Windows 7' + itemRollback = 'ROLLBACK - Kembalikan pengaturan host' + itemLogs = 'LOG - Lihat log & backup terakhir' + itemHelp = 'BANTUAN - Panduan singkat & buka README' + itemLang = 'BAHASA - Ganti bahasa (ID/EN)' + itemExit = 'KELUAR' + choose = 'Pilih' + unknownChoice = 'Pilihan tidak dikenal.' + cancelled = 'Dibatalkan.' + pressEnter = 'Tekan Enter untuk kembali ke menu' + invalidYesNo = 'Jawab y atau n.' + back = 'Kembali' + + adminWarn1 = 'PERHATIAN: menu ini belum berjalan sebagai Administrator.' + adminWarn2 = 'Sebaiknya tutup lalu jalankan lewat Menu.cmd.' + adminWarn3 = 'Tekan Enter untuk lanjut apa adanya' + + osWin7 = 'Windows 7' + osWin8 = 'Windows 8/8.1 (belum resmi didukung)' + osWin10 = 'Windows 10' + osWin11 = 'Windows 11' + + labelPickPrinter = 'Pilih nomor, atau ketik nama printer persis (Enter = batal)' + noPrinters = 'Tidak ada printer terdeteksi di PC ini.' + detectedPrinters = 'Printer yang terdeteksi:' + outOfRange = 'Nomor di luar rentang.' + required = '{0} wajib diisi.' + qHost = 'Nama/IP komputer host (tanpa \\ )' + qShare = 'Nama share printer (lihat output script host)' + + hostHeader = 'HOST - Bagikan printer dari PC ini' + hostScriptNote = 'Script host otomatis dipilih untuk: {0}' + hostItemList = 'Tampilkan daftar printer di PC ini' + hostItemShare = 'Bagikan printer (langkah demi langkah)' + hostItemDry = 'Simulasi dulu (dry-run, tidak mengubah apa pun)' + hostItemUnshare = 'Berhenti membagikan printer (unshare)' + dryRunNote = 'Mode SIMULASI (dry-run): tidak ada perubahan yang diterapkan.' + qShareName = 'Nama share (opsional, Enter = otomatis dari nama printer)' + qSmb2 = 'Aktifkan SMB2 bila dimatikan?' + qLegacy = 'Ada klien Windows 7 di jaringan? (menurunkan keamanan)' + qGuest = 'Izinkan akses tanpa password (guest)?' + qNetbios = 'Aktifkan NetBIOS (memudahkan Win7 menemukan PC)?' + qEveryone = 'Izinkan semua orang mencetak (Everyone: Print)?' + qApply = 'Terapkan sekarang?' + hostNotShared = 'Tidak ada printer yang sedang dibagikan.' + sharedPrinters = 'Printer yang sedang dibagikan:' + qUnshare = 'Berhenti membagikan printer ini?' + unshareDone = 'Berhasil berhenti membagikan printer.' + unshareFail = 'Gagal berhenti membagikan printer (kode {0}).' + + clientHeader = 'KLIEN - Sambungkan ke printer yang dibagikan' + clientOsNote = 'OS klien ini: {0}' + clientItemList = 'Lihat printer yang dibagikan di host' + clientItemConnect = 'Sambungkan ke printer host' + clientItemRepair = 'Sambungkan ulang / perbaiki (Repair)' + clientItemBatch = 'Sambung cepat via batch (khusus Win7 64-bit)' + clientItemLocal = 'Mode LocalPort + driver 32-bit (khusus Win7 32-bit)' + onlyWin7 = 'Pilihan hanya untuk Windows 7.' + qDriverInf = 'Path file driver 32-bit (.inf)' + driverRequired = 'DriverInf wajib untuk mode LocalPort.' + qSetDefault = 'Jadikan printer default?' + qTestPage = 'Cetak halaman uji setelah tersambung?' + qSaveCred = 'Simpan kredensial (bila host minta login)?' + qCompatFix = 'Terapkan fix kompatibilitas RPC (error 0x0000011b)?' + + diagHeader = 'DIAGNOSA - Cek masalah sharing (read-only)' + diagNote1 = 'Kosongkan nama host bila ingin memeriksa PC ini sendiri.' + diagNote2 = 'Jalankan di HOST dan di KLIEN untuk membandingkan hasil.' + qServer = 'Nama/IP host (Enter = PC ini)' + qShareOpt = 'Nama share printer (opsional)' + qPrinterOpt = 'Nama printer lokal untuk cek driver (opsional)' + + fixHeader = 'PERBAIKAN - Kompatibilitas Windows 7' + fixNote1 = 'Menyetel ulang RpcAuthnLevelPrivacyEnabled dan kebijakan Point and Print' + fixNote2 = 'pada PC ini (biasanya di HOST) untuk mengatasi error 0x0000011b' + fixNote3 = 'dan 0x00000bc4 dari klien lama.' + qFixLegacy = 'Aktifkan mode kompatibel Windows 7 (menurunkan keamanan)?' + qFixGuest = 'Sekaligus izinkan akses tanpa password (guest)?' + noChanges = 'Tidak ada perubahan.' + + rbHeader = 'ROLLBACK - Kembalikan pengaturan host' + rbScript = 'Script: {0}' + rbNote = 'Kosongkan path file untuk memakai cadangan terbaru.' + qRbFile = 'Path file backup/journal (opsional)' + qRbConfirm = 'Lanjutkan rollback?' + + logHeader = 'LOG & BACKUP' + logDir = 'Folder: {0}' + logEmpty = 'Belum ada file log/backup.' + logLatest = 'File terbaru:' + qOpenFolder = 'Buka folder di Explorer?' + qShowLog = 'Tampilkan isi log terbaru?' + logNone = 'Tidak ada file log.' + linesSuffix = 'baris' + + helpHeader = 'PANDUAN SINGKAT' + helpBody = @' + Urutan pemakaian yang disarankan: + + 1. Di PC yang tercolok printer (HOST), pilih menu 1 lalu bagikan printer. + Catat nama PC host dan nama share yang ditampilkan. + + 2. Di PC lain (KLIEN), pilih menu 2 lalu sambungkan ke host tersebut. + + 3. Bila bermasalah, jalankan menu 3 (DIAGNOSA). + + 4. Ingin membatalkan? Menu 4 (PERBAIKAN) atau menu 5 (ROLLBACK). + + Panduan lengkap ada di README.md. +'@ + qOpenReadme = 'Buka README di aplikasi default?' + + langHeader = 'BAHASA' + langCurrent = 'Bahasa saat ini: {0}' + langName = 'Indonesia' + langSet = 'Bahasa diatur ke Indonesia.' + } + en = @{ + title = 'PRINTER SHARING TOOLKIT' + osLine = 'This OS' + shareStatus = 'Shared printers' + statusNone = 'none yet' + itemHost = 'HOST - Share a printer from this PC' + itemClient = 'CLIENT - Connect to a shared printer' + itemDiag = 'DIAGNOSE - Check sharing problems (read-only)' + itemFix = 'REPAIR - Fix Windows 7 compatibility' + itemRollback = 'ROLLBACK - Restore host settings' + itemLogs = 'LOGS - View recent logs & backups' + itemHelp = 'HELP - Quick guide & open README' + itemLang = 'LANGUAGE - Switch language (ID/EN)' + itemExit = 'EXIT' + choose = 'Choose' + unknownChoice = 'Unknown choice.' + cancelled = 'Cancelled.' + pressEnter = 'Press Enter to return to the menu' + invalidYesNo = 'Answer y or n.' + back = 'Back' + + adminWarn1 = 'WARNING: this menu is not running as Administrator.' + adminWarn2 = 'It is better to close it and run via Menu.cmd.' + adminWarn3 = 'Press Enter to continue anyway' + + osWin7 = 'Windows 7' + osWin8 = 'Windows 8/8.1 (not officially supported)' + osWin10 = 'Windows 10' + osWin11 = 'Windows 11' + + labelPickPrinter = 'Pick a number, or type the exact printer name (Enter = cancel)' + noPrinters = 'No printer detected on this PC.' + detectedPrinters = 'Detected printers:' + outOfRange = 'Number out of range.' + required = '{0} is required.' + qHost = 'Host name/IP (without \\ )' + qShare = 'Printer share name (see host script output)' + + hostHeader = 'HOST - Share a printer from this PC' + hostScriptNote = 'Host script auto-selected for: {0}' + hostItemList = 'List printers on this PC' + hostItemShare = 'Share a printer (step by step)' + hostItemDry = 'Dry-run first (changes nothing)' + hostItemUnshare = 'Stop sharing a printer (unshare)' + dryRunNote = 'SIMULATION mode (dry-run): nothing is changed.' + qShareName = 'Share name (optional, Enter = auto from printer name)' + qSmb2 = 'Enable SMB2 if it is disabled?' + qLegacy = 'Any Windows 7 clients on the network? (lowers security)' + qGuest = 'Allow password-less access (guest)?' + qNetbios = 'Enable NetBIOS (helps Win7 find this PC)?' + qEveryone = 'Allow everyone to print (Everyone: Print)?' + qApply = 'Apply now?' + hostNotShared = 'No printer is currently shared.' + sharedPrinters = 'Currently shared printers:' + qUnshare = 'Stop sharing this printer?' + unshareDone = 'Stopped sharing the printer.' + unshareFail = 'Failed to stop sharing (code {0}).' + + clientHeader = 'CLIENT - Connect to a shared printer' + clientOsNote = 'This client OS: {0}' + clientItemList = 'List printers shared on the host' + clientItemConnect = 'Connect to a host printer' + clientItemRepair = 'Reconnect / repair (Repair)' + clientItemBatch = 'Quick connect via batch (Win7 64-bit only)' + clientItemLocal = 'LocalPort mode + 32-bit driver (Win7 32-bit only)' + onlyWin7 = 'This option is for Windows 7 only.' + qDriverInf = 'Path to 32-bit driver file (.inf)' + driverRequired = 'DriverInf is required for LocalPort mode.' + qSetDefault = 'Set as the default printer?' + qTestPage = 'Print a test page after connecting?' + qSaveCred = 'Save credentials (if the host asks for login)?' + qCompatFix = 'Apply RPC compatibility fix (error 0x0000011b)?' + + diagHeader = 'DIAGNOSE - Check sharing problems (read-only)' + diagNote1 = 'Leave the host empty to check this PC itself.' + diagNote2 = 'Run on both HOST and CLIENT to compare results.' + qServer = 'Host name/IP (Enter = this PC)' + qShareOpt = 'Printer share name (optional)' + qPrinterOpt = 'Local printer name to check the driver (optional)' + + fixHeader = 'REPAIR - Windows 7 compatibility' + fixNote1 = 'Resets RpcAuthnLevelPrivacyEnabled and the Point and Print policy' + fixNote2 = 'on this PC (usually the HOST) to fix errors 0x0000011b' + fixNote3 = 'and 0x00000bc4 from legacy clients.' + qFixLegacy = 'Enable Windows 7 compatible mode (lowers security)?' + qFixGuest = 'Also allow password-less access (guest)?' + noChanges = 'No changes.' + + rbHeader = 'ROLLBACK - Restore host settings' + rbScript = 'Script: {0}' + rbNote = 'Leave the file path empty to use the latest backup.' + qRbFile = 'Backup/journal file path (optional)' + qRbConfirm = 'Proceed with the rollback?' + + logHeader = 'LOGS & BACKUPS' + logDir = 'Folder: {0}' + logEmpty = 'No log/backup files yet.' + logLatest = 'Latest files:' + qOpenFolder = 'Open the folder in Explorer?' + qShowLog = 'Show the latest log content?' + logNone = 'No log file found.' + linesSuffix = 'lines' + + helpHeader = 'QUICK GUIDE' + helpBody = @' + Recommended order: + + 1. On the PC with the printer attached (HOST), choose 1 and share it. + Note the host PC name and the share name it prints. + + 2. On the other PC (CLIENT), choose 2 and connect to that host. + + 3. If something fails, run 3 (DIAGNOSE). + + 4. To undo, use 4 (REPAIR) or 5 (ROLLBACK). + + The full guide is in README.md. +'@ + qOpenReadme = 'Open README in the default app?' + + langHeader = 'LANGUAGE' + langCurrent = 'Current language: {0}' + langName = 'English' + langSet = 'Language set to English.' + } +} + +function T { + param([string]$Key) + $table = $Script:Strings[$Script:Lang] + if ($table -and $table.ContainsKey($Key)) { return $table[$Key] } + $fallback = $Script:Strings['id'] + if ($fallback -and $fallback.ContainsKey($Key)) { return $fallback[$Key] } + return $Key +} + +function Save-Lang { + try { + $dir = Split-Path -Parent $Script:LangFile + if (-not (Test-Path -LiteralPath $dir)) { New-Item -ItemType Directory -Path $dir -Force | Out-Null } + Set-Content -LiteralPath $Script:LangFile -Value $Script:Lang -Encoding ASCII + } + catch { } +} + +if (Test-Path -LiteralPath $Script:LangFile) { + try { + $savedLang = (Get-Content -LiteralPath $Script:LangFile | Select-Object -First 1) + if ($savedLang -and ([string]$savedLang).Trim() -eq 'en') { $Script:Lang = 'en' } + } + catch { } +} + # --------------------------------------------------------------------------- # Deteksi OS & arsitektur # --------------------------------------------------------------------------- @@ -69,10 +357,10 @@ if ($env:PROCESSOR_ARCHITECTURE -eq 'x86' -and -not $env:PROCESSOR_ARCHITEW6432) function Get-OsLabel { switch ($Script:OsFamily) { - 'Win7' { return 'Windows 7' } - 'Win8' { return 'Windows 8/8.1 (belum resmi didukung)' } - 'Win11' { return 'Windows 11' } - default { return 'Windows 10' } + 'Win7' { return (T 'osWin7') } + 'Win8' { return (T 'osWin8') } + 'Win11' { return (T 'osWin11') } + default { return (T 'osWin10') } } } @@ -98,15 +386,15 @@ function Get-ClientScript { function Write-Header { param([string]$Text) Write-Host '' - Write-Host ('============================================================') -ForegroundColor Cyan + Write-Host '============================================================' -ForegroundColor Cyan Write-Host (' ' + $Text) -ForegroundColor Cyan - Write-Host ('============================================================') -ForegroundColor Cyan + Write-Host '============================================================' -ForegroundColor Cyan Write-Host '' } function Pause-Menu { Write-Host '' - [void](Read-Host ' Tekan Enter untuk kembali ke menu') + [void](Read-Host (' ' + (T 'pressEnter'))) } function Read-YesNo { @@ -120,7 +408,7 @@ function Read-YesNo { if ($a -eq '') { return $Default } if ($a -match '^(y|ya|yes)$') { return $true } if ($a -match '^(n|no|tidak)$') { return $false } - Write-Host ' Jawab y atau n.' -ForegroundColor Yellow + Write-Host (' ' + (T 'invalidYesNo')) -ForegroundColor Yellow } } @@ -160,7 +448,7 @@ function Invoke-Tool { if (-not (Test-Path -LiteralPath $Path)) { Write-Host '' - Write-Host (' [ERROR] Script tidak ditemukan: ' + $Path) -ForegroundColor Red + Write-Host (' [ERROR] ' + $Path) -ForegroundColor Red Pause-Menu return } @@ -189,7 +477,7 @@ function Invoke-Tool { } # --------------------------------------------------------------------------- -# Pemilih printer lokal +# Printer: daftar lokal, printer yang dibagikan, status # --------------------------------------------------------------------------- function Get-LocalPrinterNames { $names = @() @@ -203,26 +491,55 @@ function Get-LocalPrinterNames { return $names } +function Get-SharedPrinters { + $out = New-Object System.Collections.ArrayList + if (Get-Command Get-Printer -ErrorAction SilentlyContinue) { + foreach ($p in @(Get-Printer -ErrorAction SilentlyContinue)) { + if ($p.Shared) { + [void]$out.Add((New-Object PSObject -Property @{ Name = [string]$p.Name; ShareName = [string]$p.ShareName })) + } + } + } + else { + foreach ($p in @(Get-WmiObject -Class Win32_Printer -ErrorAction SilentlyContinue)) { + if ($p.Shared) { + [void]$out.Add((New-Object PSObject -Property @{ Name = [string]$p.Name; ShareName = [string]$p.ShareName })) + } + } + } + return @($out) +} + +function Get-ShareStatusText { + $shared = @(Get-SharedPrinters) + $names = @() + foreach ($p in $shared) { + if ($p.ShareName) { $names += $p.ShareName } else { $names += $p.Name } + } + if ($names.Count -eq 0) { return (T 'statusNone') } + return ($names -join ', ') +} + function Select-PrinterName { $names = @(Get-LocalPrinterNames) Write-Host '' if ($names.Count -eq 0) { - Write-Host ' Tidak ada printer terdeteksi di PC ini.' -ForegroundColor Yellow + Write-Host (' ' + (T 'noPrinters')) -ForegroundColor Yellow return $null } - Write-Host ' Printer yang terdeteksi:' -ForegroundColor Cyan + Write-Host (' ' + (T 'detectedPrinters')) -ForegroundColor Cyan for ($i = 0; $i -lt $names.Count; $i++) { Write-Host (' ' + ($i + 1) + '. ' + $names[$i]) } Write-Host '' - $a = Read-Host ' Pilih nomor, atau ketik nama printer persis (Enter = batal)' + $a = Read-Host (' ' + (T 'labelPickPrinter')) if ($null -eq $a) { return $null } $a = $a.Trim() if ($a -eq '') { return $null } if ($a -match '^[0-9]+$') { $idx = [int]$a - 1 if ($idx -ge 0 -and $idx -lt $names.Count) { return $names[$idx] } - Write-Host ' Nomor di luar rentang.' -ForegroundColor Yellow + Write-Host (' ' + (T 'outOfRange')) -ForegroundColor Yellow return $null } return $a @@ -233,18 +550,24 @@ function Select-PrinterName { # --------------------------------------------------------------------------- function Show-MainMenu { Clear-Host + if ($null -eq $Script:ShareStatus) { $Script:ShareStatus = Get-ShareStatusText } + Write-Host '' Write-Host '============================================================' -ForegroundColor Cyan - Write-Host (' PRINTER SHARING TOOLKIT v' + $Script:Version) -ForegroundColor Cyan + Write-Host (' ' + (T 'title') + ' v' + $Script:Version) -ForegroundColor Cyan Write-Host '============================================================' -ForegroundColor Cyan - Write-Host (' OS ini : ' + (Get-OsLabel) + ' ' + $Script:ArchBits) -ForegroundColor Gray + Write-Host (' ' + (T 'osLine') + ' : ' + (Get-OsLabel) + ' ' + $Script:ArchBits) -ForegroundColor Gray + Write-Host (' ' + (T 'shareStatus') + ' : ' + $Script:ShareStatus) -ForegroundColor Gray Write-Host '' - Write-Host ' 1. HOST - Bagikan printer dari PC ini' - Write-Host ' 2. KLIEN - Sambungkan ke printer yang dibagikan' - Write-Host ' 3. DIAGNOSA - Cek masalah sharing (read-only)' - Write-Host ' 4. PERBAIKAN - Fix kompatibilitas Windows 7' - Write-Host ' 5. ROLLBACK - Kembalikan pengaturan host' - Write-Host ' 0. Keluar' + Write-Host (' 1. ' + (T 'itemHost')) + Write-Host (' 2. ' + (T 'itemClient')) + Write-Host (' 3. ' + (T 'itemDiag')) + Write-Host (' 4. ' + (T 'itemFix')) + Write-Host (' 5. ' + (T 'itemRollback')) + Write-Host (' 6. ' + (T 'itemLogs')) + Write-Host (' 7. ' + (T 'itemHelp')) + Write-Host (' 8. ' + (T 'itemLang')) + Write-Host (' 0. ' + (T 'itemExit')) Write-Host '' } @@ -255,64 +578,133 @@ function Start-HostSharing { param([bool]$DryRun = $false) Clear-Host - Write-Header 'HOST - Bagikan printer dari PC ini' + Write-Header (T 'hostHeader') if ($DryRun) { - Write-Host ' Mode SIMULASI (dry-run): tidak ada perubahan yang diterapkan.' -ForegroundColor Yellow + Write-Host (' ' + (T 'dryRunNote')) -ForegroundColor Yellow Write-Host '' } $printer = Select-PrinterName - if (-not $printer) { Write-Host ' Dibatalkan.' -ForegroundColor Yellow; Pause-Menu; return } + if (-not $printer) { Write-Host (' ' + (T 'cancelled')) -ForegroundColor Yellow; Pause-Menu; return } - $share = Read-Text ' Nama share (opsional, Enter = otomatis dari nama printer)' + $share = Read-Text (' ' + (T 'qShareName')) $toolArgs = @{ PrinterName = $printer } if ($share -ne '') { $toolArgs['ShareName'] = $share } if ($Script:OsFamily -eq 'Win7') { - if (Read-YesNo ' Aktifkan SMB2 bila dimatikan?' $false) { $toolArgs['EnableSMB2'] = $true } + if (Read-YesNo (' ' + (T 'qSmb2')) $false) { $toolArgs['EnableSMB2'] = $true } } else { - $legacy = Read-YesNo ' Ada klien Windows 7 di jaringan? (menurunkan keamanan)' $false + $legacy = Read-YesNo (' ' + (T 'qLegacy')) $false if ($legacy) { $toolArgs['AllowLegacyWin7'] = $true - if (Read-YesNo ' Izinkan akses tanpa password (guest)?' $false) { $toolArgs['AllowGuest'] = $true } - if (Read-YesNo ' Aktifkan NetBIOS (memudahkan Win7 menemukan PC)?' $false) { $toolArgs['EnableNetBios'] = $true } + if (Read-YesNo (' ' + (T 'qGuest')) $false) { $toolArgs['AllowGuest'] = $true } + if (Read-YesNo (' ' + (T 'qNetbios')) $false) { $toolArgs['EnableNetBios'] = $true } } - if (Read-YesNo ' Izinkan semua orang mencetak (Everyone: Print)?' $false) { $toolArgs['GrantEveryonePrint'] = $true } + if (Read-YesNo (' ' + (T 'qEveryone')) $false) { $toolArgs['GrantEveryonePrint'] = $true } } if ($DryRun) { $toolArgs['WhatIf'] = $true } - elseif (-not (Read-YesNo ' Terapkan sekarang?' $true)) { - Write-Host ' Dibatalkan.' -ForegroundColor Yellow + elseif (-not (Read-YesNo (' ' + (T 'qApply')) $true)) { + Write-Host (' ' + (T 'cancelled')) -ForegroundColor Yellow Pause-Menu return } Invoke-Tool (Get-HostScript) $toolArgs + $Script:ShareStatus = $null +} + +function Stop-HostSharing { + Clear-Host + Write-Header (T 'hostItemUnshare') + + $shared = @(Get-SharedPrinters) + if ($shared.Count -eq 0) { + Write-Host (' ' + (T 'hostNotShared')) -ForegroundColor Yellow + Pause-Menu + return + } + + Write-Host (' ' + (T 'sharedPrinters')) -ForegroundColor Cyan + for ($i = 0; $i -lt $shared.Count; $i++) { + Write-Host (' ' + ($i + 1) + '. ' + $shared[$i].Name + ' [' + $shared[$i].ShareName + ']') + } + Write-Host '' + + $a = Read-Host (' ' + (T 'labelPickPrinter')) + if ($null -eq $a) { return } + $a = $a.Trim() + if ($a -eq '' -or -not ($a -match '^[0-9]+$')) { Write-Host (' ' + (T 'cancelled')) -ForegroundColor Yellow; Pause-Menu; return } + + $idx = [int]$a - 1 + if ($idx -lt 0 -or $idx -ge $shared.Count) { + Write-Host (' ' + (T 'outOfRange')) -ForegroundColor Yellow + Pause-Menu + return + } + + $target = $shared[$idx] + if (-not (Read-YesNo (' ' + (T 'qUnshare')) $false)) { + Write-Host (' ' + (T 'cancelled')) -ForegroundColor Yellow + Pause-Menu + return + } + + $ok = $false + $code = '' + if (Get-Command Set-Printer -ErrorAction SilentlyContinue) { + try { + Set-Printer -Name $target.Name -Shared $false -ErrorAction Stop + $ok = $true + } + catch { + $code = $_.Exception.Message + } + } + else { + if ($target.ShareName) { + & net share $target.ShareName /delete | Out-Null + $code = [string]$LASTEXITCODE + if ($LASTEXITCODE -eq 0) { $ok = $true } + } + else { + $code = 'no-share-name' + } + } + + Write-Host '' + if ($ok) { Write-Host (' ' + (T 'unshareDone')) -ForegroundColor Green } + else { Write-Host (' ' + ((T 'unshareFail') -f $code)) -ForegroundColor Red } + + $Script:ShareStatus = $null + Pause-Menu } function Show-HostMenu { while ($true) { Clear-Host - Write-Header 'HOST - Bagikan printer' - Write-Host (' Script host otomatis dipilih untuk: ' + (Get-OsLabel)) + Write-Header (T 'hostHeader') + Write-Host (' ' + ((T 'hostScriptNote') -f (Get-OsLabel))) Write-Host '' - Write-Host ' 1. Tampilkan daftar printer di PC ini' - Write-Host ' 2. Bagikan printer (langkah demi langkah)' - Write-Host ' 3. Simulasi dulu (dry-run, tidak mengubah apa pun)' - Write-Host ' 0. Kembali' + Write-Host (' 1. ' + (T 'hostItemList')) + Write-Host (' 2. ' + (T 'hostItemShare')) + Write-Host (' 3. ' + (T 'hostItemDry')) + Write-Host (' 4. ' + (T 'hostItemUnshare')) + Write-Host (' 0. ' + (T 'back')) Write-Host '' - $c = Read-Host ' Pilih' + $c = Read-Host (' ' + (T 'choose')) if ($null -eq $c) { return } switch ($c.Trim()) { '1' { Invoke-Tool (Get-HostScript) @{ ListPrinters = $true } } '2' { Start-HostSharing $false } '3' { Start-HostSharing $true } + '4' { Stop-HostSharing } '0' { return } - default { Write-Host ' Pilihan tidak dikenal.' -ForegroundColor Yellow } + default { Write-Host (' ' + (T 'unknownChoice')) -ForegroundColor Yellow } } } } @@ -322,20 +714,18 @@ function Show-HostMenu { # --------------------------------------------------------------------------- function Start-Win7Batch { Clear-Host - Write-Header 'KLIEN Win7 - Sambung cepat (batch)' - Write-Host ' Cara ini untuk Windows 7 64-bit. Untuk 32-bit pakai mode LocalPort.' -ForegroundColor Gray - Write-Host '' + Write-Header (T 'clientItemBatch') - $server = Read-Text ' Nama/IP komputer host (tanpa \\ )' - if ($server -eq '') { Write-Host ' Host wajib diisi.' -ForegroundColor Yellow; Pause-Menu; return } + $server = Read-Text (' ' + (T 'qHost')) + if ($server -eq '') { Write-Host (' ' + ((T 'required') -f (T 'qHost'))) -ForegroundColor Yellow; Pause-Menu; return } - $share = Read-Text ' Nama share printer (lihat output script host)' - if ($share -eq '') { Write-Host ' Nama share wajib diisi.' -ForegroundColor Yellow; Pause-Menu; return } + $share = Read-Text (' ' + (T 'qShare')) + if ($share -eq '') { Write-Host (' ' + ((T 'required') -f (T 'qShare'))) -ForegroundColor Yellow; Pause-Menu; return } $testStr = '-' - if (Read-YesNo ' Cetak halaman uji?' $false) { $testStr = 'test' } + if (Read-YesNo (' ' + (T 'qTestPage')) $false) { $testStr = 'test' } $repairStr = '-' - if (Read-YesNo ' Hapus koneksi lama dulu (repair)?' $false) { $repairStr = 'repair' } + if (Read-YesNo (' ' + (T 'clientItemRepair')) $false) { $repairStr = 'repair' } $cmdPath = Join-Path $Script:Root 'client\Win7\02-Connect-Win7.cmd' Invoke-Tool $cmdPath @($server, $share, '-', '-', $testStr, $repairStr) @@ -345,35 +735,35 @@ function Start-ClientConnect { param([string]$Action, [switch]$LocalPort) Clear-Host - Write-Header 'KLIEN - Sambungkan ke printer host' + Write-Header (T 'clientItemConnect') $scriptPath = Get-ClientScript - $server = Read-Text ' Nama/IP komputer host (tanpa \\ )' - if ($server -eq '') { Write-Host ' Host wajib diisi.' -ForegroundColor Yellow; Pause-Menu; return } + $server = Read-Text (' ' + (T 'qHost')) + if ($server -eq '') { Write-Host (' ' + ((T 'required') -f (T 'qHost'))) -ForegroundColor Yellow; Pause-Menu; return } if ($Action -eq 'list') { Invoke-Tool $scriptPath @{ Server = $server; ListRemote = $true } return } - $share = Read-Text ' Nama share printer (lihat output script host)' - if ($share -eq '') { Write-Host ' Nama share wajib diisi.' -ForegroundColor Yellow; Pause-Menu; return } + $share = Read-Text (' ' + (T 'qShare')) + if ($share -eq '') { Write-Host (' ' + ((T 'required') -f (T 'qShare'))) -ForegroundColor Yellow; Pause-Menu; return } $toolArgs = @{ Server = $server; ShareName = $share } if ($Action -eq 'repair') { $toolArgs['Repair'] = $true } if ($LocalPort) { - $inf = Read-Text ' Path file driver 32-bit (.inf)' - if ($inf -eq '') { Write-Host ' DriverInf wajib untuk mode LocalPort.' -ForegroundColor Yellow; Pause-Menu; return } + $inf = Read-Text (' ' + (T 'qDriverInf')) + if ($inf -eq '') { Write-Host (' ' + (T 'driverRequired')) -ForegroundColor Yellow; Pause-Menu; return } $toolArgs['Mode'] = 'LocalPort' $toolArgs['DriverInf'] = $inf } else { - if (Read-YesNo ' Jadikan printer default?' $true) { $toolArgs['SetDefault'] = $true } - if (Read-YesNo ' Cetak halaman uji setelah tersambung?' $false) { $toolArgs['TestPage'] = $true } - if (Read-YesNo ' Simpan kredensial (bila host minta login)?' $false) { $toolArgs['SaveCredential'] = $true } + if (Read-YesNo (' ' + (T 'qSetDefault')) $true) { $toolArgs['SetDefault'] = $true } + if (Read-YesNo (' ' + (T 'qTestPage')) $false) { $toolArgs['TestPage'] = $true } + if (Read-YesNo (' ' + (T 'qSaveCred')) $false) { $toolArgs['SaveCredential'] = $true } if ($Script:OsFamily -ne 'Win7') { - if (Read-YesNo ' Terapkan fix kompatibilitas RPC (error 0x0000011b)?' $false) { $toolArgs['ApplyCompatFix'] = $true } + if (Read-YesNo (' ' + (T 'qCompatFix')) $false) { $toolArgs['ApplyCompatFix'] = $true } } } @@ -383,19 +773,19 @@ function Start-ClientConnect { function Show-ClientMenu { while ($true) { Clear-Host - Write-Header 'KLIEN - Sambungkan ke printer yang dibagikan' - Write-Host (' OS klien ini: ' + (Get-OsLabel) + ' ' + $Script:ArchBits) + Write-Header (T 'clientHeader') + Write-Host (' ' + ((T 'clientOsNote') -f ((Get-OsLabel) + ' ' + $Script:ArchBits))) Write-Host '' - Write-Host ' 1. Lihat printer yang dibagikan di host' - Write-Host ' 2. Sambungkan ke printer host' - Write-Host ' 3. Sambungkan ulang / perbaiki (Repair)' + Write-Host (' 1. ' + (T 'clientItemList')) + Write-Host (' 2. ' + (T 'clientItemConnect')) + Write-Host (' 3. ' + (T 'clientItemRepair')) if ($Script:OsFamily -eq 'Win7') { - Write-Host ' 4. Sambung cepat via batch (khusus Win7 64-bit)' - Write-Host ' 5. Mode LocalPort + driver 32-bit (khusus Win7 32-bit)' + Write-Host (' 4. ' + (T 'clientItemBatch')) + Write-Host (' 5. ' + (T 'clientItemLocal')) } - Write-Host ' 0. Kembali' + Write-Host (' 0. ' + (T 'back')) Write-Host '' - $c = Read-Host ' Pilih' + $c = Read-Host (' ' + (T 'choose')) if ($null -eq $c) { return } switch ($c.Trim()) { '1' { Start-ClientConnect -Action 'list' } @@ -403,14 +793,14 @@ function Show-ClientMenu { '3' { Start-ClientConnect -Action 'repair' } '4' { if ($Script:OsFamily -eq 'Win7') { Start-Win7Batch } - else { Write-Host ' Pilihan hanya untuk Windows 7.' -ForegroundColor Yellow } + else { Write-Host (' ' + (T 'onlyWin7')) -ForegroundColor Yellow } } '5' { if ($Script:OsFamily -eq 'Win7') { Start-ClientConnect -Action 'connect' -LocalPort } - else { Write-Host ' Pilihan hanya untuk Windows 7.' -ForegroundColor Yellow } + else { Write-Host (' ' + (T 'onlyWin7')) -ForegroundColor Yellow } } '0' { return } - default { Write-Host ' Pilihan tidak dikenal.' -ForegroundColor Yellow } + default { Write-Host (' ' + (T 'unknownChoice')) -ForegroundColor Yellow } } } } @@ -420,14 +810,14 @@ function Show-ClientMenu { # --------------------------------------------------------------------------- function Show-DiagMenu { Clear-Host - Write-Header 'DIAGNOSA - Cek masalah sharing (read-only)' - Write-Host ' Kosongkan nama host bila ingin memeriksa PC ini sendiri.' -ForegroundColor Gray - Write-Host ' Jalankan di HOST dan di KLIEN untuk membandingkan hasil.' -ForegroundColor Gray + Write-Header (T 'diagHeader') + Write-Host (' ' + (T 'diagNote1')) -ForegroundColor Gray + Write-Host (' ' + (T 'diagNote2')) -ForegroundColor Gray Write-Host '' - $server = Read-Text ' Nama/IP host (Enter = PC ini)' - $share = Read-Text ' Nama share printer (opsional)' - $printer = Read-Text ' Nama printer lokal untuk cek driver (opsional)' + $server = Read-Text (' ' + (T 'qServer')) + $share = Read-Text (' ' + (T 'qShareOpt')) + $printer = Read-Text (' ' + (T 'qPrinterOpt')) $toolArgs = @{} if ($server -ne '') { $toolArgs['Server'] = $server } @@ -442,20 +832,20 @@ function Show-DiagMenu { # --------------------------------------------------------------------------- function Show-FixMenu { Clear-Host - Write-Header 'PERBAIKAN - Kompatibilitas Windows 7' - Write-Host ' Menyetel ulang RpcAuthnLevelPrivacyEnabled dan kebijakan Point and Print' - Write-Host ' pada PC ini (biasanya di HOST) untuk mengatasi error 0x0000011b' - Write-Host ' dan 0x00000bc4 dari klien lama.' -ForegroundColor Gray + Write-Header (T 'fixHeader') + Write-Host (' ' + (T 'fixNote1')) + Write-Host (' ' + (T 'fixNote2')) + Write-Host (' ' + (T 'fixNote3')) -ForegroundColor Gray Write-Host '' - if (-not (Read-YesNo ' Aktifkan mode kompatibel Windows 7 (menurunkan keamanan)?' $true)) { - Write-Host ' Tidak ada perubahan.' -ForegroundColor Yellow + if (-not (Read-YesNo (' ' + (T 'qFixLegacy')) $true)) { + Write-Host (' ' + (T 'noChanges')) -ForegroundColor Yellow Pause-Menu return } $toolArgs = @{ AllowLegacyWin7 = $true } - if (Read-YesNo ' Sekaligus izinkan akses tanpa password (guest)?' $false) { $toolArgs['AllowGuest'] = $true } + if (Read-YesNo (' ' + (T 'qFixGuest')) $false) { $toolArgs['AllowGuest'] = $true } Invoke-Tool (Join-Path $Script:Root 'tools\04-Fix-LegacyCompat.ps1') $toolArgs } @@ -465,25 +855,26 @@ function Show-FixMenu { # --------------------------------------------------------------------------- function Show-RollbackMenu { Clear-Host - Write-Header 'ROLLBACK - Kembalikan pengaturan host' + Write-Header (T 'rbHeader') if ($Script:OsFamily -eq 'Win7') { $scriptPath = Join-Path $Script:Root 'tools\05-Rollback-Win7.ps1' $fileParam = 'JournalFile' - Write-Host ' Script: 05-Rollback-Win7.ps1' -ForegroundColor Gray + $scriptName = '05-Rollback-Win7.ps1' } else { $scriptPath = Join-Path $Script:Root 'tools\05-Rollback.ps1' $fileParam = 'BackupFile' - Write-Host ' Script: 05-Rollback.ps1' -ForegroundColor Gray + $scriptName = '05-Rollback.ps1' } - Write-Host ' Kosongkan path file untuk memakai cadangan terbaru.' -ForegroundColor Gray + Write-Host (' ' + ((T 'rbScript') -f $scriptName)) -ForegroundColor Gray + Write-Host (' ' + (T 'rbNote')) -ForegroundColor Gray Write-Host '' - $file = Read-Text ' Path file backup/journal (opsional)' + $file = Read-Text (' ' + (T 'qRbFile')) - if (-not (Read-YesNo ' Lanjutkan rollback?' $false)) { - Write-Host ' Dibatalkan.' -ForegroundColor Yellow + if (-not (Read-YesNo (' ' + (T 'qRbConfirm')) $false)) { + Write-Host (' ' + (T 'cancelled')) -ForegroundColor Yellow Pause-Menu return } @@ -492,6 +883,119 @@ function Show-RollbackMenu { if ($file -ne '') { $toolArgs[$fileParam] = $file } Invoke-Tool $scriptPath $toolArgs + $Script:ShareStatus = $null +} + +# --------------------------------------------------------------------------- +# Menu LOG & BACKUP +# --------------------------------------------------------------------------- +function Show-LogsMenu { + $dir = Join-Path $env:ProgramData 'PrinterShare\logs' + while ($true) { + Clear-Host + Write-Header (T 'logHeader') + Write-Host (' ' + ((T 'logDir') -f $dir)) -ForegroundColor Gray + Write-Host '' + + $items = @() + if (Test-Path -LiteralPath $dir) { + $items = @(Get-ChildItem -LiteralPath $dir | + Where-Object { -not $_.PSIsContainer } | + Sort-Object LastWriteTime -Descending | + Select-Object -First 10) + } + + if ($items.Count -eq 0) { + Write-Host (' ' + (T 'logEmpty')) -ForegroundColor Yellow + } + else { + Write-Host (' ' + (T 'logLatest')) -ForegroundColor Cyan + foreach ($it in $items) { + Write-Host (' {0} {1,9} {2}' -f $it.LastWriteTime.ToString('yyyy-MM-dd HH:mm'), $it.Length, $it.Name) + } + } + + Write-Host '' + Write-Host (' 1. ' + (T 'qOpenFolder')) + Write-Host (' 2. ' + (T 'qShowLog')) + Write-Host (' 0. ' + (T 'back')) + Write-Host '' + $c = Read-Host (' ' + (T 'choose')) + if ($null -eq $c) { return } + + switch ($c.Trim()) { + '1' { + if (Test-Path -LiteralPath $dir) { + try { Start-Process -FilePath 'explorer.exe' -ArgumentList $dir } catch { } + } + else { + Write-Host (' ' + (T 'logEmpty')) -ForegroundColor Yellow + Pause-Menu + } + } + '2' { + $latest = $null + if (Test-Path -LiteralPath $dir) { + $latest = Get-ChildItem -LiteralPath $dir -Filter '*.log' | + Sort-Object LastWriteTime -Descending | + Select-Object -First 1 + } + Clear-Host + if ($latest) { + Write-Header $latest.Name + $lines = @(Get-Content -LiteralPath $latest.FullName) + $tail = @($lines | Select-Object -Last 40) + foreach ($l in $tail) { Write-Host $l } + Write-Host '' + Write-Host (' ({0} {1})' -f $lines.Count, (T 'linesSuffix')) -ForegroundColor DarkGray + } + else { + Write-Host (' ' + (T 'logNone')) -ForegroundColor Yellow + } + Pause-Menu + } + '0' { return } + default { Write-Host (' ' + (T 'unknownChoice')) -ForegroundColor Yellow } + } + } +} + +# --------------------------------------------------------------------------- +# Menu BANTUAN +# --------------------------------------------------------------------------- +function Show-HelpMenu { + Clear-Host + Write-Header (T 'helpHeader') + foreach ($line in ((T 'helpBody') -split "\r?\n")) { Write-Host $line } + Write-Host '' + + if (Read-YesNo (' ' + (T 'qOpenReadme')) $false) { + $readme = Join-Path $Script:Root 'README.md' + try { Start-Process -FilePath $readme } + catch { Write-Host (' ' + $readme) -ForegroundColor Gray } + } +} + +# --------------------------------------------------------------------------- +# Menu BAHASA +# --------------------------------------------------------------------------- +function Show-LangMenu { + Clear-Host + Write-Header (T 'langHeader') + Write-Host (' ' + ((T 'langCurrent') -f (T 'langName'))) + Write-Host '' + Write-Host ' 1. Indonesia' + Write-Host ' 2. English' + Write-Host '' + $c = Read-Host (' ' + (T 'choose')) + if ($null -eq $c) { return } + switch ($c.Trim()) { + '1' { $Script:Lang = 'id'; Save-Lang } + '2' { $Script:Lang = 'en'; Save-Lang } + default { return } + } + Write-Host (' ' + (T 'langSet')) -ForegroundColor Green + Start-Sleep -Seconds 1 } # --------------------------------------------------------------------------- @@ -504,16 +1008,18 @@ function Test-IsAdmin { } function Start-Menu { + $Script:ShareStatus = $null + if (-not (Test-IsAdmin)) { Write-Host '' - Write-Host ' PERHATIAN: menu ini belum berjalan sebagai Administrator.' -ForegroundColor Yellow - Write-Host ' Sebaiknya tutup lalu jalankan lewat Menu.cmd.' -ForegroundColor Yellow - [void](Read-Host ' Tekan Enter untuk lanjut apa adanya') + Write-Host (' ' + (T 'adminWarn1')) -ForegroundColor Yellow + Write-Host (' ' + (T 'adminWarn2')) -ForegroundColor Yellow + [void](Read-Host (' ' + (T 'adminWarn3'))) } while ($true) { Show-MainMenu - $c = Read-Host ' Pilih menu' + $c = Read-Host (' ' + (T 'choose')) if ($null -eq $c) { return } switch ($c.Trim()) { '1' { Show-HostMenu } @@ -521,11 +1027,17 @@ function Start-Menu { '3' { Show-DiagMenu } '4' { Show-FixMenu } '5' { Show-RollbackMenu } + '6' { Show-LogsMenu } + '7' { Show-HelpMenu } + '8' { Show-LangMenu } '0' { return } - default { Write-Host ' Pilihan tidak dikenal.' -ForegroundColor Yellow } + default { Write-Host (' ' + (T 'unknownChoice')) -ForegroundColor Yellow } } } } -Start-Menu -exit 0 +# Jalankan menu hanya bila TIDAK di-dot-source (agar bisa diuji). +if ($MyInvocation.InvocationName -ne '.') { + Start-Menu + exit 0 +} diff --git a/README.en.md b/README.en.md index b158e55..ec113b0 100644 --- a/README.en.md +++ b/README.en.md @@ -106,7 +106,11 @@ printer-share-toolkit/ │ ├── 05-Rollback-Win7.ps1 # Rollback changes on Windows 7 Hosts │ └── dev/ │ └── Test-Scripts.ps1 # Syntax, PS 2.0 compatibility, and lint checks -├── .github/workflows/ci.yml # CI: automated lint on push / pull request +├── tests/ # Pester tests (menu, structure, quality checker) +│ ├── Run-Tests.ps1 # Runs the whole test suite +│ └── *.Tests.ps1 +├── .github/workflows/ci.yml # CI: automated lint + tests on push / pull request +├── .editorconfig # Writing style (encoding, indentation, line endings) ├── CHANGELOG.md # Change history ├── VERSION # Application version ├── LICENSE # MIT License @@ -142,24 +146,30 @@ Don't want to type long PowerShell commands? Use the **interactive menu** instea ```text ============================================================ - PRINTER SHARING TOOLKIT + PRINTER SHARING TOOLKIT v1.0.0 ============================================================ - OS ini : Windows 10 64-bit - - 1. HOST - Bagikan printer dari PC ini - 2. KLIEN - Sambungkan ke printer yang dibagikan - 3. DIAGNOSA - Cek masalah sharing (read-only) - 4. PERBAIKAN - Fix kompatibilitas Windows 7 - 5. ROLLBACK - Kembalikan pengaturan host - 0. Keluar + This OS : Windows 10 64-bit + Shared printers : none yet + + 1. HOST - Share a printer from this PC + 2. CLIENT - Connect to a shared printer + 3. DIAGNOSE - Check sharing problems (read-only) + 4. REPAIR - Fix Windows 7 compatibility + 5. ROLLBACK - Restore host settings + 6. LOGS - View recent logs & backups + 7. HELP - Quick guide & open README + 8. LANGUAGE - Switch language (ID/EN) + 0. EXIT ``` The menu detects your Windows version (7 / 10 / 11) and picks the right script, so you never have to remember parameters like `-PrinterName`, `-Server`, `-ShareName`, or `-AllowLegacyWin7`. > [!TIP] -> - **HOST**: choose `1` → `2` to share a printer. Just pick the printer from the list and answer prompts such as *"Are there Windows 7 clients?"*. +> - **HOST**: choose `1` → `2` to share a printer. Just pick the printer from the list and answer prompts such as *"Are there Windows 7 clients?"*. Use `1` → `4` to stop sharing (unshare). > - **CLIENT**: choose `2` → `2` to connect. For Windows 7 32-bit, use the *LocalPort* option and provide the `.inf` driver path. > - **DIAGNOSTICS**: choose `3` (safe, changes nothing). +> - **LOGS**: choose `6` to list recent logs/backups, open the folder, or view the content. +> - **LANGUAGE**: choose `8` to switch between Indonesian and English; the choice is remembered. > - The menu only **wraps** the original scripts in `host\`, `client\`, and `tools\`; manual PowerShell usage below still works exactly as before. --- @@ -348,8 +358,22 @@ It performs three checks: Use `-FailOnWarning` to be stricter (warnings count as failures), or `-SkipLint` to skip the lint stage. -GitHub Actions CI (`.github/workflows/ci.yml`) runs these checks automatically -on every `push` and `pull request`. +There is also a **Pester test suite** that verifies the menu logic, repository +structure, and the quality checker: + +```powershell +.\tests\Run-Tests.ps1 +``` + +The tests run on both Pester 3.x (bundled with Windows PowerShell 5.1) and Pester 5. +If Pester is not installed: + +```powershell +Install-Module Pester -Scope CurrentUser -Force +``` + +GitHub Actions CI (`.github/workflows/ci.yml`) runs these checks and tests +automatically on every `push` and `pull request`. --- diff --git a/README.md b/README.md index 9e1159c..0389b62 100644 --- a/README.md +++ b/README.md @@ -106,7 +106,11 @@ printer-share-toolkit/ │ ├── 05-Rollback-Win7.ps1 # Mengembalikan perubahan Host Windows 7 │ └── dev/ │ └── Test-Scripts.ps1 # Cek sintaks, kompatibilitas PS 2.0, dan lint -├── .github/workflows/ci.yml # CI: lint otomatis saat push / pull request +├── tests/ # Test Pester (menu, struktur, pemeriksa kualitas) +│ ├── Run-Tests.ps1 # Menjalankan seluruh test +│ └── *.Tests.ps1 +├── .github/workflows/ci.yml # CI: lint + test otomatis saat push / pull request +├── .editorconfig # Gaya penulisan (encoding, indentasi, akhir baris) ├── CHANGELOG.md # Riwayat perubahan ├── VERSION # Nomor versi aplikasi ├── LICENSE # Lisensi MIT @@ -142,24 +146,30 @@ Tidak ingin mengetik perintah panjang di PowerShell? Cukup pakai **menu interakt ```text ============================================================ - PRINTER SHARING TOOLKIT + PRINTER SHARING TOOLKIT v1.0.0 ============================================================ OS ini : Windows 10 64-bit + Printer dibagikan : belum ada 1. HOST - Bagikan printer dari PC ini 2. KLIEN - Sambungkan ke printer yang dibagikan 3. DIAGNOSA - Cek masalah sharing (read-only) 4. PERBAIKAN - Fix kompatibilitas Windows 7 5. ROLLBACK - Kembalikan pengaturan host - 0. Keluar + 6. LOG - Lihat log & backup terakhir + 7. BANTUAN - Panduan singkat & buka README + 8. BAHASA - Ganti bahasa (ID/EN) + 0. KELUAR ``` Menu otomatis mendeteksi versi Windows (7 / 10 / 11) dan memilih script yang tepat, sehingga Anda tidak perlu menghafal parameter seperti `-PrinterName`, `-Server`, `-ShareName`, atau `-AllowLegacyWin7`. > [!TIP] -> - **HOST**: pilih menu `1` → `2` untuk membagikan printer. Anda cukup memilih printer dari daftar, lalu menjawab pertanyaan seperti *"Ada klien Windows 7?"*. +> - **HOST**: pilih menu `1` → `2` untuk membagikan printer. Anda cukup memilih printer dari daftar, lalu menjawab pertanyaan seperti *"Ada klien Windows 7?"*. Menu `1` → `4` untuk berhenti membagikan (unshare). > - **KLIEN**: pilih menu `2` → `2` untuk menyambung. Khusus Windows 7 32-bit, gunakan pilihan *mode LocalPort* dan masukkan path driver `.inf`. > - **DIAGNOSA**: pilih menu `3` (aman, tidak mengubah apa pun). +> - **LOG**: pilih menu `6` untuk melihat log/backup terbaru, membuka foldernya, atau menampilkan isinya. +> - **BAHASA**: pilih menu `8` untuk berganti antara Bahasa Indonesia dan English; pilihan disimpan. > - Menu ini hanya **membungkus** script asli di folder `host\`, `client\`, dan `tools\`; pemakaian manual lewat PowerShell tetap tersedia seperti dijelaskan di bawah. --- @@ -348,7 +358,21 @@ Pemeriksa ini melakukan tiga hal: Gunakan `-FailOnWarning` untuk memperketat (warning dianggap gagal), atau `-SkipLint` untuk melewati tahap lint. -CI GitHub Actions (`.github/workflows/ci.yml`) menjalankan pemeriksaan ini +Selain itu, tersedia **test Pester** untuk memverifikasi logika menu, kelengkapan +struktur repositori, dan pemeriksa kualitas: + +```powershell +.\tests\Run-Tests.ps1 +``` + +Test berjalan di Pester 3.x (bawaan Windows PowerShell 5.1) maupun Pester 5. +Bila Pester belum terpasang: + +```powershell +Install-Module Pester -Scope CurrentUser -Force +``` + +CI GitHub Actions (`.github/workflows/ci.yml`) menjalankan pemeriksaan dan test ini otomatis pada setiap `push` dan `pull request`. --- diff --git a/tests/Menu.Tests.ps1 b/tests/Menu.Tests.ps1 new file mode 100644 index 0000000..336b194 --- /dev/null +++ b/tests/Menu.Tests.ps1 @@ -0,0 +1,126 @@ +#Requires -Version 5.1 +<# +.SYNOPSIS + Test untuk Menu.ps1 (logika menu, tanpa menjalankan menunya). +#> + +$script:RepoRoot = Split-Path -Parent $PSScriptRoot +. (Join-Path $PSScriptRoot 'TestHelpers.ps1') + +# Menu.ps1 sengaja tidak dijalankan saat di-dot-source, jadi aman dimuat di sini. +. (Join-Path $script:RepoRoot 'Menu.ps1') + +Describe 'Menu.ps1 - pemuatan' { + It 'tidak menjalankan menu saat di-dot-source' { + Assert-NotNull (Get-Command -Name 'Start-Menu' -ErrorAction SilentlyContinue) 'Fungsi Start-Menu tidak terdefinisi.' + } + + It 'membaca versi dari file VERSION' { + $expected = (Get-Content -LiteralPath (Join-Path $script:RepoRoot 'VERSION') -TotalCount 1).Trim() + Assert-Equal $Script:Version $expected + } + + It 'menyimpan root di folder repositori' { + Assert-Equal $Script:Root $script:RepoRoot + } +} + +Describe 'Menu.ps1 - deteksi OS' { + It 'mengenali keluarga OS' { + Assert-True (@('Win7', 'Win8', 'Win10', 'Win11') -contains $Script:OsFamily) ("OS tidak dikenal: " + $Script:OsFamily) + } + + It 'menunjuk script host yang ada' { + $p = Get-HostScript + Assert-True (Test-Path -LiteralPath $p) ("Script host tidak ada: " + $p) + } + + It 'menunjuk script klien yang ada' { + $p = Get-ClientScript + Assert-True (Test-Path -LiteralPath $p) ("Script klien tidak ada: " + $p) + } + + It 'memberi label OS yang tidak kosong' { + Assert-True ((Get-OsLabel).Length -gt 0) + } +} + +Describe 'Menu.ps1 - bahasa' { + It 'menerjemahkan kunci di kedua bahasa' { + $before = $Script:Lang + try { + $Script:Lang = 'id' + Assert-Equal (T 'itemExit') 'KELUAR' + $Script:Lang = 'en' + Assert-Equal (T 'itemExit') 'EXIT' + } + finally { + $Script:Lang = $before + } + } + + It 'memakai Indonesia sebagai fallback' { + $before = $Script:Lang + try { + $Script:Lang = 'xx' + Assert-Equal (T 'itemExit') 'KELUAR' + } + finally { + $Script:Lang = $before + } + } + + It 'mengembalikan nama kunci bila kunci tidak ada' { + Assert-Equal (T 'kunci.tidak.ada.xyz') 'kunci.tidak.ada.xyz' + } + + It 'punya daftar kunci yang sama untuk ID dan EN' { + $idKeys = @($Script:Strings['id'].Keys) + $enKeys = @($Script:Strings['en'].Keys) + $missingEn = @($idKeys | Where-Object { -not $Script:Strings['en'].ContainsKey($_) }) + $missingId = @($enKeys | Where-Object { -not $Script:Strings['id'].ContainsKey($_) }) + Assert-Equal $missingEn.Count 0 ('Kunci hilang di EN: ' + ($missingEn -join ', ')) + Assert-Equal $missingId.Count 0 ('Kunci hilang di ID: ' + ($missingId -join ', ')) + } +} + +Describe 'Menu.ps1 - format argumen' { + It 'memformat hashtable sebagai parameter bernama' { + $s = Format-ToolArgs @{ Server = 'PC-TEST'; Repair = $true; SetDefault = $false } + Assert-Match $s '-Server "PC-TEST"' + Assert-Match $s '-Repair' + Assert-NotMatch $s '-SetDefault' + } + + It 'memformat array sebagai argumen posisional' { + $s = Format-ToolArgs @('PC-TEST', 'SHARE-X', '-', '-', 'test', '-') + Assert-Equal $s 'PC-TEST SHARE-X - - test -' + } + + It 'mengembalikan teks kosong untuk argumen kosong' { + Assert-Equal (Format-ToolArgs $null) '' + } +} + +Describe 'Menu.ps1 - printer' { + It 'Get-LocalPrinterNames mengembalikan daftar tanpa error' { + $names = @(Get-LocalPrinterNames) + foreach ($n in $names) { Assert-True ($n.Length -gt 0) } + } + + It 'Get-SharedPrinters mengembalikan objek dengan properti Name/ShareName' { + $shared = @(Get-SharedPrinters) + foreach ($p in $shared) { + Assert-NotNull $p.Name + Assert-True ($p.PSObject.Properties.Name -contains 'ShareName') + } + } + + It 'Get-ShareStatusText mengembalikan teks' { + Assert-True ((Get-ShareStatusText).Length -gt 0) + } + + It 'Test-IsAdmin mengembalikan boolean' { + Assert-True ((Test-IsAdmin) -is [bool]) + } +} diff --git a/tests/Quality.Tests.ps1 b/tests/Quality.Tests.ps1 new file mode 100644 index 0000000..0b2c20d --- /dev/null +++ b/tests/Quality.Tests.ps1 @@ -0,0 +1,46 @@ +#Requires -Version 5.1 +<# +.SYNOPSIS + Test integrasi untuk pemeriksa kualitas tools\dev\Test-Scripts.ps1. +#> + +$script:RepoRoot = Split-Path -Parent $PSScriptRoot +. (Join-Path $PSScriptRoot 'TestHelpers.ps1') + +function Invoke-Checker { + param([string]$RepoRoot) + + $checker = Join-Path $RepoRoot 'tools\dev\Test-Scripts.ps1' + $exe = Get-Command powershell.exe -ErrorAction SilentlyContinue + if ($exe) { + & $exe.Source -NoProfile -ExecutionPolicy Bypass -File $checker *> $null + } + else { + & pwsh -NoProfile -ExecutionPolicy Bypass -File $checker *> $null + } + return $LASTEXITCODE +} + +Describe 'Pemeriksa kualitas (Test-Scripts.ps1)' { + It 'lulus pada repositori yang bersih' { + Assert-Equal (Invoke-Checker $script:RepoRoot) 0 + } + + It 'gagal saat menemukan kode yang tidak kompatibel PS 2.0' { + $badDir = Join-Path $script:RepoRoot 'tests\_tmp_negative' + $badFile = Join-Path $badDir 'Bad-Ps2.ps1' + New-Item -ItemType Directory -Path $badDir -Force | Out-Null + Set-Content -LiteralPath $badFile -Encoding ASCII -Value @( + '#Requires -Version 2.0' + '$here = $PSScriptRoot' + '$list = [ordered]@{ a = 1 }' + ) + try { + $code = Invoke-Checker $script:RepoRoot + Assert-True ($code -ne 0) 'Pemeriksa seharusnya gagal pada file yang tidak kompatibel.' + } + finally { + Remove-Item -LiteralPath $badDir -Recurse -Force -ErrorAction SilentlyContinue + } + } +} diff --git a/tests/Run-Tests.ps1 b/tests/Run-Tests.ps1 new file mode 100644 index 0000000..0245e8e --- /dev/null +++ b/tests/Run-Tests.ps1 @@ -0,0 +1,50 @@ +#Requires -Version 5.1 +<# +.SYNOPSIS + Menjalankan seluruh test Pester di folder tests\. + +.DESCRIPTION + Berfungsi di Pester 3.x (bawaan Windows PowerShell 5.1) maupun Pester 4/5. + + Keluar dengan kode: + 0 - semua test lulus + 1 - ada test yang gagal + 2 - Pester tidak terpasang + +.EXAMPLE + .\tests\Run-Tests.ps1 +#> +[CmdletBinding()] +param() + +$ErrorActionPreference = 'Stop' + +if (-not (Get-Module -ListAvailable -Name Pester)) { + Write-Host 'Pester tidak terpasang.' -ForegroundColor Red + Write-Host 'Install-Module Pester -Scope CurrentUser -Force' -ForegroundColor Yellow + exit 2 +} + +Import-Module Pester -Force +$pesterVersion = (Get-Module Pester).Version +Write-Host ('Pester ' + $pesterVersion) -ForegroundColor Cyan +Write-Host '' + +$params = @{ + Path = $PSScriptRoot + PassThru = $true +} +if ($pesterVersion.Major -ge 5) { + $params['Output'] = 'Detailed' +} + +$result = Invoke-Pester @params + +Write-Host '' +if ($result.FailedCount -gt 0) { + Write-Host ('HASIL: GAGAL ({0} dari {1} test gagal)' -f $result.FailedCount, $result.TotalCount) -ForegroundColor Red + exit 1 +} + +Write-Host ('HASIL: LULUS ({0} test)' -f $result.PassedCount) -ForegroundColor Green +exit 0 diff --git a/tests/Structure.Tests.ps1 b/tests/Structure.Tests.ps1 new file mode 100644 index 0000000..7f96356 --- /dev/null +++ b/tests/Structure.Tests.ps1 @@ -0,0 +1,78 @@ +#Requires -Version 5.1 +<# +.SYNOPSIS + Memeriksa kelengkapan struktur repositori. +#> + +$script:RepoRoot = Split-Path -Parent $PSScriptRoot +. (Join-Path $PSScriptRoot 'TestHelpers.ps1') + +$script:RequiredFiles = @( + 'Menu.cmd' + 'Menu.ps1' + 'README.md' + 'README.en.md' + 'LICENSE' + 'VERSION' + 'CHANGELOG.md' + '.gitignore' + '.editorconfig' + 'PSScriptAnalyzerSettings.psd1' + 'tools\dev\Test-Scripts.ps1' + 'tools\03-Test-PrinterShare.ps1' + 'tools\04-Fix-LegacyCompat.ps1' + 'tools\05-Rollback.ps1' + 'tools\05-Rollback-Win7.ps1' + 'host\Win7\01-Sharing-Win7.ps1' + 'host\Win10\01-Sharing-Win10.ps1' + 'host\Win11\01-Sharing-Win11.ps1' + 'client\Win7\02-Connect-Win7.cmd' + 'client\Win7\02-Connect-Win7.ps1' + 'client\Win10\02-Connect-Win10.ps1' + 'client\Win11\02-Connect-Win11.ps1' + '.github\workflows\ci.yml' +) + +Describe 'Struktur repositori' { + foreach ($rel in $script:RequiredFiles) { + $full = Join-Path $script:RepoRoot $rel + It ('file ada: ' + $rel) { + Assert-True (Test-Path -LiteralPath $full -PathType Leaf) ('File tidak ditemukan: ' + $full) + } + } + + It 'VERSION berisi versi semantik' { + $v = (Get-Content -LiteralPath (Join-Path $script:RepoRoot 'VERSION') -TotalCount 1).Trim() + Assert-Match $v '^[0-9]+\.[0-9]+\.[0-9]+$' + } + + It 'Menu.cmd memanggil Menu.ps1' { + $c = Get-Content -LiteralPath (Join-Path $script:RepoRoot 'Menu.cmd') -Raw + Assert-Match $c 'Menu\.ps1' + } + + It 'Menu.cmd meminta hak Administrator (RunAs)' { + $c = Get-Content -LiteralPath (Join-Path $script:RepoRoot 'Menu.cmd') -Raw + Assert-Match $c 'RunAs' + } + + It 'CI menjalankan pemeriksa script' { + $c = Get-Content -LiteralPath (Join-Path $script:RepoRoot '.github\workflows\ci.yml') -Raw + Assert-Match $c 'Test-Scripts\.ps1' + } + + It 'CI menjalankan test Pester' { + $c = Get-Content -LiteralPath (Join-Path $script:RepoRoot '.github\workflows\ci.yml') -Raw + Assert-Match $c 'Run-Tests\.ps1' + } + + It 'README (ID) menyebut Menu.cmd' { + $c = Get-Content -LiteralPath (Join-Path $script:RepoRoot 'README.md') -Raw + Assert-Match $c 'Menu\.cmd' + } + + It 'README (EN) menyebut Menu.cmd' { + $c = Get-Content -LiteralPath (Join-Path $script:RepoRoot 'README.en.md') -Raw + Assert-Match $c 'Menu\.cmd' + } +} diff --git a/tests/TestHelpers.ps1 b/tests/TestHelpers.ps1 new file mode 100644 index 0000000..6c2fae8 --- /dev/null +++ b/tests/TestHelpers.ps1 @@ -0,0 +1,88 @@ +#Requires -Version 5.1 +<# +.SYNOPSIS + Fungsi assertion untuk file Pester di folder tests\. + +.DESCRIPTION + Sintaks Should berbeda antar versi Pester: + + - Pester 3.x (bawaan Windows PowerShell 5.1) memakai "Should Be". + - Pester 4/5 memakai "Should -Be". + + Supaya file test yang sama tetap jalan di kedua versi, test memakai + helper di bawah ini. Helper melempar exception saat gagal, dan Pester + melaporkannya sebagai test yang gagal. +#> + +function Assert-True { + param( + [AllowNull()]$Condition, + [string]$Message = 'Kondisi seharusnya true.' + ) + if (-not $Condition) { throw $Message } +} + +function Assert-False { + param( + [AllowNull()]$Condition, + [string]$Message = 'Kondisi seharusnya false.' + ) + if ($Condition) { throw $Message } +} + +function Assert-Equal { + param( + [AllowNull()]$Actual, + [AllowNull()]$Expected, + [string]$Message = '' + ) + if (-not [object]::Equals($Actual, $Expected)) { + $prefix = '' + if ($Message -ne '') { $prefix = $Message + ' ' } + throw ('{0}Harap <{1}>, dapat <{2}>.' -f $prefix, $Expected, $Actual) + } +} + +function Assert-NotNull { + param( + [AllowNull()]$Value, + [string]$Message = 'Nilai seharusnya tidak null.' + ) + if ($null -eq $Value) { throw $Message } +} + +function Assert-Match { + param( + [AllowNull()][string]$Actual, + [string]$Pattern, + [string]$Message = '' + ) + if ($Actual -notmatch $Pattern) { + $prefix = '' + if ($Message -ne '') { $prefix = $Message + ' ' } + throw ('{0}<{1}> seharusnya cocok dengan <{2}>.' -f $prefix, $Actual, $Pattern) + } +} + +function Assert-NotMatch { + param( + [AllowNull()][string]$Actual, + [string]$Pattern, + [string]$Message = '' + ) + if ($Actual -match $Pattern) { + $prefix = '' + if ($Message -ne '') { $prefix = $Message + ' ' } + throw ('{0}<{1}> seharusnya TIDAK cocok dengan <{2}>.' -f $prefix, $Actual, $Pattern) + } +} + +function Assert-Throws { + param( + [scriptblock]$Script, + [string]$Message = 'Script seharusnya melempar error.' + ) + $threw = $false + try { & $Script } catch { $threw = $true } + if (-not $threw) { throw $Message } +}