Output to New Window in PowerShell - powershell

How can I get the output of a command (i.e. get-process) to display in a new powershell window with the the -nologo and -noninteractive options. I've tried all sorts of things that don't work like:
get-process > start-process powershell.exe -nologo -noninteractive
get-process | write-output start-process powershell.exe -nologo -noninteractive
I just can't seem to get my output into a new powershell window, no matter how many ways I Google it. I need to be able to do this when selecting a certain function via my mutli-level powershell menu script.

start -FilePath powershell.exe -ArgumentList "-nologo -noninteractive -command {Get-Process}"
Will do what you asked for but I have a feeling that may not really be what you want.

If you want to output to a new window - Why do you need those options?
This command outputs anything under the command parameter to a new PS Window (sleep timer helps it stay active:
Start-process powershell.exe -ArgumentList '-command Write-Host "Explorer Process Current State" -ForegroundColor Red; gps explorer | ft ; Start-Sleep -s 10;'

Related

Powershell-Command to download a file with admin rights

I try do download a file via a powershell command. The command I use is simple:
Start-BitsTransfer -Source 'https://download.com/file.zip' -Destination 'E:\test\file.zip'
I can run the command in PS succesfully. But now I want to run it with elevated rights. So I gooogled and found this solution:
There it says the command should be:
Start-Process powershell.exe -Verb Runas -ArgumentList "-Command & {get-process}"
So I tried adjusting it for my use case:
Start-Process powershell.exe -Verb Runas -ArgumentList "-Command & {Start-BitsTransfer -Source 'https://download.com/file.zip' -Destination 'E:\test\file.zip'}"
But all is does is open a new PS-Window and closing it right after. Where is my mistake?
You can change to this
Start-Process powershell.exe -Verb Runas -ArgumentList "& {Start-BitsTransfer -Source 'https://download.com/file.zip' -Destination 'E:\test\file.zip'}"
Note the window will close after the execution completes. If you would like to see the output/errors (such as what would be shown in your non working example) just add another command to pause.
Start-Process powershell.exe -Verb Runas -ArgumentList "& {Start-BitsTransfer -Source 'https://download.com/file.zip' -Destination 'E:\test\file.zip';pause}"
& is used to invoke a command. It's useful for executing strings or scriptblocks. It runs in a child runspace.
& 'Get-Host'
& 'Write-Host' Hello -Fore Green
& {Write-Host Goodbye -Fore Cyan}
; is used to separate different commands on the same line.
& {$name = 'Doug';Write-Host Hello $name}
You can also use a period to invoke a scriptblock in the current runspace. In the previous command the $name variable would be empty in the callers scope where the following command would leave the variable defined.
& {$name = 'Doug';Write-Host Hello $name}
$name # empty as it all happens in the child scope
vs
. {$name = 'Doug';Write-Host Hello $name}
$name # populated because it's brought into the caller's scope

How do I call an elevated PowerShell from Windows command prompt to execute commands and a PowerShell script file?

The following script works fine in Powershell:
Set-ExecutionPolicy Bypass -Scope Process -Force; Invoke-Webrequest
'https://blah.blob.core.windows.net/laps/AutoAutoPilot.ps1' -OutFile
C:\script.ps1; C:\script.ps1
I'm trying to convert it so that it runs as a CMD/BAT file. I simply need to double click to run it. I need the CMD/BAT file to run Powershell as administrator and from there, it will run the script from above. Here's what I have. It'll just quit straight away without doing anything.
powershell -ExecutionPolicy Bypass -c Start-Process -Verb RunAs -Wait
powershell.exe '-ExecutionPolicy Bypass -Noexit -c Set-Location
"\"\\\"%CD%\\\"\""; -c "& Invoke-Webrequest
\"https://blah.blob.core.windows.net/laps/AutoAutoPilot.ps1\"
-OutFile C:\script.ps1; C:\script.ps1" '
Update:
I got it working now. The full output looks like this:
powershell -Command "& ({Start-Process powershell -Verb RunAs -ArgumentList '-ExecutionPolicy Bypass -NoExit -Command Invoke-WebRequest -Uri https://blah.blob.core.windows.net/laps/AutoAutoPilot.ps1 -OutFile C:\script.ps1; C:\script.ps1'})"
If you use the -NoExit parameter when starting powershell.exe PowerShell should not close after the script has finished running. Afterwards if you do not see errors, you can look at the $error variable, to see any errors which occurred when running your script.
You are trying to run your PowerShell code, using PowerShell.exe from command prompt, so you should be able to use the same code as you did before, when you were running your code directly in PowerShell before.
To my understanding you want to run powershell code in a batch-file.well Depending upon your preference there are multiple solutions to this problem(well i haven't checked any of them):
Solution:1
make a batch file and give your powershell script to it as a parameter.
Without Admin access:
#ECHO OFF
PowerShell.exe -NoProfile -ExecutionPolicy Bypass -Command "& '%~dpn0.ps1'"
PAUSE
With Admin access:
#ECHO OFF
PowerShell.exe -NoProfile -Command "& {Start-Process PowerShell.exe -ArgumentList '-NoProfile -ExecutionPolicy Bypass -File ""%~dpn0.ps1""' -Verb RunAs}"
PAUSE
Solution:2
If you don't want an external .ps1 file,then you can try this.just save it as something.bat
powershell -command if ($true)^
Set-ExecutionPolicy Bypass -Scope Process -Force; Invoke-Webrequest 'https://blah.blob.core.windows.net/laps/AutoAutoPilot.ps1' -OutFile C:\script.ps1; C:\script.ps1^
This should do the trick:
powershell -Command "& {Start-Process powershell -Verb RunAs -ArgumentList '-ExecutionPolicy Bypass -NoExit -Command Set-Location -Path C:\whatever\working\directory\you\need; Invoke-WebRequest -Uri https://blah.blob.core.windows.net/laps/AutoAutoPilot.ps1 -OutFile C:\script.ps1; C:\script.ps1'}"
Explanation:
When executing commands in PowerShell using the -Command argument, ExecutionPolicies do not apply as your are executing a single command and not a script. Even the execution of a scriptblock consisting of multiple commands counts as the execution of a single command. That's why you can directly call PowerShell from the command prompt like this (without anything else):
powershell -Command ...
-Command expects - to read from stdin or a scriptblock (read more). Scriptblocks have to be enclosed in curly braces ({...}). If you pass a scriptblock from the command prompt to PowerShell, you also have to add the call operator &:
powershell -Command "& {...}"
As you need an elevated PowerShell, you start a new PowerShell process from the previous PowerShell with Start-Process in combination with the -Verb RunAs argument. You add all arguments that you want to pass to the elevated PowerShell to the -ArgumentList argument:
... Start-Process powershell -Verb RunAs -ArgumentList '...' ...
As you want to call a script file, you now need the corresponding ExecutionPolicy. If you don't want to change it on the system, you can bypass the ExecutionPolicy with -ExecutionPolicy Bypass as you already did. And you also add -NoExit here. To pass your desired PowerShell commands, you use the -Command argument again. This time, you don't need the call operator and you can also omit the curly braces as we are now in PowerShell and not in the command prompt anymore.
... -ExecutionPolicy Bypass -NoExit -Command Set-Location -Path C:\whatever\working\directory\you\need; Invoke-WebRequest -Uri https://blah.blob.core.windows.net/laps/AutoAutoPilot.ps1 -OutFile C:\script.ps1; C:\script.ps1 ...

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?

How to Run Long Powershell script from Windows Command Prompt (CMD)

I tried to launch a long powershell script with the name "long name here.ps1" from command prompt. But I am also trying to ensure that it runs as an administrator command in powershell. I have all execution policies in powershell set accordingly I used the ss64 set-executionpolicy command guide for powershell to get powershell working. But I am trying to use the solution from another stackoverflow question that talks about running commands as administrator. I am running a batch script that needs to execute a powershell script (.ps1) as admin, and I don't mind if the user is prompted by UAC or for the password. I am currently using the following command:
powershell.exe -command "&{ Start-Process powershell -ArgumentList '-noprofile -file "C:\long name here.ps1"' -verb RunAs}"
I found this command at https://ss64.com/ps/powershell.html at the bottom where there are details on how to run a powershell command as administrator. The problem with that code is that my powershell script 1. has arguments, and 2. has a long name. I have tried many different iterations of this command with no success, and the ones that DON'T work are listed below:
powershell.exe -command "&{ Start-Process powershell -ArgumentList '-noprofile -file C:\long` name` here.ps1' -verb RunAs}"
powershell.exe -command "&{ Start-Process powershell -ArgumentList '-noprofile -file:"C:\long name here.ps1' -verb RunAs}"
Also, I am completely lost as to how to send arguments to the actual script.
If I'm reading your question correctly - powershell wont find the file as it stops reading the path name when it encounters a blank space?
The example given here specifies that; powershell commands to be run from command prompt as an administrator should have the following syntax:
powershell.exe -noprofile -command "&{ start-process powershell -ArgumentList '-noprofile -file MyScript.ps1' -verb RunAs}"
Couple of ways to achieve what you're looking for. But the easiest method would be to escape the quotes using a ` character. So something similar to;
powershell.exe -noprofile -command "&{ start-process powershell -ArgumentList '-noprofile -file `"C:\long file name.ps1`"' -verb RunAs}"
Also might be worth checking out other answers here
Use a Freeware Third Party Utility
If a freeware third-party executable is permissible, you can use a short tool I wrote called elevate32.exe (32-bit) and elevate64.exe (64-bit) to launch powershell.exe as administrator with the -File parameter and the script arguments you want to use:
elevate64 -- powershell.exe -File "<path>\<long script name>.ps1" -Arg "<long script argument>"
You can get the tool from www.westmesatech.com (copyrighted freeware, free to use anywhere, no installation needed).
Use a WSH Script
If you can't use an external executable, you can also do this (although it does not handle quoting in as robust a manner as the elevate tool's -- parameter) using a Windows Script Host (WSH) script, elevate.js:
var args = WScript.Arguments;
if ( args.Length >= 1 ) {
var exec = args.Item(0);
var cmdLine = "";
for (var i = 1; i < WScript.Arguments.Length; i++ ) {
cmdLine += cmdLine == "" ? '"' + args.Item(i) + '"' : ' "' + args.Item(i) + '"';
}
var shellApp = new ActiveXObject("Shell.Application");
shellApp.ShellExecute(exec, cmdLine, "", "runas");
}
You can call as follows:
wscript.exe "d:\path\elevate.js" powershell.exe -File "C:\long path\script name.ps1" "long script argument"
Self-Elevate your PowerShell Script
Another option is to write a self-elevating PowerShell script. You can check for elevation in the script; if not elevated, it can launch itself elevated and run any command you need. Example:
$isElevated = ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
if ( -not $isElevated ) {
Start-Process powershell.exe "-File",('"{0}"' -f $MyInvocation.MyCommand.Path) -Verb RunAs
exit
}
& "d:\long path name\script name.ps1" "Long Argument 1" "Long Argument 2"
When you use PowerShell.exe -Command you don't need to use quotes. For example, you can run the following:
PowerShell.exe -Command Get-Service 'wuauserv'
Everything after -Command is interpreted as the command. Note also that double quotes in CMD need escaping with a backslash. Therefore:
powershell.exe -Command Start-Process PowerShell -ArgumentList '-NoProfile -File \"C:\long name here.ps1\"' -Verb RunAs
If your file has arguments:
powershell.exe -Command Start-Process PowerShell -ArgumentList '-NoProfile -File \"C:\long name here.ps1\" \"Arg1\" \"Arg2\"' -Verb RunAs

Send a command to a powershell opened with "Start-Process powershell -Verb runas"

I want to open an admin powershell and send it a command (eventually a script). Right now, it doesn't matter what command, but I've tried things like:
Start-Process powershell -Verb runas < $something
or
$something | Start-process powershell -Verb runas
just to get some text to show up in the new admin powershell window. Any ideas?
That awkward moment when you do a little more research and find what you want: this link will help anyone: how to execute set of commands in elevated mode of powershell
Essentially, add the -argument argument to your command
Start-Process powershell -verb runas -argument dir