Powershell ISE - Choose script file when open a new window - powershell

I'm trying to open a new Powershell ISE window providing my own script .ps1 file.
How can I accomplish that? Seems that the only way to open a new Powershell ISE window is with a blank script file, and not one one's may choose(i.e. start powershell_ise.exe -file "myfile.ps1" - That's not working).

Here is a few solutions:
1) Use ISE twice, the only downside is that you'll see extra untitled doc
ise; ise ".\test.ps1"
2) You can start it in admin mode (from non-admin mode), it will force to create a new ISE:
Start-Process powershell_ise -ArgumentList ".\test.ps1" -Verb RunAs
3) Run as different user
Start-Process powershell_ise -ArgumentList "-noprofile .\test.ps1" -Credential $cred
Method 2/3 only open new ISE once though (until you close it)

From inside powershell I run:
ise myfile.ps1
and it will open it.

Simply put, I don't think it's possible. I've done a quick Google and found the answer that campbell.rw posted but the same thing occurred. Similarly, I've just tried to start a new PowerShell ISE process using the following command...
Start-Process -FilePath C:\Windows\System32\WindowsPowerShell\v1.0\powershell_ise.exe -ArgumentList "-File .\testscript.ps1"
...but like you mentioned in the comments below the existing answer, instead of opening a new instance of PowerShell ISE it simply creates a new tab in the same instance with the script I specified in the 'ArgumentList' parameter.

Related

Powershell Elevated and pass a command

So I am building a script that launches an executable in the common files folder of x86 folder. The issue I am having is the script uses the (x86) as if the x86 is a command that should be run first. Does anyone have any ideas on how to prevent that?
$Pulse = "${env:CommonProgramFiles(x86)}\Pulse Secure\JamUI\JamCommand.exe"
$ImportFile = '"-importfile "C:\Program Files (x86)\MyFile.preconfig"'
Start-Process powershell -ArgumentList "-noexit", "-noprofile", "-command &{Start $Pulse, $ImportFile}" -Verb Runas
As Mathias notes, there is no strict need to launch another PowerShell instance with elevation (run as admin, -Verb RunAs), because you can directly elevate the target executable, JamCommand.exe; however, if you want to run the executable in another PowerShell session that stays open afterwards - as your use of -noexit suggests - you indeed do:
$pulse = "${env:CommonProgramFiles(x86)}\Pulse Secure\JamUI\JamCommand.exe"
$importFileArg = '-importfile "C:\Program Files (x86)\MyFile.preconfig"'
Start-Process -Verb RunAs powershell #"
-noexit -noprofile -c & "$pulse" $importFileArg
"#
Note:
This runs JamCommand.exe directly in the elevated PowerShell session, synchronously (assuming it is a console application), and the interactive session is only entered after that program exits. (Your attempt contains another Start-Process call (via alias Start), which would make a console program run in yet another console window, which auto-closes when the program exits.)
All pass-through arguments are encoded in a single (here)-string passed to the (positionally implied) -ArgumentList parameter, which allows direct control of the command line that is used to launch process, and is generally the most robust approach due to a long-standing bug in how passing arguments individually, as elements of an array is handled - see this answer.

start-process, ArgumentList issue via powershell

Trying to invoke cmd via powershell and pass on arguments that will change directory on cmd to c:\pilot
Sample code that I tried doing this via start-process:
Start-Process "C:\Users\su\AppData\Roaming\Windows\Start Menu\Programs\System Tools\Command Prompt.lnk" -ArgumentList 'C:\pilot'
so after running this, it appears to pop up a new cmd window, but doesn't change the directory to c:\pilot, is there a special format in sending arguments to cmd?
From an earlier revision of your question:
ultimately I am trying to change directory and also pass on an command for execution on the 2nd window without closing the second window.
The following opens a stay-open cmd.exe console window ("Command Prompt") in working directory C:\pilot and executes command date /t
Start-Process cmd -WorkingDirectory C:\pilot -ArgumentList '/k', 'date /t'

Run a PowerShell method from cmd and don't wait for its return

In cmd I'm trying to run Method1 which is in a PowerShell script, script1.
Method1 is a method that takes a few hours, and I simply want to fire and forget.
The following is working for me:
c:\temp> powershell
PS c:\temp> . .\script1.ps1;Method1
When I do the lines above, everything is working fine as long as I keep the CMD of PS opened. once I close the PS window, it kills Method1.
So actually I want that from cmd, in one line, to somehow make Method1 work without the dependency of the PowerShell window, maybe create a new process.. I am not really sure.
I've tried:
c:\temp> cmd /c powershell . .\script1.ps1;Method1
It is running for a few seconds, but when the cmd gets closed, then Method1 also terminates.
I also tried
c:\temp>cmd /c powershell -noexit "& { . .\script.ps1;Method1 }"
Again, once I do this, it is working. However, a PowerShell window is opened and if I close it then it terminates Method1.
From you help, I've tried:
c:\temp> cmd /c powershell start-process cmd /c powershell . .\script1.ps1;Method1
But I get an exception:
Start-Process : A positional parameter cannot be found that accepts
argument 'powershell'.
But still, I am not able to make it work.
Alternatively if you want a pure PowerShell solution (note this needs to be running as Admin):
Invoke-Command LocalHost -Scriptblock $script -InDisconnectedSession
The InDisconnectedSession switch runs it in a separate PowerShell session that will not be terminated when you close the PowerShell window. You can also use Get-PSSession and pass the session to Enter-PSSession to interact with it during or after execution. Remember in this state if you close the window it -will- kill it, so you'll want to use Exit-PSSession to keep it alive.
There is however a problem - you can't do any remoting tasks, at least not easily. This incurs the wrath of the "double hop" where you remote to one computer (your own in this case), then to another, and for security PowerShell refuses to pass any credentials to the second remoting session so it can't connect, even if you put the credentials in manually. If you do need to do remoting I recommend sticking with launching a hidden PowerShell process.
You can use PowerShell jobs for that, so just:
Start-Job -FilePath somepath
And add a method call at the end of the script, or pass in a Scriptblock like:
Start-Job -ScriptBlock {. .\path_to_ps1; Method1}
Or perhaps use the hackish:
start-process cmd -WindowStyle Hidden -ArgumentList "'/c powershell . .\script1.ps1;Method1'"
Actually, you can just launch PowerShell, without CMD, and I am not sure why I was using a cmd approach:
start-process powershell -WindowStyle Hidden -ArgumentList ". .\script1.ps1;Method1"
Easy answer ya'll; Just paste "start" command into your PS window (whether in a remote session or not) and it works fine:
Start C:\Windows\SysWOW64\WindowsPowerShell\v1.0\powershell.exe -file 'driverletter:\path\yourpowershellscript.ps1'

PowerShell: Run script from shortcut using relative path

EDIT: To future readers, in short, PowerShell scripts weren't intended to be used this way which is why there is no elegant solution.
I have the following line which runs a script as an administrator from a shortcut:
C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -noprofile
-noexit Start-Process Powershell -verb RunAs -ArgumentList "C:\Documents\WindowsPowerShell\Scripts\test.ps1"
I want to change:
"C:\Documents\WindowsPowerShell\Scripts\test.ps1"
to a relative path like:
".\test.ps1"
but I haven't figured out how I can do that. How can I run the script relative to the location of the shortcut? (The shortcut and script are in the same folder)
Here is an ugly workaround.
Shortcut.lnk file with Target: %COMSPEC% /C .\launcher.cmd (source) and Start In: %CD% (or blank).
Launcher.cmd file with contents:
Powershell -noprofile -noexit -File %CD%\PSlauncher.ps1
PSlauncher.ps1 file with contents:
Start-Process Powershell -verb RunAs -ArgumentList ($pwd.path + "\test.ps1")
Surely there is a better solution. Maybe with the -WorkingDirectory parameter of Start-Process? Or storing credentials with the Convert*-SecureString cmdlets? Count me curious.
Why do you want a shortcut?
After much trial and error, I've come up with a solution:
Create a shortcut with this (edited for your .ps1) to have scrips run as admin relative to any directory:
CMD /C PowerShell "SL -PSPath '%CD%'; $Path = (GL).Path; SL ~; Start PowerShell -Verb RunAs -Args \""SL -PSPath '"$Path"'; & '".\YourScriptHere.ps1"'"\""
You'll have to empty the shortcut's "Start in" field to have its relative path be set as the working directory.
Or, here's a script that will generate one of these shortcuts for each .ps1 in a directory (with "Start in" already cleared):
(GCI | Where-Object {$_.Extension -eq ".ps1"}).Name | ForEach-Object {
$WshShell = New-Object -ComObject WScript.Shell
$Shortcut = $WshShell.CreateShortcut((GL).Path+"\$_ Run.lnk")
$Shortcut.TargetPath = 'CMD'
$Shortcut.Arguments = "/C PowerShell `"SL -PSPath `'%CD%`'; `$Path = (GL).Path; SL ~; Start PowerShell -Verb RunAs -Args \`"`"SL -PSPath `'`"`$Path`"`'; & `'`".\$_`"`'`"\`"`""
$Shortcut.IconLocation = 'PowerShell.exe'
$Shortcut.Save()
}
If needed, add -NoExit, -ExecutionPolicy Unrestricted, etc. just after the first \".
Notes:
The reason for a second, admin instance of PowerShell launching from the first, is that launching as admin directly (by ticking a shortcut's "Run as administrator" box), for some reason ignores "Start in" and always launches in System32.
CMD is being used to launch the first instance because PowerShell currently fails to resolve paths containing square brackets, interpreting them as regex characters. This would normally be avoided using the LiteralPath parameter (aka PSPath), but here, the path is being passed behind the scenes at launch, and it's up to the developers to fix (I just filed a bug report here).
When I run a script from a shortcut, it uses the path of the actual script. You can check the current directory with pwd (present working directory). You can check (and then use) the path of the script with split-path -parent $MyInvocation.MyCommand.Definition like the answer says in What's the best way to determine the location of the current PowerShell script?.
So to answer your question, you should already be able to use relative paths. Have you tried it? If so, what was your experience?
For your script, set it to open using Powershell by default. Create a shortcut for your script and assign it a hot key by right clicking on your shortcut, selecting properties, click the shortcut tab. Move your cursor the select shortcut key and define a shortcut key. Each time you press the shortcut key your script will run
This is definitely made out to be more difficult than it is.
This issue is more likely to affect you on Windows Server. On regular Windows, you can run Set-ExecutionPolicy unrestricted and it will stay in affect on the machine, on Windows Server (at least on AWS), setting the execution policy from a powershell script only lasts for the session of the script and it closes immediately so you can't see the error.
I just successfully modded the registry on an AWS instance bypassing group policy and can simply right click powershell scripts from any directory and send a shortcut to the desktop that is runnable.

How to open Powershell Console Window from Powershell

I am writing a script to use multiple plink (PuTTY) sessions as a Windows version of clusterssh. I am stuck however because I want to open multiple Powershell windows from powershell. When I type the command for powershell, it opens a new session. This is similar to typing bash in bash. I want multiple physical windows opening.
I tried -windowstyle as well as the other args to no avail. I was wondering if there is a way you know of. I really appreciate your help. I looked and didn't find anything already here. Thanks for your time.
This will open a new window.
Either:
start-process powershell
Or:
start powershell
if you are trying to open a new window and launch a new script:
start powershell {.\scriptInNewPSWindow.ps1}
This will do it:
Invoke-Item C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe
This works for me:
$argList = "-file `"$Location\script.ps1`""
Start-Process powershell -argumentlist $argList
(The backticks are necessary. This can be copied outright.) Variables can be used in the "-file" parameter (such as one set at the beginning of the script to reflect the location of the file) and spaces can appear in the variable due to the backticks.
Edited to use a two-line solution (the "$argList" variable) because PowerShell can mangle things otherwise.
To start Powershell 6 from a PS console start pwsh might do the trick.
It starts in the same folder.
(I haven't delved into it but I guess PS6's pwsh.exe has to be in the path for it to work.)