PowerShell in Task Manager Shows Window - powershell

I am trying to make Task Schedule Task so it is completely invisible that a PowerShell script is running so I created a Task on my Win10 machine configured as follows:
Program/Script:
powershell.exe
Add arguments (optional):
-WindowStyle Hidden -command "& {Out-File 'C:\temp\somefile.txt'}" -NonInteractive -NoLogo -NoProfile
When I run this task the powershell command windows pops up for a split second which I don't want.

You can get around this with an 'Application Host' type wrapper. This is a known issue with powershell as a console-based host.
The most convenient way to do this I've found, is to use WScript.exe and run a VBS script that will invoke the process "invisibly", with no console or task bar flicker.
VBS Code:
On Error Resume Next
ReDim args(WScript.Arguments.Count-1)
For i = 0 To WScript.Arguments.Count-1
If InStr(WScript.Arguments(i), " ") > 0 Then
args(i) = Chr(34) & WScript.Arguments(i) & Chr(34)
Else
args(i) = WScript.Arguments(i)
End If
Next
CreateObject("WScript.Shell").Run Join(args, " "), 0, False
Save the above code in a file with extension '.vbs', and place it somewhere it can be run by the client running the task. This may be in a protected fileshare on the network (if you expect the script it invokes to only run while connected to the network), or locally on the client.
Now when you invoke your console-based script (PowerShell, BAT, CScript, etc.), you invoke this VBS script with WScript explicitly WScript.exe. It also pays to throw on the 'Batch Mode' parameter //B which will suppress script errors & prompts - such as if the wrapper file itself can't be found.
At this point, all you need to do is pass powershell & the command you want powershell to run to this launch sequence:
WScript.exe //B "\\Path\To\Launcher.VBS" powershell.exe -ExecutionPolicy ByPass -file "\\Powershell\Script\To\Run"

I had the same problem, it was resolved at the simple way.
When you create a Task on Windows, just set this configuration:
Open Properties dialog;
Then you check Run whether user is logged on or not;
You can check Do not store password to avoid asking for PC password on Task execution;
In Add arguments (optional): just:
-File 'C:\temp\somefile.txt
This spcript will run without popup the prompt.
Solved in this link below:
https://stackoverflow.com/a/50630717/19926325

Related

Powershell window does not hide even after adding -WindowsStyle hidden while running task from task scheduler

I have created a task in task scheduler.
Its basically a powershell script which has to run in interactive mode.
Task is running under SYSTEM account.
In Actions tab, under Program/Script I have added path of the ServiceUI.exe e.g, C:**\ServiceUI.exe
Under Add arguments option, I have added C:\WINDOWS\system32\WindowsPowerShell\v1.0\powershell.exe -Windowstyle hidden -NoProfile -Executionpolicy bypass -file "C:**\PS1.ps1"
When I run the task, powershell window prompt shows for a fraction of a second.
Could someone please suggest a way to hide it?
I was able to fix the problem by using vb script.
WScript.Quit CreateObject("WScript.Shell").Run("powershell.exe -ExecutionPolicy Bypass -WindowStyle Hidden -File " & PSscriptPath, 0, true)
In Actions tab, under Program/Script I had path of the ServiceUI.exe e.g, C:**\ServiceUI.exe
Added wscript.exe "vbs script path" in the arguments option.
Powershell prompt doesn't come up, and task works perfectly in interactive mode under SYSTEM account using these options.

Windows Sandbox PowerShell logon command window not visible

I'm trying to use Windows Sandbox with a PowerShell logon command. This is the LogonCommand section of my WSB file:
<LogonCommand>
<Command>C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe -executionpolicy unrestricted -file "C:\\Users\\WDAGUtilityAccount\\Desktop\\boot.ps1" -noexit</Command>
</LogonCommand>
The Windows Sandbox instance loads up okay suggesting no syntactic/validation issues with the WSB file content, but the PowerShell window is not shown. Adding -windowstyle normal has no effect.
I suspect the LogonCommand content is run in a command prompt which is not made visible so running the command to open PowerShell from it somehow "inherits" the terminal window not being visible.
Is it possible to force the PowerShell terminal window to reveal itself in such a case? I want to do this so that I can see the errors that I get because the PowerShell script is not executing as expected and I'm blind to any output/progress indication.
Found an answer (doesn't look like the cleanest option, but works):
<Command>powershell -executionpolicy unrestricted -command "start powershell {-noexit -file C:\Users\WDAGUtilityAccount\Desktop\boot.ps1}"</Command>
powershell switches from CMD to PowerShell
-windowstyle normal won't work to make this PowerShell window visible
-executionpolicy unrestricted allows the nested PowerShell to run from file
start powershell runs another PowerShell with visible window
Running this directly for LogonCommand will not work
-noexit tells the nested PowerShell to remain visible
This is not necessary but it is useful for debugging the script errors
-file C:\Users\WDAGUtilityAccount\Desktop\boot.ps1 runs the given script
Share it with the machine by using a MappedFolder in the WSB configuration

Running PowerShell code inside VBS with many nested quotes, in one line

I'm starting to see double here from staring at this so long. I am trying to use an environment variable inside a script path that I'm going to launch from PowerShell, all initiated from a single line inside an mshta command run from a scheduled task on logon.
In case you were wondering, MSHTA can execute HTML/VBS/JS as if a local GUI app.
mshta vbscript:Execute("CreateObject(""Wscript.Shell"").Run ""powershell -NoLogo -Command """"& '\\$env:USERDNSDOMAIN\FOLDER1\FOLDER with Spaces\Folder3\Script-To-Run.ps1'"""""", 0 : window.close")
Premise: I have to do it this way to prevent momentary popups that flash onscreen when running from a scheduled task in user context. I cannot run this script in the System context.
I know that putting anything inside two single quotes gives me a string literal but if I try double quotes it seems to then use the space in the path. I've tried separating the two and concatenating them in all sorts of ways to no avail.
VBS equivalent of $env:USERDNSDOMAIN is
CreateObject("Wscript.Shell").ExpandEnvironmentStrings( "%USERDNSDOMAIN%" )
If the goal/purpose is to execute a PowerShell script without displaying the powershell.exe console window, you can do this by running it from a VBScript script executed by wscript.exe (not cscript.exe).
Example VBScript script:
Dim WshShell
Set WshShell = CreateObject("WScript.Shell")
WshShell.Run "%SystemRoot%\system32\WindowsPowerShell\v1.0\powershell.exe -NoProfile -ExecutionPolicy Bypass -File """d:\path name\whatever.ps1"" [parameter [...]]", 0, False
The second parameter of the WshShell object's Run method is 0, so powershell.exe executes from a hidden window.
(Hint: The -File parameter to powershell.exe is generally easier to use than -Command. It must be the last parameter on the powershell.exe command line.)
End result: VBScript script runs the PowerShell script from a hidden window. Also, the VBScript itself has no console window, because you executed it using wscript.exe (the GUI host).

Batch script not calling Powershell

I have a batch script that calls a Powershell file in administration mode. I found this code a while ago, and it's worked great ever since:
PowerShell -NoProfile -ExecutionPolicy Bypass -Command
"& {Start-Process PowerShell -ArgumentList '-NoProfile -ExecutionPolicy Bypass -File %PSFile%' -Verb RunAs}";
This time though, I called the batch script from another program. This program says the process worked, but it didn't actually do anything. Examining the logs from echo, I can see the batch script is being called, but it's not calling Powershell. I tried running the batch script manually, and it calls PS fine, so something with how the batch script is being called by the other program is messing with how it calls PS.
This in mind, I tried changing the batch script to directly run my .ps1 file, instead of starting a new admin instance of powershell to start it. My new .bat file looked like this:
Powershell -File %PSFILE% -Verb RunAs
Calling this from the other program sucessfully calls my Powershell script, but I get a bunch of errors from the PS script, since it's not an admin PS session like it needs to be.
How can I change my batch script to call Powershell as an admin, without using Powershell to call itself (which doesn't seem to work with the program that needs to run it)?
EDIT: After trying a bunch of tweaks, I've found I don't even need to be in admin mode to do what this script does. However, I still get access denied errors when running it through the program (admin or not). So something about running it from the program is making it need more permissions than when I run the batch script manually.
This is what I do (inside the .bat file):
If the .bat is NOT running as admin
powershell.exe -Command "powershell.exe 'C:\path\to\script.ps1' -Verb runAs"
If the .bat is running as admin
powershell.exe -ExecutionPolicy Bypass -Command "C:\path\to\script.ps1"
You could use a small utility I wrote called elevate32.exe/elevate64.exe.
elevate64 -- C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -NoProfile -ExecutionPolicy Bypass -File "d:\path to script\scriptfile.ps1"
elevate32.exe (32-bit version) and elevate64.exe (64-bit version) basically elevate whatever command line you pass to them.
You can get it here (ElevationToolkit1.zip):
http://www.westmesatech.com/misctools.html
An alternative is to use a short WSH script that, when called, provokes elevation. An example is on Aaron Margosis' blog here:
https://blogs.msdn.microsoft.com/aaron_margosis/2007/07/01/scripting-elevation-on-vista/
Script:
// elevate.js -- runs target command line elevated
if (WScript.Arguments.Length >= 1) {
Application = WScript.Arguments(0);
Arguments = "";
for (Index = 1; Index < WScript.Arguments.Length; Index += 1) {
if (Index > 1) {
Arguments += " ";
}
Arguments += WScript.Arguments(Index);
}
new ActiveXObject("Shell.Application").ShellExecute(Application, Arguments, "", "runas");
}
else {
WScript.Echo("Usage:");
WScript.Echo("elevate Application Arguments");
}
The limitations of this approach is that it relies on the WSH command-line parser and can't wait for the program to terminate. These limits may not be a problem in your scenario.
Looks like I was totally off as to the problem source. This was a permissions error on some folders I was editing. The program I was running the scripts through acts as a separate service. I had to add that with modify permissions to the security groups of all the folders I was editing. No elevation required in the scripts, just modifying permissions.

StdIn.Writeline Fails in ASP sending strings to PowerShell

I am updating a Classic ASP webpage. It seems that if you try to use StdIn.Writeline to send command to PowerShell it fails. It behaves like the command interpreter only accepts commands as part of creating the session.
Does anyone have any working examples of passing supplemental commands to an open PowerShell execution from a Classic (Not ASP.Net) web page?
Command = "C:\Windows\SysWOW64\WindowsPowerShell\v1.0\Powershell.exe -NoExit -inputformat none -ExecutionPolicy bypass -NonInteractive -noprofile -Command ""& {""$PSVersionTable.PSVersion""; ""Add-PSSnapIn VMware* -ErrorAction SilentlyContinue""; 2>&1} "
Set oExec = WshShell.Exec(Command)
If oExec.Status = 0 Then
oExec.StdIn.Writeline("Dir 2>&1")
oExec.StdIn.Writeline("Exit")
oExec.StdIn.Close()
Do While oExec.StdOut.AtEndOfStream <> True
Response.Write oExec.StdOut.ReadLine
Loop
End If
When I try to keep the command interpreter open and use StdIn.Writeline to send additional commands, including the exit command, it never closes and I have to kill the process on the IIS server.
If I remove the -NoExit switch, it does close after running the string passed, and obviously I can't send additional commands to run.
Any ideas on how to get PowerShell to work like %comspec% does?