Create new process or use Start cmdlet in Powershell - powershell

I was messing around with a script that I found on the internet that will check to see if you are running the current Powershell console under the Admin role and, if not, start a new instance of Powershell and close the former window.
The part that checks it isn't really the issue, I just have a question on how it starts a new instance of Powershell.
This is how it is performed in the script:
$newProcess = New-Object System.Diagnostics.ProcessStartInfo "Powershell";
$newProcess.Arguments = "& '" + $MyInvocation.MyCommand.Name + "'"
$newProcess.Verb = "runas";
[System.Diagnostics.Process]::Start($newProcess);
Exit;
This is a rather well-known and regularly used script (empirically, it is scattered all over the web in myriad websites).
As most Powershell-savvy folks know, you can bring up Powershell and have it run as Administrator from the command line (within a Run prompt, Command shell, & Powershell) by typing:
Start Powershell -ArgumentList "& '$scriptpath'" -Verb runas
And anyone that is familiar with scripting can see that these will do the exact same thing--they even seem to resemble each other!
Between these two ways of starting a new instance of Powershell and running a called script, what are the differences? Which is recommended and which is not? Is one more correct (appropriate) than the other?
As I am self-taught and I generally learn as I go, best practices, advice, and what is deprecated\superseded is often overlooked.
I don't really have a background in the .NET framework or C#, so, if the answer is obvious from that standpoint, you'll have to forgive me.
Thanks.

Start is an alias for Start-Process, which is basically a wrapper around [System.Diagnostics.Process]::Start (it actually returns a System.Diagnostics.Process object). You can use either of them, but the former is more PoSh since its syntax follows PowerShell conventions.
See also this comprehensive Technet article for an overview of ways to run executables from PowerShell.

Related

Do PowerShell ISE scripts produce system calls altering the entire OS down to the kernel?

I'm a complete rookie to programming. I will say so much off the bat: please go easy on me. I simply want to know what happens on a system-wide level when I run a script through the PowerShell ISE program. If I run something in an IDE, I have always assumed that no system calls are made, meaning the script isn't communicating with the kernel or making actual changes to the OS. To the contrary, the script is simply being run in a sandboxed environment, as a test run for lack of better terms. I use the term sandboxed loosely here.
If I am on the mark here regarding how an IDE works, does PowerShell also work the same way. If I am incorrect overall with all of my observations, please correct me. I'm just a tad bit beyond the phase of a script kiddie. I can write simple Bash scripts and execute PowerShell commands but I am miles behind the talent of a developer or full-time programmer. Looking for an answer from a veteran to a rookie here.
The PowerShell ISE is called an Integrated Scripting Environment. It can be thought of as a stripped down Visual Studio or maybe instead an enlightened Notepad with a paired PowerShell console.
In any case, and maybe someone will chime in with the true history of the ISE here, the PowerShell console is just as effective and powerful as the Linux Bash Shell, or the Windows Command Prompt.
Commands you run in PowerShell use underlying Windows APIs or dotnet namespaces which can absolutely change the system.
For instance, you can start and stop services or even disable them, if you've got the permissions and are running as an administrator. That's definitely changing the underlying system.
Set-Service -Name Spooler -StartupType Disabled
You can also change registry keys you definitely should not be touching.
#Disable Windows Update
Set-ItemProperty -Path HKLM:\SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate -Name AU -Type DWord -Value "NoAutoUpdate"
Having permission to do these things depeneds on what your account can do. If you're running as a standard Windows user without admin rights, these calls will fail.
If you run the ISE or PowerShell without 'Run As Administrator', these calls will fail.
However, if you are an admin, and run PowerShell or the ISE as an Admin, you have effectively taken both safeties off and can now freely ventilate your foot.
Same goes for if you're running with a powerful Active Directory or Azure account. Only use those credentials when you need them, or your inevitable accidents will be truly remarkable, swift and terrible.

Powershell - How to use Start-Process to call file from share/pass args in single line

To preface this, I am self teaching and brand new to scripting in general, let alone powershell.
After a cumulative 12 hours, my Google fu has run out.
I had a series of programs tailored to different models of computer we support that ran a staged series of installers from a fileshare. The program would check to see if the tech deploying the software was running it as admin, if not, it used a Start-Process line to elevate and run again.
It worked flawlessly, but we wanted to see if we could remove the need for the tech to enter r to run the scripts from the share.
In trying to figure out how to add -executionpolicy bypass to the arg list for Start-Process, I've hit a wall.
It now errors on trying to call to the fileshare to retrieve the parent script, before getting to the point where I can troubleshoot the bypass can of worms.
Below is my rough framework, remember I'm self taught by googling and using tutorials point.
$principal = New-Object Security.Principal.WindowsPrincipal([Security.Principal.WindowsIdentity]::GetCurrent())
if($principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator))
{
#usually I have a get-childitem | foreach-object loop here that runs the files from the folder one by one in a specific order,
#it also checks to see if msiexec is running or not before trying to load and install files using a if-else>do-while combo
}
else
{
Start-Process -FilePath "powershell" -ArgumentList "$('-File "\\server\dir\foo".ps1')$($MyInvocation.MyCommand.Name)$('""')" -Verb runAs
}#this calls to a script that is a 1:1 copy of the code in the if{} block
This returns an error from the -File parameter that says it can't call the file because it doesn't exist.
What am I doing wrong?
How do I pass -executionpolicy bypass as an additional arg without breaking it further?
Is there a better way to do this?
Is there a neater way to automate this?
Please help me geniuses of StackOverflow before I start gnawing on my keyboard.

Powershell not running on cmd

I'm trying to run the following command but when I do it the CMD windows closes without the command being executed
the command is
cmd.exe /c powershell.exe (New-Object System.Net.WebClient).DownloadFile(https://site,'%temp%\file.txt');Start-Process '%temp%\file.txt'
You don't need cmd here at all¹. You can spawn a process without a shell just as well. Furthermore, it's usually a good idea to quote arguments to avoid surprises with argument parsing (cmd for example has its own meaning for parentheses, which may well interfere here).
powershell -Command "(New-Object System.Net.WebClient).DownloadFile('https://site',$Env:Temp + '\file.txt');Invoke-Item $Env:Temp\file.txt"
I've also added quotes around the URL you want to download, since that wouldn't otherwise work, either. And since cmd is no longer around, environment variables can be expanded by PowerShell as well, with a different syntax.
Start-Process also is for starting processes and Invoke-Item is closer to what you actually want, although I'm sure with ShellExecute behavior, Start-Process could launch Notepad with a text file as well if desired.
¹ If in doubt, it's always a good idea to reduce the number of parts, processes and different wrapped concepts needed. Same reason why you don't use Invoke-Expression in PowerShell to run other programs: Unnecessary, and complicates everything just further by introducing another layer of parsing and interpretation.

Powershell closes on executing exe

I am trying to run and .exe in C:programfiles(x86)
I can launch it directly from the filepath. If I run in powershell just closes. No feedback.
Running powershell 5.1.17134 Rev 590
Start-Process -FilePath "C:\Program Files (x86)\App\App.exe"
I tried running powershell -NoExit and then start-process but it returns without any feedback.
If I run it on same machine in Powershell 6.1.0 preview - it runs fine. No issue. How can I track down whats causing this to 1) not run 2)close powershell.
Thanks,
This answer makes a general point. It doesn't solve your problem, if using Start-Process truly crashes the calling PowerShell window.
If C:\Program Files (x86)\App\App.exe is a console application that you want to run in the current console window, do not use Start-Process to invoke it.
Instead, invoke it directly.
Given that its path contains spaces and special characters (( and )), you need to:
quote it
invoke it with &, PowerShell's call operator.
PS> & 'C:\Program Files (x86)\App\App.exe'
Note:
The use of & with a command specified in a quoted string and/or via a variable reference is a syntactic necessity, given that PowerShell has two distinct parsing modes - see about_Parsing.
Invoking a console application directly:
ensures its synchronous execution
That is, control isn't returned to the caller until the application has terminated.
connects its standard output streams - stdout and stderr - to the equivalent PowerShell streams.
That is, you can capture or redirect the application's success output and/or error output, as needed.
You have an interactive shell. You spawn this new process - then your shell closes?
Clearly it is terminating its parent process, and clearly pwsh is doing something different.
I don't think this is truly a powershell question, it's a windows internals one. The suite of tools to use is Sysinternals. The first thing I'd try - and I'd do this on cmd, powershell and pwsh to establish a basis for comparison - is run Process Monitor with a filter on your app's path. Something in its last actions may prove illuminating. Process Explorer may also be useful.
Are you in a corporate environment? I have agents on my machine that kill processes based on heuristics. That can do things like this.
There may be a workaround based on how you invoke the app;
try mklement0's suggestion
try invoking through WMI; this does not provide your powershell process as a parent process: Invoke-WmiMethod -Class win32_process -Name create -ArgumentList "PathToApp.exe"
try invoking via cmd.exe if you are constrained by what's on your target machines
I do think this is off-topic, though.

Powershell to EXE tool Advice

So here's the deal. Because of a number of... let's just say not PowerShell smart people who will be using an incredibly complex application that I just finished, I need the ability to package it in an exe wrapper.
This shouldn't be that hard
I was able to successfully use PS2EXE, except for some reason with AD, it throws out a whooooole bunch of AD text that I can't get rid of. Tried to fix that for a few days before getting frustrated and moving on.
Then, I discovered PowerGUI. I can't say that I like it, at all. However, its compiler was exactly what I was looking for! Except for the fact that Exchange 2010 snap-ins are not compatible with .NET 4.5 through this application.
I want to make it very clear that my script works perfectly on multiple different computers, but as soon as I use any of these tools, everything breaks.
An exe is the best thing that I can think of to simplify the interface, and keep the Technically Intellectually Stunted from breaking everything, or running to me with every little error because they somehow got into the code and typed something and saved it, and now nothing works and it's the end of the world and they have no idea what happened.
If you guys know of any tools to wrap this up into an exe, or have any other ideas on how to help, I would really appreciate anything you guys can give me.
You have never failed me in the past!
From my point of view if you really want an EXE file you should write a .NET application, it's not so hard to embed PowerShell CmdLets.
In order to avoid end user modifying your code I know two solutions :
First : set execution policy to AllSigned on the user computer and sign the scripts you deploy. You can manage to use our own certificates (not expensive at all) or public certificates (more expensive). One of the drawback of this solution is that it does not prevent users from seeing the code. Another big drawback is that a PKI and sign code infrastructure is a lot of wast time.
Second : for non interactive scripts (be carefull it's a kind of makeshift job) :
Create a new user account
Only allow access to the script file for the new account.
Set up a task in the Windows scheduler to run that script file with PowerShell under that specific account. The permissions for the scheduled tasks allow read and execute access to the user(s). Then set the task to "disabled".
Whenever the script file needs to be run, the corresponding task is manually started by the user.
Using this solution will also allow you to remote execute your script.
When I had a similar deployment problem - 1) user's didn't know powershell 2) I didn't want them to have to understand things like execution policy, 3) how to start PS, 4) etc. I wrapped it in a batch file. I also wanted to make sure that experienced PS users still had the capabilities of PS, so the batch file determined if it was running under PS or not and ran in the current PS session if applicable. I was never too worried that users would mess with the script - they were happy if it "just worked". So whether users liked Explorer, CMD.EXE, or PS, they all were accommodated.
The batch file I wrote first runs a bit of powershell code to determine if the process of the batch file is the grandchild of a powershell process. If it is then the batch file is being invoked from PS. The execution policy is also checked and if it is lenient enough then Wscript.SendKeys is used to send keystrokes to PS to get the script running in the current PS session. If it isn't then it starts a new PS session using -ExecutionPolicy parameter and passes the script as a command line argument (-Command).
This bit of powershell code communicates back to the .CMD file using a return code. Sorry it's cryptic, but the length of command line parameters is limited. Here's the code:
set scr= $mp=[diagnostics.process]::getcurrentprocess().id
set scr=%scr%; $pp=([wmi]\"win32_process.handle='$mp'\").parentprocessid
set scr=%scr%; $gp=([wmi]\"win32_process.handle='$pp'\").parentprocessid
set scr=%scr%; $ep=[int][microsoft.powershell.executionpolicy](get-executionpolicy)
set scr=%scr%; try {$pnp=1-[int](([wmi]\"win32_process.handle='$gp'\").Name -eq \"powershell.exe\")
set scr=%scr%; } catch {$pnp=1}
set scr=%scr%; $ev = (8 * $pnp + $ep) -band 0xB; %wo% pp: $pp gp: $gp ev: $ev; if ($ev -le 1) {
set scr=%scr% %wo% Launching within existing powershell session...`n;
set scr=%scr% $w=new-object -com wscript.shell;$null=$w.appactivate($gp);
set scr=%scr%; $w.sendkeys(\"^&{{}`$st =cat "%me%";`$sc=`$st -join [char]10 -split 'rem PS script';
set scr=%scr% `$script:myArgs = `\" %*`\";`$sb=[scriptblock]::create{(} `$sc[3]{)};. `$sb{}}~\")
set scr=%scr%; }
set scr=%scr%; exit $ev
powershell -noprofile -Command %scr%
%wo% is to allow debugging this "checker script". If debugging is on the %wo% is set to write-host. Otherwise it is set to define a "null" function and then invoke the null function. The null doesn't do anything so the message that is the argument to the function is not output.
Note the escaping when invoking SendKeys. ^ is the CMD.EXE escape character and SendKeys has it's own escape mechanism, as does PS.
If run from PS you end up in a PS session thanks to SendKeys. Otherwise the batch file does this:
set scr= ren function:prompt prompto
set scr=%scr%; function prompt{ 'myApp: '+(prompto)}
set scr=%scr%; $st= (cat %me%) -join \"`n\";
set scr=%scr%; $sx=($st -split 'rem PS script')
set scr=%scr%; $sc=$sx[3]
set scr=%scr%; %wo% myArgs: $myArgs script length: $sc.length
set scr=%scr%; ^&{$script:myArgs=\"%*\"; iex $sc}
title MyApp
rem Change the number of lines on the console if currently set to 25
for /f "tokens=2" %%i in ('mode con^|findstr Lines:') do if %%i LEQ 25 (mode con lines=50&color 5F)
powershell -noexit -noprofile -command "%scr%"
This "helper script" also can't be too long. So the helper script reads the original .CMD file and then splits it by using the string 'rem PS script'. That string will be in both this helper script as well as in the batch file (separating the batch file statements from PS statements). In my case the string is also in the batch file comments, so that is why the index of 3 is used.
Your PS script can define functions or a module. Your PS script can also output some introductory info to explain to users how to get started, how to get help, or whatever you want.
Rather than just using the PS command line, your PS script could create it's own interactive environment (using Read-Host for example). However I didn't want to do that because it would have prevented experienced PS users from using their knowledge about PS. For example if your script requires a username/password, an experienced PS user could use get-credential to create a credential to send to your script.