Batch file to run PowerShell Script Only Works Once - powershell

So I'm trying to create a batch file to run a PowerShell script while bypassing the execution policy. Oddly, it worked a single time, but without me editing anything, it will not run again. I've created other files thinking maybe my file somehow got corrupted, but nothing... Any chance someone sees anything blatantly wrong with this?
#echo off
Powershell.exe -Command "& {Start-Process Powershell.exe -ArgumentList '-ExecutionPolicy Bypass -File %~dp0File.ps1' -Verb RunAs}"
PAUSE
The *.ps1 file works by itself if I click through the prompts. Also, if I manually set the execution policy in PowerShell to Bypass, this batch file still does not work. This is not a process I usually need to take, so I'm curious if anyone sees anything wrong with how this is written?

If this is just to run your script, what I personally do is create a shortcut of the script and then modify the Target of the shortcut:
Target: Powershell.exe -ExecutionPolicy Bypass -File "C:\scriptpath\script.ps1"
If you want your script to be executed as Administrator you can add this to the top of the main script:
$myInvoke="-file `"$($MyInvocation.ScriptName)`""
Start-Process "$PSHome\powershell.exe" -Verb Runas -ArgumentList $myInvoke -EA 'Stop'
If the shortcut will always be in the same folder as your script you can also leave Start In blank and change the path for Powershell.exe -ExecutionPolicy Bypass -File ".\script.ps1" by doing so if you copy the entire folder to a different location, the shortcut will still work.

Related

Running a powershell script as administrator and minimized

So I have set up a task on task scheduler to run a .bat file that runs a powershell script as admin which sets the DNS settings. I figured out how to make the .bat file run minimised, but the powershell window still pops up. Here is the script for the .bat file called "SetDNS". The powershell script's name is "DNS.ps1".
#ECHO OFF
SET ThisScriptsDirectory=%~dp0
SET PowerShellScriptPath=%ThisScriptsDirectory%DNS.ps1
PowerShell -NoProfile -ExecutionPolicy Bypass -Command "& {Start-Process PowerShell -ArgumentList '-NoProfile -ExecutionPolicy Bypass -File ""%C:\Users\Test\Downloads\DNS.ps1%""' -Verb RunAs}";
I want to change it so that the powershell script does not flash open while it runs. Is there something that I could add to the above code to make it run minimized? I tried to add "start /min" to the above code but it did not work. Help is appreciated.

Run powershell command as admin with a batch variable

I currently have a problem where there is a process that gets stuck in task manager. I'm tired of going into the task manager and ending the random amount of tasks for my users. I would love to simplify the script that I have set up to not require placing the variable in a text file.
This is what I have set up now:
set curuser=Domain\%username%
powershell -noprofile -executionpolicy Bypass -command " '%curuser%' | Out-File -filepath C:\software\lynctemp.txt"
PowerShell -NoProfile -ExecutionPolicy Bypass -Command "& {Start-Process PowerShell -ArgumentList '-NoProfile -ExecutionPolicy Bypass -File ""powershellscript.ps1""' -Verb RunAs}"
pause
del C:\software\lynctemp.txt
powershell -executionpolicy Bypass -command "start-process -filepath 'C:\Program Files (x86)\Microsoft Lync\communicator.exe'"
The powershell script that gets called is literaly one command but it requires the current user variable. I couldn't for the life of me figure out how to get the Run As switch to work in just calling the powershell command. Instead I made a text file to hold the variable and then I delete it after its done being used. the only problem is that I would love to just pass the %curuser% variable right into the powershell call for example:
powershell -noprofile -executionpolicy Bypass -command "get-process -includeUsername | Where-Object {$_.Username -eq %curuser% -and $_.processname -eq "communicator"} | Stop-Process -force" -verb runas
The reason I want to do that, is because if this gets ran twice on the same host, the current user wont be the current user and its set for failure.
I was also looking at the taskkill.exe but I need to make sure it doesn't just end a random task because the users are using a shared rds host. so if I end task it needs to be for that user. If anyone has any ideas on better way of fixing this bug with Microsoft Lync 2010, Please let me know. im just setting up a bandaid for when it opens 50 communicator processes which makes the program unusable.
Hi I ended up finding a different solution after digging into the filter for taskkill.exe
set curuser=Domain\%username%
taskkill.exe /f /fi "USERNAME eq %curuser%" /im communicator.exe
ping pleasesleep.com
powershell -executionpolicy Bypass -command "start-process -filepath 'C:\Program Files (x86)\Microsoft Lync\communicator.exe'"
I've tested it on my local machine and am going to test tomorrow when the tickets come in.
I still am curious about my initial question though:
If I did want to pass paramaters to a powershell script that is being run as admin, How would I do so from a batch file?

Powershell / cmd - Redirecting embedded script's output streams to file

I have a situation in which a cmd script must launch a powershell script (install.ps1), elevating to admin if the cmd is not already. The line that launches the powershell looks like this:
powershell -WindowStyle Hidden "Start-Process powershell \"-NoP -Exec Bypass -File `\"%~dp0install.ps1`\" %args%\" -Verb runAs -Wait"
Or this also works:
powershell -WindowStyle Hidden "Start-Process powershell \"-NoP -Exec Bypass invoke-command { %~dp0install.ps1 %args% } \" -Verb runAs -Wait"
I would like to redirect the output from the install.ps1 script to a file for logging purposes, but having trouble doing this. Something like the following will generate the log.txt file, but output will still be shown in the console and the resulting log.txt file will be empty:
powershell -WindowStyle Hidden "Start-Process powershell \"-NoP -Exec Bypass invoke-command { %~dp0install.ps1 %args% } \" *> log.txt -Verb runAs -Wait"
Moving the *> log.txt portion to inside the Start-Process block (just after the invoke-command block), which I thought would be the key, seems to not even run the script at all (or it's flashing an error in the console too quick to see because it closes immediately).
Is it possible to achieve this logging behavior when the data I want is buried in a couple layers of powershell, executed by a cmd file?
We've technically gotten this to work by creating a powershell wrapper script that is called/elevated by the cmd, then within the wrapper calling the install.ps1 script and assigning logging in that call. Unfortunately the extra script layer causes a bunch of other tricky / more critical problems regarding getting arguments passed at the command line all the way through to the actual install script correctly, so we're really trying to avoid that route.
EDIT
Thanks to #mklement0 for the pointer that the redirect needed to be escaped, which was my problem. Follow-up question - The following command works great to log to file, but is there any way to get this same behavior using -File rather than -Command when invoking the PS script ("-Command %~dp0pg.ps1")?
powershell -Command "Start-Process -WindowStyle Hidden -Verb RunAs -Wait powershell \"-NoProfile -ExecutionPolicy Bypass -Command %~dp0pg.ps1 *^> %CD%\log.txt\""
Moving the *>log.txt redirection into the Invoke-Command block works in principle, but your problem is that in Windows PowerShell (as opposed to PowerShell Core) a process invoked with elevation (as admin), via -Verb RunAs, defaults to C:\Windows\System32 as the working directory, not the caller's working dir.
Aside from the fact that you probably didn't mean to create a log file in C:\Windows\System32, the command will fail, because writing to that location requires the caller to already be elevated.
The simplest solution is to make *> redirect to a file specified with a full path instead:
powershell -Command "Start-Process -WindowStyle Hidden -Verb RunAs -Wait powershell \"-NoProfile -ExecutionPolicy Bypass -Command %~dp0pg.ps1 *^> %CD%\log.txt\""
Note:
There is no need for Invoke-Command - just invoke the *.ps1 file directly; however, I've added -Command to make it more obvious that the remainder of the command line is to be interpreted as PowerShell code (not a script-file path with arguments only).
Because > is a cmd.exe metacharacter, it must be escaped as ^> in order to be passed through to PowerShell - perhaps surprisingly, cmd.exe considers the > to be unquoted, because it doesn't recognize the \" sequences as embedded double quotes - only PowerShell does.
As in your original command, the assumption is that neither %~dp0 - the batch file's folder dir. path - nor %CD% - the caller's working dir. path - contain spaces or other special chars. that would need additional quoting / escaping.

Run PowerShell script with admin privileges and bypass execution policy

I'm having trouble with PowerShell script. I'm getting an error when running it
cannot be loaded because running scripts is disabled on this system.
For more information, see about_Execution_Policies at
https:/go.microsoft.com/fwlink/?LinkID=135170.
Script is not being run as admin.
if (-not ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")) {
$arguments = "& '" + $MyInvocation.MyCommand.Definition + "'"
Start-Process powershell -Verb runAs -ArgumentList $arguments
break
}
Set-ExecutionPolicy Bypass -Scope Process -Force
# Rest code
Seems like the line with execution policy is not being executed.
The command
Set-ExecutionPolicy Unrestricted
didn't help as well.
The ExecutionPolicy is keeping the script from running at all. You will have to call the .ps1 with parameters that deal with that up front.
Powershell.exe -ExecutionPolicy Bypass -File yourscript.ps1
I have struggled with this. I have found that if I type in the double quotes in the task schedule action tab, it will work. If you copy and paste, the double quote is different and does not work. If you type a quote in Word for example, it looks like this “, if you type it in Task Scheduler it looks like this ". Same exact key on the keyboard, but apparently different ascii code and it does not work when you copy and paste.

Powershell Start-Process works but not from .ps1 script

If I paste this into Powershell blue window it runs fine and launches the program
Start-Process “C:\Program Files (x86)\Engine Pro\engine.exe” -ArgumentList "#21#”;
but if I try to run the same command in a script, run.ps1 script, that launches from a scheduled task in Windows, it does nothing
PowerShell.exe -windowstyle hidden -NoProfile -ExecutionPolicy Bypass C:\run.ps1
Does it have something to do with the -ExecutionPolicy Bypass? Do I have to have an Execution policy in the script as well? I really don't know what that is. I know what -windowstyle hidden is but -NoProfile -ExecutionPolicy Bypass I'm not sure why that is there, just found it on another page, but it's all working except for the program launching from within the script.
Thank you.
& Start-Process "C:\Program Files (x86)\Engine Pro\engine.exe" -ArgumentList "#21#";