Run powershell command as admin with a batch variable - powershell

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?

Related

Batch file to run PowerShell Script Only Works Once

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.

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.

Running PowerShell script from batch file as SYSTEM

There are various posts I have seen showing how to run a PowerShell script from a batch file, however I am still not quite sure how to do this with admin rights or running under the system account. I have a batch file that needs to execute a PowerShell script and run the script as admin or the local system account WITHOUT prompting for credentials. This is running on end user machines that do not have the permissions. This is the best I have found for executing a powershell script from a batch file:
#ECHO OFF
PowerShell.exe -NoProfile -Command "& {Start-Process PowerShell.exe -ArgumentList '-NoProfile -ExecutionPolicy Bypass -File ""%~dpn0.ps1""' -Verb RunAs}"
PAUSE
But UAC will prompt with the above. Any ideas?

Powershell Requires UAC, I need help translating this function to a BAT file for PSexec

$i=0;
$pnp = pnputil -e;$matched = [regex]::matches($pnp, ".......................................Lexmark International");
$split = $matched -split (".........inf");
$replace = $split -replace " Driver package provider : Lexmark International","";
$replace1 = $replace -replace " ","`n";
write-output $replace1;
foreach ($i in $replace1){;
$pnpdel = pnputil -f -d $i;$pnpdel;
};
Reg delete "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Print\Environments\Windows x64\Drivers\Version-3\Lexmark Universal v2 XL" /f;
net stop spooler;
net start spooler;
$PrinterPath = "\\officechicprt5\111w-2w-bprn-07";
$net = new-Object -Com WScript.Network;
$net.AddWindowsPrinterConnection($PrinterPath)
I know it's not pretty, but it works every time I have tried it. In case you are curious, in our environment, Lexmark drivers corrupt frequently, which is actually a Microsoft issue. In the registry, Dependent Files is truncated, so the printer will never print, often forcing gibberish to the printer. The only way we have found to fix this is to remove the driver completely, and read our point and print driver. This script does that, but unfortunately requires UAC elevation. I have attempted a bat file to run alongside this:
#ECHO OFF
PowerShell.exe -NoProfile -Command "& {Start-Process PowerShell.exe -ArgumentList '-NoProfile -ExecutionPolicy Bypass -File ""%~dpn0.ps1""' -Verb RunAs}"
timeout /t 10
But unfortunately it leaves the user with a confused expression and a UAC prompt. Is it possible to run this somehow through PSexec in a bat file? I do not want to run this by RDP'ing into hundreds of machines (been there, done that). I would prefer a repeatable process, this issue is a pandemic here.
Thanks again
You're overcomplicating things. Don't start PowerShell to start PowerShell with parameters. Just start PowerShell directly with parameters.
powershell.exe -NoProfile -ExecutionPolicy Bypass -File ""%~dpn0.ps1"" -Verb RunAs
If you need to run the PowerShell script with elevated privileges when your users are not members of the administrators group you should rather enable PS Remoting and run it via Invoke-Command on the remote hosts:
Invoke-Command -Computer 'hostA', 'hostB', ... -ScriptBlock {
# your PowerShell code here
}

Syntax error when starting powershell from bat file

I want to start a powershell script with RunAs from a bat file. This works.
#echo
SET "InstallerFolder=\\dc01\e\script"
PowerShell -NoProfile -ExecutionPolicy Bypass -Command "& {Start-Process PowerShell -ArgumentList '-NoProfile -ExecutionPolicy Bypass -File ""%InstallerFolder%\Script.ps1""' -Verb RunAs}";
But if i add:
-RedirectStandardOutput ""%InstallerFolder%\node.txt""
It breaks.
So the line looks like this:
PowerShell -NoProfile -ExecutionPolicy Bypass -Command "& {Start-Process PowerShell -ArgumentList '-RedirectStandardOutput ""%InstallerFolder%\node.txt"" -NoProfile -ExecutionPolicy Bypass -File ""%InstallerFolder%\TSM Client Install Script.ps1""' -Verb RunAs}";
And resuslts in an powershell error which is gone so fast i can't see it.
Probably syntax?
Help much appreciated!
Thanks.
You get an error because powershell.exe does not have a -RedirectStandardOuptut parameter. (See Technet).
Also your syntax is way off (but since i dont see any reason to start powershell to start powershell again i wont bother explaining the syntax errors).
If you want to use RunAs from the cmd use it directly. For more info see Technet (again).
Also you can redirect output in Batch Files with > or >> if you want to append.