Running PowerShell script as admin and with PowerShell window hidden - windows

I have a PowerShell script that needs to run as administrator when i click the .bat file to launch it, however, i also need the PowerShell window hidden. I have a script that currently launches it as admin, but i need it to hide the window as well. I have tried to put in -windowstyle hidden, but it does not work. Here is my launch script:
#ECHO OFF
SET ThisScriptsDirectory=%~dp0
SET PowerShellScriptPath=%ThisScriptsDirectory%PMCS_Full_InProgress.ps1
PowerShell -NoProfile -ExecutionPolicy Bypass -Command "& {Start-Process PowerShell -ArgumentList '-NoProfile -ExecutionPolicy Bypass -File ""%PowerShellScriptPath%""' -Verb RunAs}";
Can anyone help me hide the window? Thanks for your time.

Solved. I was not putting -windowstyle hiddeninsideofthe "& {Start-Process PowerShell -Arguments . . .} so it wasn't recognizing it at all. I was trying to put it on the outside. Thanks for your help!

Related

Batch script to run Powershell script: Flashing window

System: Windows 10
Powershell Version: 5.1
Purpose: Run a powershell script from a batch file
Parameters: Directory, Filename, Server, Username, Password all being passed in as string encompassed in "" when called from command to handle the situation when there is a space (such as the Directory which currently has a space in)
The Powershell script works perfectly, it creates the credential and starts the RDP connection without issues. When calling from a batch file however the Powershell window flashes and closes immediately. Command Prompt window is run as Administrator.
I've tried using:
- pause
- -noexit
- code from https://blog.danskingdom.com/allow-others-to-run-your-powershell-scripts-from-a-batch-file-they-will-love-you-for-it/
if ($Host.Name -eq "ConsoleHost")
{
Write-Host "Press any key to continue..."
$Host.UI.RawUI.FlushInputBuffer() # Make sure buffered input doesn't "press a key" and skip the ReadKey().
$Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyUp") > $null
}
Clicking on the appearing Powershell window (To try get the select function to pause the window).
None of which have worked.
The code in question is:
PowerShell -NoProfile -ExecutionPolicy Bypass -Command "& {Start-Process PowerShell -ArgumentList '-NoProfile -ExecutionPolicy Bypass -File """"%PowerShellScriptPath%"""" """"%server%"""" """"%username%"""" """"%password%""""' -Verb RunAs}";
Outside of this code no changes have been made to the system, the four speech marks were marked as required to pass through parameters and can be found under the blog post link above at the bottom just before the comments.
There is a high chance i'm using this incorrectly, I am a novice to batch and even newer to powershell. The batch scripts are being made as internal as possible, they need to be able to be used by a base install of Windows. They will eventually be migrated onto versions of Windows Server 2008 and up.
Is there anything that needs to be done with command prompt to allow it to run Powershell code?
Is the powershell code correct for the purpose i'm intending to use it for?
Is there any way, besides the ones listed, to view error, log information or pause the powershell window when run from a batch script?
Any input would be really appreciated!
Edit:
-NoExit variations:
Parent Call
PowerShell **-NoExit** -NoProfile -ExecutionPolicy Bypass -Command "& {Start-Process PowerShell -ArgumentList '-NoProfile -ExecutionPolicy Bypass -File """"%PowerShellScriptPath%"""" """"%server%"""" """"%username%"""" """"%password%""""' -Verb RunAs}";
Nested call
PowerShell -NoProfile -ExecutionPolicy Bypass -Command "& {Start-Process PowerShell -ArgumentList '**-NoExit** -NoProfile -ExecutionPolicy Bypass -File """"%PowerShellScriptPath%"""" """"%server%"""" """"%username%"""" """"%password%""""' -Verb RunAs}";
Parent and Nested
PowerShell **-NoExit** -NoProfile -ExecutionPolicy Bypass -Command "& {Start-Process PowerShell -ArgumentList '**-NoExit** -NoProfile -ExecutionPolicy Bypass -File """"%PowerShellScriptPath%"""" """"%server%"""" """"%username%"""" """"%password%""""' -Verb RunAs}";
Variables set inside batch script as:
SET server=%~1
To remove the quotation marks I have also tried using:
SET server=%1
SET server=%server:"=%

Keep batch script running after launching powershell within

I am using a batch script to automate a lot of tasks I have to run on a computer.
In the batch file I have a menu making you choose between each task separately or do everything.
When I choose to do everything, after launching the first .ps1 it just kills my cmd window.
I found some way to keep the window open but the script doesn't continue...
Also I created a "master file" to call all the ".ps1" and tried those cmds: call, /wait
The call feature works and they all start. So I don't understand why they would do the same in my script.
The cmd lines bellow are not bellow each other in my script because I want to be able to call them separately.
Part of the script I would like to run properly:
echo Windows Layout
start /wait PowerShell.exe -Command "& {Start-Process PowerShell.exe -ArgumentList '-ExecutionPolicy Bypass -File ""%~dp0Customisation\Export_Import_Layout.ps1""' -Verb RunAs}"
echo Remove Unwanted Apps
start /wait PowerShell.exe -Command "& {Start-Process PowerShell.exe -ArgumentList '-ExecutionPolicy Bypass -File ""%~dp0Clean\RemoveAppx.ps1""' -Verb RunAs}"
wmic product where name="WinZip 22.5" call uninstall
ping -n 6 localhost >nul
Taskkill /IM /F "MicrosoftEdge.exe"
Taskkill /IM /F "MicrosoftEdgeCP.exe"
Taskkill /IM /F "MicrosoftEdgeSH.exe"
%~dp0Clean\MCPR.exe
The master.bat looks like this :
call PowerShell.exe -Command "& {Start-Process PowerShell.exe -ArgumentList '-ExecutionPolicy Bypass -File ""%~dp0InstallChocoAndApps.ps1""' -Verb RunAs}"
call PowerShell.exe -Command "& {Start-Process PowerShell.exe -ArgumentList '-ExecutionPolicy Bypass -File ""%~dp0Clean\RemoveAppx.ps1""' -Verb RunAs}"
Any hint would be appriciated.
Please keep in mind I am not a script specialist.
Thanks
Ben
Managed to solve my issue by adding start "" /wait instead of start /wait

Executing file from Admin CMD via CLI

I am trying to execute a file via the CMD with Administrative privileges.
How can I open a cmd via command line with Administrative privileges.
I have to execute a script within a script.
powershell -ExecutionPolicy ByPass -noprofile -command "&{ start-process powershell -ArgumentList '-noprofile -File C:\scripts\install_ims.ps1' -verb RunAs}"
I have tried this in a bat file, but it doesn't work when executed within the script.
This should work fine for your purposes.
powershell -Command "Start-Process <filename> -Verb RunAs"
This is copy-pasted from some Batch files that I finally added to GitHub in the last few days if you have questions, that's probably the best place to go. https://github.com/Benny121221/Batch-BS

Powershell Unable to send Email through Batch file or Cmd prompt or Task Scheduler

I've been stuck at this same issue from past 5 days. The script has no issues and is sending email without any issues when executed from ISE directly.
#ECHO OFF C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -noprofile -executionpolicy RemoteSigned -file D:\powershell\Fedex_Meter_Check1.ps1 PAUSE
Also tried
C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -noprofile -executionpolicy RemoteSigned -file D:\powershell\Fedex_Meter_Check1.ps1
There are no errors when executed from powershell.exe or cmd but no email. Please assist me on this.
Send-MailMessage -from 'Trax_FedEx ittraxsupport#xpo.com' -to 'Rahul `Rahul.Lalwani#xpo.com'<#'TRAX ittraxsupport#xpo.com' #> -subject 'Daily Rates `Check for FedEx Meters.' -body 'Perfect! All FedEx Meters Have Good Rates!'` `-Encoding Unicode -port 25 -smtpserver mailhost.cnf.com
I have had numerous issues running Powershell from BAT files in the past. One thing that I remember is that there are weird issues dealing with starting directory. From the command line, try changing the directory to the same directory as the powershell script, and then run it from there. I have this in a BAT file that works as long as the .bat and .ps1 share the same name.
#ECHO OFF
SET ThisScriptsDirectory=%~dpn0
PowerShell -NoProfile -ExecutionPolicy Bypass -Command "& '%~dpn0'"
PAUSE
Another solution I found in another old script is to run powershell.exe from the .bat or command line and give the .ps1 as a command to powershell instead of as a file.
powershell.exe -command "& {C:\filepath.ps1}"
I found a solution. Just adding Start-Sleep -Seconds 1 as the last line and it worked for me.

Setting wallpaper: PowerShell works but only temporarily

I have some trouble with a PowerShell and Batch file. When I run a batch file in which a Powershell script is called, it runs normally. After a logoff and logon it´s as if nothing happened.
This is the batch file (SetWallpaper.bat):
#ECHO OFF
PowerShell.exe -NoProfile -Command "& {Start-Process PowerShell.exe -ArgumentList '-ExecutionPolicy Bypass -File ""%~dpn0.ps1""' -Verb RunAs}"
PAUSE
And here is my Powershell code (SetWallpaper.ps1):
Set-ItemProperty -path 'HKCU:\Control Panel\Desktop\' -name wallpaper -value "<root>\Users\temp\Tree_Updown.jpg"
rundll32.exe user32.dll, UpdatePerUserSystemParameters
As I said, it works, but after a logoff and on, the wallpaper is the default Windows picture.
The curiosity is, that when I launch just the Powershell code alone, without a batch, it works perfect.
I searched the web for some other alternatives, like launching the file via VBS, and it didn´t work.
VBS-code(LaunchSetWallpaper.vbs):
command = "powershell.exe -nologo -command <root>\Users\temp\SetWallpaper.ps1"
set shell = CreateObject("WScript.Shell")
shell.Run command,0
for some reason unknown, it doesn't do anything.
At this point, I don´t know what else to do. Hope someone can give me some advice.
Thanks.
Martin Leiva

Resources