Automage

chat with powershell

Mar 6th, 2026
9
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 13.90 KB | None | 0 0
  1. <#
  2. .SYNOPSIS
  3. Simple LAN Chat between two PCs on the same network
  4. .DESCRIPTION
  5. Enables two-way communication between computers using TCP sockets
  6.  
  7. PC NAMES AND IPs:
  8. staaandup 192.168.1.101
  9. inferno 192.168.1.105
  10.  
  11. .PARAMETER RemoteIP
  12. IP address of the other computer (default: 192.168.1.101)
  13. .PARAMETER Port
  14. Port number to use for communication (default: 5050)
  15. .PARAMETER UserName
  16. Your display name in chat (default: current username)
  17. .EXAMPLE
  18. .\LAN-Chat.ps1 -RemoteIP "192.168.1.105" -Port 5050 -UserName "Staaandup"
  19. #>
  20.  
  21. param(
  22. [Parameter(Mandatory=$false)]
  23. [string]$RemoteIP = "192.168.1.101",
  24.  
  25. [Parameter(Mandatory=$false)]
  26. [int]$Port = 5050,
  27.  
  28. [Parameter(Mandatory=$false)]
  29. [string]$UserName = $env:USERNAME
  30. )
  31.  
  32. # Load required assemblies
  33. Add-Type -AssemblyName System.Windows.Forms
  34. Add-Type -AssemblyName System.Drawing
  35.  
  36. # Function to find an available port
  37. function Get-AvailablePort {
  38. param([int]$StartPort = 5050)
  39.  
  40. $port = $StartPort
  41. $maxPort = $StartPort + 100 # Try up to 100 ports above the starting port
  42.  
  43. while ($port -le $maxPort) {
  44. $tcpListener = $null
  45. try {
  46. $tcpListener = [System.Net.Sockets.TcpListener]::new($port)
  47. $tcpListener.Start()
  48. $tcpListener.Stop()
  49. return $port
  50. } catch {
  51. $port++
  52. } finally {
  53. if ($tcpListener) { $tcpListener.Stop() }
  54. }
  55. }
  56. return $null
  57. }
  58.  
  59. # Function to kill any leftover listener jobs
  60. function Clear-StaleListeners {
  61. $staleJobs = Get-Job -Name "LANChatListener_*" -ErrorAction SilentlyContinue | Where-Object { $_.State -eq 'Running' }
  62. foreach ($job in $staleJobs) {
  63. Write-Host "Cleaning up stale listener job: $($job.Name)" -ForegroundColor Yellow
  64. $job.StopJob()
  65. Remove-Job $job -Force
  66. }
  67. }
  68.  
  69. # Clean up stale jobs before starting
  70. Clear-StaleListeners
  71.  
  72. # Check if the port is available and find an alternative if needed
  73. $originalPort = $Port
  74. $availablePort = Get-AvailablePort -StartPort $Port
  75.  
  76. if (-not $availablePort) {
  77. Write-Host "ERROR: No available ports found in range $Port-$($Port+100)!" -ForegroundColor Red
  78. Write-Host "Please close other applications and try again." -ForegroundColor Yellow
  79. exit 1
  80. }
  81.  
  82. if ($availablePort -ne $originalPort) {
  83. Write-Host "Port $originalPort is in use. Using alternative port: $availablePort" -ForegroundColor Yellow
  84. $Port = $availablePort
  85. }
  86.  
  87. # Create a unique identifier for this session
  88. $sessionID = Get-Random -Maximum 99999
  89. $global:listenerRunning = $true
  90. $global:cleanupDone = $false
  91.  
  92. # Setup Ctrl+C handler
  93. [Console]::TreatControlCAsInput = $true
  94.  
  95. # Clear console and show welcome screen initially
  96. Clear-Host
  97. Write-Host "============================================================" -ForegroundColor DarkCyan
  98. Write-Host " LAN CHAT - Connected as: $UserName" -ForegroundColor Cyan
  99. Write-Host "============================================================" -ForegroundColor DarkCyan
  100. Write-Host "Remote PC IP: $RemoteIP" -ForegroundColor Yellow
  101. Write-Host "Local Port: $Port" -ForegroundColor Yellow
  102. if ($Port -ne $originalPort) {
  103. Write-Host "(Original port $originalPort was in use)" -ForegroundColor DarkYellow
  104. }
  105. Write-Host "------------------------------------------------------------" -ForegroundColor DarkGray
  106. Write-Host "Quick IP Reference:" -ForegroundColor Cyan
  107. Write-Host " staaandup = 192.168.1.101" -ForegroundColor White
  108. Write-Host " inferno = 192.168.1.105" -ForegroundColor White
  109. Write-Host "------------------------------------------------------------" -ForegroundColor DarkGray
  110. Write-Host "Type your messages below and press Enter to send." -ForegroundColor Green
  111. Write-Host "Type '/quit' to exit, '/clear' to clear screen" -ForegroundColor Green
  112. Write-Host "Type '/port' to see current port, '/ips' to show IP reference" -ForegroundColor Green
  113. Write-Host "------------------------------------------------------------" -ForegroundColor DarkGray
  114.  
  115. Write-Host "Starting listener on port $Port..." -ForegroundColor Green
  116.  
  117. # Start listener in a background job with better error handling
  118. $scriptBlock = {
  119. param($localPort, $userName)
  120.  
  121. Add-Type -AssemblyName System.Windows.Forms
  122. Add-Type -AssemblyName System.Drawing
  123.  
  124. $listener = $null
  125. $running = $true
  126.  
  127. try {
  128. # Create listener with reuse address option
  129. $listener = New-Object System.Net.Sockets.TcpListener([System.Net.IPAddress]::Any, $localPort)
  130. $listener.Server.SetSocketOption('Socket', 'ReuseAddress', 1)
  131. $listener.Start()
  132. $listener.Server.ReceiveTimeout = 1000
  133.  
  134. # Signal that listener started successfully
  135. Write-Host "LISTENER_READY: $localPort"
  136.  
  137. while ($running) {
  138. try {
  139. # Check if we can accept connections
  140. if ($listener.Pending()) {
  141. $client = $listener.AcceptTcpClient()
  142. $client.ReceiveTimeout = 5000
  143.  
  144. $stream = $client.GetStream()
  145. $reader = New-Object System.IO.StreamReader($stream)
  146.  
  147. # Read message
  148. $msg = $reader.ReadLine()
  149.  
  150. if ($msg) {
  151. $timeStamp = Get-Date -Format "HH:mm:ss"
  152.  
  153. # Parse message (format: "UserName: Message" or just raw message)
  154. if ($msg -match "^(.*?):(.*)$") {
  155. $senderName = $matches[1].Trim()
  156. $actualMessage = $matches[2].Trim()
  157. } else {
  158. $senderName = "Friend"
  159. $actualMessage = $msg
  160. }
  161.  
  162. # Display message in console
  163. Write-Host "[$timeStamp] " -NoNewline
  164. Write-Host "$senderName" -ForegroundColor Cyan -NoNewline
  165. Write-Host ": $actualMessage"
  166.  
  167. # Show balloon notification
  168. try {
  169. $notify = New-Object System.Windows.Forms.NotifyIcon
  170. $notify.Icon = [System.Drawing.SystemIcons]::Information
  171. $notify.Visible = $true
  172. $notify.ShowBalloonTip(3000, "LAN Chat - Message from $senderName", $actualMessage, [System.Windows.Forms.ToolTipIcon]::Info)
  173. Start-Sleep -Milliseconds 100
  174. $notify.Dispose()
  175. } catch {
  176. # Notifications might fail in some environments, ignore
  177. }
  178. }
  179.  
  180. $client.Close()
  181. } else {
  182. Start-Sleep -Milliseconds 100
  183. }
  184. } catch {
  185. # Check if this is just a timeout or actual error
  186. if ($_.Exception.Message -notlike "*timeout*") {
  187. Write-Host "Error in listener: $($_.Exception.Message)" -ForegroundColor Red
  188. }
  189. }
  190. }
  191. } catch {
  192. Write-Host "FATAL LISTENER ERROR: $($_.Exception.Message)" -ForegroundColor Red
  193. } finally {
  194. if ($listener) {
  195. try {
  196. $listener.Stop()
  197. } catch {}
  198. }
  199. }
  200. }
  201.  
  202. $listenerJob = Start-Job -Name "LANChatListener_$sessionID" -ScriptBlock $scriptBlock -ArgumentList $Port, $UserName
  203.  
  204. # Wait for listener to start - simplified to avoid false warnings
  205. $timeout = 5
  206. $listenerStarted = $false
  207. while ($timeout -gt 0 -and -not $listenerStarted) {
  208. Start-Sleep -Milliseconds 500
  209. $jobOutput = Receive-Job $listenerJob -ErrorAction SilentlyContinue
  210. if ($jobOutput -match "LISTENER_READY") {
  211. $listenerStarted = $true
  212. Write-Host "Listener started successfully on port $Port" -ForegroundColor Green
  213. }
  214. $timeout--
  215. }
  216.  
  217. if (-not $listenerStarted) {
  218. Write-Host "Note: Listener is starting in background." -ForegroundColor Yellow
  219. }
  220.  
  221. # Function to send message
  222. function Send-Message {
  223. param([string]$Message)
  224.  
  225. if ([string]::IsNullOrWhiteSpace($Message)) {
  226. return $true
  227. }
  228.  
  229. # Check for commands
  230. switch ($Message) {
  231. '/quit' { return $false }
  232. '/clear' {
  233. Clear-Host
  234. # Redisplay header
  235. Write-Host "============================================================" -ForegroundColor DarkCyan
  236. Write-Host " LAN CHAT - Connected as: $UserName" -ForegroundColor Cyan
  237. Write-Host "============================================================" -ForegroundColor DarkCyan
  238. Write-Host "Remote PC IP: $RemoteIP" -ForegroundColor Yellow
  239. Write-Host "Local Port: $Port" -ForegroundColor Yellow
  240. Write-Host "------------------------------------------------------------" -ForegroundColor DarkGray
  241. Write-Host "Quick IP Reference:" -ForegroundColor Cyan
  242. Write-Host " staaandup = 192.168.1.101" -ForegroundColor White
  243. Write-Host " inferno = 192.168.1.105" -ForegroundColor White
  244. Write-Host "------------------------------------------------------------" -ForegroundColor DarkGray
  245. Write-Host "Type your messages below and press Enter to send." -ForegroundColor Green
  246. Write-Host "Type '/quit' to exit, '/clear' to clear screen" -ForegroundColor Green
  247. Write-Host "Type '/port' to see current port, '/ips' to show IP reference" -ForegroundColor Green
  248. Write-Host "------------------------------------------------------------" -ForegroundColor DarkGray
  249. return $true
  250. }
  251. '/port' {
  252. Write-Host "Local port: $Port" -ForegroundColor Cyan
  253. return $true
  254. }
  255. '/ips' {
  256. Write-Host "IP Reference:" -ForegroundColor Cyan
  257. Write-Host " staaandup = 192.168.1.101" -ForegroundColor White
  258. Write-Host " inferno = 192.168.1.105" -ForegroundColor White
  259. return $true
  260. }
  261. }
  262.  
  263. # Format message with username
  264. $formattedMessage = "$UserName`: $Message"
  265. $timeStamp = Get-Date -Format "HH:mm:ss"
  266.  
  267. try {
  268. # Try to send message with retry logic
  269. $maxRetries = 2
  270. $retryCount = 0
  271. $sent = $false
  272.  
  273. while (-not $sent -and $retryCount -lt $maxRetries) {
  274. try {
  275. $client = New-Object System.Net.Sockets.TcpClient
  276. $client.Connect($RemoteIP, $Port)
  277. $client.SendTimeout = 3000
  278.  
  279. $writer = New-Object System.IO.StreamWriter($client.GetStream())
  280. $writer.AutoFlush = $true
  281. $writer.WriteLine($formattedMessage)
  282. $client.Close()
  283. $sent = $true
  284.  
  285. # Display sent message
  286. Write-Host "[$timeStamp] " -ForegroundColor DarkGray -NoNewline
  287. Write-Host "You" -ForegroundColor Green -NoNewline
  288. Write-Host ": $Message" -ForegroundColor White
  289.  
  290. } catch {
  291. $retryCount++
  292. if ($retryCount -ge $maxRetries) {
  293. throw
  294. }
  295. Start-Sleep -Milliseconds 200
  296. }
  297. }
  298. } catch {
  299. Write-Host "[$timeStamp] Could not send message: $($_.Exception.Message)" -ForegroundColor Red
  300. Write-Host " Make sure the other PC is running the chat script on port $Port" -ForegroundColor Yellow
  301. Write-Host " Target IP: $RemoteIP (staaandup = 101, inferno = 105)" -ForegroundColor Yellow
  302. }
  303.  
  304. return $true
  305. }
  306.  
  307. # Main sending loop with better status checking
  308. $running = $true
  309. $lastJobCheck = Get-Date
  310.  
  311. try {
  312. while ($running) {
  313. # Check listener status periodically (every 30 seconds)
  314. if (((Get-Date) - $lastJobCheck).TotalSeconds -gt 30) {
  315. $job = Get-Job -Name "LANChatListener_$sessionID" -ErrorAction SilentlyContinue
  316. if (-not $job -or $job.State -ne 'Running') {
  317. Write-Host "`nWARNING: Listener has stopped unexpectedly!" -ForegroundColor Red
  318. Write-Host "You can still send messages, but won't receive any." -ForegroundColor Yellow
  319. Write-Host "Type '/quit' and restart the script to fix this." -ForegroundColor Yellow
  320. }
  321. $lastJobCheck = Get-Date
  322. }
  323.  
  324. # Handle Ctrl+C
  325. if ([Console]::KeyAvailable) {
  326. $key = [Console]::ReadKey($true)
  327. if ($key.Modifiers -eq 'Control' -and $key.Key -eq 'C') {
  328. Write-Host "`nCtrl+C detected. Use '/quit' to exit gracefully." -ForegroundColor Yellow
  329. continue
  330. }
  331. }
  332.  
  333. # Get user input
  334. $userInput = Read-Host
  335.  
  336. # Send message and check if we should continue
  337. $running = Send-Message -Message $userInput
  338. }
  339. } finally {
  340. # Cleanup
  341. Write-Host "`nShutting down chat..." -ForegroundColor Yellow
  342.  
  343. # Stop listener job
  344. $jobs = Get-Job -Name "LANChatListener_*" -ErrorAction SilentlyContinue
  345. foreach ($job in $jobs) {
  346. if ($job.State -eq 'Running') {
  347. $job.StopJob()
  348. Start-Sleep -Milliseconds 500
  349. Remove-Job $job -Force -ErrorAction SilentlyContinue
  350. }
  351. }
  352.  
  353. # Clean up any leftover notify icons
  354. try {
  355. $notify = New-Object System.Windows.Forms.NotifyIcon
  356. $notify.Dispose()
  357. } catch {}
  358.  
  359. Write-Host "Chat ended. Goodbye!" -ForegroundColor Green
  360. }
Advertisement
Add Comment
Please, Sign In to add comment