Which program to edit a file in powershell and just the powershell? - powershell

I see a lot of questions about this but the answers are only about get function and replace function.
Isn't there anyway to edit a file simple a nano or vi in linux, already pre-installed in powershell?
I could think about a thousand of usecase where you don't want to use function to do that. One among many is that you are remoting on a nanoserver and you want to do several changes in a single script file.

With PowerShell ISE (pre-installed on Windows clients) and vscode with PowerShell Extension and Integrated Console, you can open files in Remote PowerShell Sessions with psEdit $filetoopen.
Example
Enter-PSSession -ComputerName nanoserver
psedit C:\nanofile.txt

Related

How to run an executable through PowerShell without batch files or cmd?

I am currently using batch files to run a set of simulations. Each line in the batch file reads:
"filepath\program.exe" "filepath\simulation.file"
The quotation marks exist to bound any spaces that exist within the file paths. Without any spaces in the file paths, the quotation marks can be removed.
When I run the batch file through PowerShell, using the following command, it works fine:
.\batch.bat
The executable is run and the output is written to the host, as if I was running the same batch file in cmd.
However, I want to ditch the batch files and run the command directly through PowerShell. When I run the following, I get the program to execute, though it doesn't run properly and I don't get anything written to host. It also appears to hang until I use Ctrl+C to cancel.
& "filepath\program.exe" "filepath\simulation.file"
Could you please help me with the following?
Any resources discussing how PowerShell executes batch files.
How to run an executable through PowerShell without using cmd or a batch file and have it write to host.
Have you tried Start-Process?
Start-Process -FilePath "filepath\program.exe" -ArgumentList "filepath\simulation.file" -Wait
PS: The Parameter -Wait is optional.
Although I'm not quite sure why yet, I found out that this issue only occurred while working remotely. Whenever I was connected to the network locally the command ran just fine.
Since I plan to execute the command on PCs that are situated locally on the network, I'll leave it at this for now.
Thanks to everyone who commented!

Format-List not recognized

I'm trying to create a script to automatically export Outlook contacts based on display name. When I run the .bat in Exchange PowerShell, it tells me that Format-List is an unrecognized command. Not quite sure what's going on here. What I've found online usually just recommends running it from PowerShell.
.bat is an extension for batch files, which are run in CMD, even if you call them from PowerShell. CMD and batch files don't know anything about PowerShell cmdlets. If you want to write a PowerShell script, it must have the extension .ps1.

Is it possible to start Powershell ISE with specified (not default) profile?

I want to have several (more than one) PowerShell profiles which will create different environments.
More specifically I need way for start separate PowerShell ISE for work with TFS and other PowerShell ISE instance for regular work. 'TFS' environment require loading some additional snappins, modules, modify prompt and so on. I do not want all this stuff will be executed for regular PowerShell ISE sessions but only when I want to.
I found that I can automatically load arbitrary script through command line parameter -File, but it does not executed automatically..
I do it by creating a shortcut for PowerShell ISE with a default directory :
In the default Directory (here called D:\TFS) I create a .PS1 file called local_profile.ps1.
In the beginning of the current profile file (C:\Windows\System32\WindowsPowerShell\v1.0\profile.ps1) I add :
# Try to load local profile
Get-ChildItem "local_profile.ps1" -ErrorAction SilentlyContinue | %{.$_}
You just have to add your initialization code to D:\TFS\local_profile.ps1.
powershell ISE has a profile too.
Probably is something like:
E:\Users\UserName\Documents\WindowsPowerShell\Microsoft.PowerShellISE_profile.ps1
Or you can open powershell ise and look at $profile variable.
After locate your profile file, write your modules import and custom scripts in it.

Running a Powershell script on multiple PCs

I have modified a script to standardise our organisations signatures in Outlook. The script uses a Word document as a template for the signature and extracts user details from the Active Directory info on our SBS 2003 server.
I am logged in as a Domain Admin and the script works ok for my Outlook signature (there are a couple of errors but it creates the 3x outlook signature files that I need). I can't get it to run on any other computer (but this is the only one with Powershell installed) nor will it run for any other user on this computer.
I would really like to be able to run the script from each workstation. This would be easy if it was a batch file, but it won't work as a powershell script. Do I need to install Powershell on every workstation or is there a simpler way to get it to work?
Also,
I wonder if there is a problem with the script that is not allowing other users to run it from this computer (even with Powershell installed).
Cheers,
Greg
Yes, you need Powershell installed on every machine where you want the script to run. It's included with OS on everything from Server 2008 and Windows 7, but otherwise you'll need to install Powershell manually.
You will also have to enable remote scripting on each machine, since this is disabled by default (for security reasons). Take a look at the following help pages for information and instructions on how to set up:
Get-Help about_remote
Get-Help about_remote_FAQ
Get-Help about_remote_requirements
Get-Help about_remote_troubleshooting
If you want to use PowerShell remotely you will need to install it. If you don't want to do that you could look at psexec - that's one of Sys Internals great tools. It will enable you to run commands\scripts remotely.
I have a different suggestion. Could you generate these signature files for your employees on your machine and then push the signatures out to all the other machines?

how to edit a file in powershell remoting session (powershell)

I am connecting to another computer using powershell remoting, really nice. can do lots, but how do I edit a file?
PS C:\Users\guutlee> Enter-PSSession -ComputerName appprod
[appprod]: PS C:\Users\guutlee\Documents> cd \myapp
[appprod]: PS C:\myapp>
what can I do to open a file editor on a file on the remote machine?
[appprod]: PS C:\myapp> edit app.config
so edit "filename" just seems to hang, from powershell.exe or from powershell_ise.exe
The only thing I can think of is back out of the pssession and "start \webprod\c$\inetpub\myapp\web.config", which would open visual studio.
[appprod]: PS C:\myapp> exit
PS C:\Users\guutlee> start \agobuild\c$\myapp\app.config
PS C:\Users\guutlee> Enter-PSSession -ComputerName appprod
[appprod]: PS C:\Users\guutlee\Documents> cd \myapp
[appprod]: PS C:\myapp> myapp.exe
Of course with this I have to re-find the file, hope that the c$ share is available and accessible, and the reconnect my pssession and re-find my working directory when I want to go on. It doesn't seem very elegant.
I could maybe wrap this is a function, but having a hard time wrapping my head around that..
so how do I conveniently edit a file with a remote pssession?
EDIT
kbrimington's post got me thinking me about the -X option to ssh. probably would be an awesome thing for powershell sessions to be able to forward windowed apps back to the original windowing environment...
but still I'd be happy just to edit the file.
EDIT
tests using vi, emacs, cmd and edit
PS C:\Users\Meredith> Enter-PSSession -ComputerName appprod
[appprod]: PS C:\Users\guutlee\Documents> C:\vim\vim72\vim filename.txt
[appprod]: PS C:\Users\guutlee\Documents> C:\emacs-23.2\bin\emacs.exe -nw filename.txt
emacs.exe : emacs: standard input is not a tty
+ CategoryInfo \: NotSpecified: (emacs: standard input is not a tty:String) [], RemoteException
+ FullyQualifiedErrorId \: NativeCommandError
[appprod]: PS C:\Users\guutlee\Documents> cmd
Microsoft Windows [Version 6.1.7600]
Copyright (c) 2009 Microsoft Corporation. All rights reserved.
C:\Users\guutlee\Documents>
[appprod]: PS C:\Users\guutlee\Documents> edit filename.txt
vi and edit hang (Control-C to get a prompt back)
cmd runs, producing a prompt, but immediately exits back to the powershell prompt
emacs produces the error (standard input is not a tty)
EDIT
Jered suggests pulling the file back locally to edit. I embellished his answer to copying using pssessions rather than UNCs (perhaps this is what he intended)
PS C:\Users\Meredith> Invoke-Command -Session $ps -ScriptBlock {get-content c:/inetpub/myapp/web.config} > web.config
edit web config
PS C:\Users\Meredith> get-content web.config | Invoke-Command -Session $ps -ScriptBlock {set-content c:/inetpub/myapp/web.config}
Potentially we could run the invoke-commands in either direction, local to remote or remote back to local.
If you are using Powershell 5, you can use command called PSEdit. It only works from ISE.
So first, open PowerShell ISE
Then open remote session to the remote computer using Enter-PSSession
Then edit the file using PsEdit 'filename'
The remote file will be opened in a new tab in your (local) ISE window.
Actually I found this answer from the comments section of this SO question , but I think it will be helpful for others if I post it as answer here.
Can you not pull the file locally, edit it and post it? I know this is tedious and not elegant but it seems editors are presently having issue with remote sessions.
E.g.,
Get-Content REMOTE\Filename.txt > LOCAL\Filename.txt
Make your changes locally and then
Set-Content -path REMOTE\Filename.txt -value (get-content LOCAL\Filename.txt)
EDIT
Also if you are only replacing certain instances you can do this pretty easily.
E.g.,
Get-Content REMOTE\Filename.txt | foreach-object { $_ -replace "OLD", "NEW" } | Set-Content REMOTE\Filename.txt
After much digging around, I found something that seems relevant in the powershell help documentation. At the powershell prompt, type:
help about_remote_troubleshooting
At the very end of the help file that is displayed, there is a section entitled 'TROUBLESHOOTING UNRESPONSIVE BEHAVIOUR', which states:
TROUBLESHOOTING UNRESPONSIVE BEHAVIOR
This section discusses remoting problems that prevent a command from
completing and prevent or delay the return of the Windows PowerShell
prompt.
HOW TO INTERRUPT A COMMAND
Some native Windows programs, such as programs with a user interface,
console applications that prompt for input, and console
applications that use the Win32 console API, do not work
correctly in the Windows PowerShell remote host.
When you use these programs, you might see unexpected behavior, such
as no output, partial output, or a remote command that does not
complete. To end an unresponsive program, type CTRL + C. To view any
errors that might have been reported, type "$error" in the
local host and the remote session.
Thus it would seem even non-GUI console applications such as VIM won't work unfortunately. Anyone
care to shed a little light on why this might be the case and/or whether it can be worked
around? I would REALLY love it if I could use vim over powershell remoting.
First, create a temp folder on the local machine (LOCALTEMPFOLDER). Then, use the following function:
function vimrem {param([parameter(position=0,mandatory=$true)][string]$Session, [parameter(position=1,mandatory=$true)][string]$Path)
$TempFile = split-path -path $Path -leaf
copy-item -fromsession $Session -path $Path -destination LOCALTEMPFOLDER\$TempFile
vim $LOCALTEMPFOLDER\$TempFile
copy-item -tosession $Session -path LOCALTEMPFOLDER\$TempFile -destination $Path
remove-item -path LOCALTEMPFOLDER\$TempFile
}
This should work, but you will have leave an interactive session before using this function.
PowerShell_ISE.exe \\REMOTE\...\File.txt
will load and edit the file directly and save it back to the remote computer in one step and, since its command line, easy to build functions using it. Doesn't get around sharing problems, but the easiest way I've found.
Try it out using a console-based editor such as VI or Emacs. As in my comment, I think the problem is that the edit command is bound to a windowed application which, in turn, is not virtualized across a remote session.
I try all the above suggestion and even other microsoft related solution but none works the way you and I want --"full interactive and responsive shell"--. If you really want to have the ssh experience that unix users have from the beggining of time i recomend you install an ssh server. I personally use freesshd, you can find it here http://www.freesshd.com and instructions of how to configure it here http://www.windowsnetworking.com/articles_tutorials/install-SSH-Server-Windows-Server-2008.html. After you make all that it says in the instructions you only need to use any ssh client app to connect to your computer and use powershell full interactive. Vim, edit, emacs or whatever you use to edit a file is going to work without any problem.
i encourage you to not waste your time with psremoting, telnet, winrs, psexec, trying to achieve what a real interactive shell provide (i already lost it, T_T). Try that ssh server an see for your self.
Inspired by the answer provided by #chenz, this can also be done using Visual Studio Code when inside the Powershell Integrated Shell. I tried this with Powershell 7 over SSH remoting, but should also work with WinRM remoting as well.
Enter-Session ...
[RemoteSystem] PS> psedit service.log
The filename will follow this pattern:
C:\users\dev\appdata\local\temp\2\pses-15960\remotefiles\1702137071\winboxname\service.log
I got nano to work easily over SSH to PowerShell. It's available in Chocolatey so you can just do...
choco install nano -y
Then you can just do...
nano filename
I've been looking into this quite thoroughly given the limitations of PSRemoting and the possible work arounds or solutions.
Console editors do not work as they are native (exe) commands and are character based. (I'm wondering if cmd over ssh works with these) It needs to be a cmdlet to properly interact with the console host over a psremote session.
A PSRemote session is line based. You edit the line locally push enter and then it is sent to the remote end, the command is executed and the result returned. So it does support line interactivity but not character interactivity.
Given all these limitations, GNU's ed appears to be a perfect fit. I'm surprised that no one has looked at implementing it as a cmdlet.
I decided to investigate this further, I checked that the powershell cmdlet read-host works and then the C# equivalent PSHostUserInterface.ReadLine() work over a PSRemote session and they do, which is all that is needed to make a working line editor.
So here's what I've done so far. I could probably use some help on the more exotic regex code.
https://github.com/silicontrip/ps-ed
I've used this to edit files via a psremote session. (I wouldn't go editing large source files with it, but for the odd small config file or ps1 script it is perfect.)
Make sure you are familiar with GNU ED before using this cmdlet. It'd be like trying to use VI for the very first time, otherwise.