0
votes

GOALS: run a powershell script without showing the window (it's ok if it pops up for few seconds).

PROBLEM: the script tcplisten.ps1 works just if the window is displayed to the user. All the attempts below don't work. Because when I run netstat -ano -p tcp, port 9999 is not listening.

tcplisten.ps1

$Listener = [System.Net.Sockets.TcpListener]9999;
$Listener.Start()

ATTEMPTS:

powershell.exe

powershell.exe -windowstyle hidden .\tcplisten.ps1

hidden -command

powershell -windowstyle hidden -command $Listener = [System.Net.Sockets.TcpListener]9999; $Listener.Start()

-NoProfile -NonInteractive -ExecutionPolicy Bypass

powershell -NoP -NonI -W Hidden -Exec Bypass -Command

Start-Process

Start-Process powershell.exe -ArgumentList "-WindowsStyle hidden -file .\tcplisten.ps1"

vbs script

Create a .vbs with this script and run it

command = "powershell.exe -nologo -command C:\Users\Utente\Desktop\tcplisten.ps1"
set shell = CreateObject("WScript.Shell")
shell.Run command,0

QUESTION: is there a solution? Am I doing some mistake?

2

2 Answers

0
votes

Just give a try for this vbscript :

Option Explicit
Dim Ws,Port,StrCmd
Set Ws = WScript.CreateObject("WScript.Shell")
Port = 9999
REM We can run this script as admin or not 
Call RunAsAdmin()
Call Start_TcpListener(Port)
REM We try to launch the default browser by opening this url with port
ws.Run """http://127.0.0.1:9999""",1,False
wscript.sleep 5000
REM Here just for checking if the port is open or not !
StrCmd = "CMD /K Title Checking Openning Port on "& Port & "& netstat -ano -p tcp | find "& chr(34) & Port & chr(34) &""
Ws.Run StrCmd,1,True
'------------------------------------------------------------------------------
Sub Start_TcpListener(Port)
    Dim Ws,PS_CMD,shell
    Set Ws = WScript.CreateObject("WScript.Shell")
    PS_CMD = "$Listener = [System.Net.Sockets.TcpListener]"& Port &";" & vbCrLF &_
    "$Listener.Start{(}{)}~cls~"
    ws.run "Powershell",1,False
    ws.AppActivate "PowerShell"
    wscript.sleep 2000
    Ws.sendkeys(PS_CMD)
    wscript.sleep 2000
    Set shell = CreateObject("Shell.Application")
    Shell.MinimizeAll
End Sub
'------------------------------------------------------------------------------
Sub RunAsAdmin()
If Not WScript.Arguments.Named.Exists("elevate") Then
  CreateObject("Shell.Application").ShellExecute WScript.FullName _
    , chr(34) & WScript.ScriptFullName & chr(34) & " /elevate", "", "runas", 1
  WScript.Quit
End If
End Sub
'------------------------------------------------------------------------------
0
votes

Try running it as a background job. This command runs on the computer instead of any user so it keeps going when you logout:

Invoke-Command -ComputerName $env:COMPUTERNAME -FilePath 'C:\Users\Utente\Desktop\tcplisten.ps1' -AsJob