Why does a working batch command only partially work when redirected? - command-line

I'm writing a batch script that, among other things, opens a macro enabled excel file (.xlsm):
2>nul (
>>%CSF% echo off
) && (start "cmdTitle" /B excel %CSF% /e /automation) || (echo could not open)
%CSF% is the variable referring to a full path to the excel file i.e. "C:\test\testfile.xlsm" (including the quotes for cases where there may be spaces in the directory / filename)
This code checks if the file is locked for editing, then if not it opens the file (start command) otherwise echos could not open.
If I open the file from windows explorer or run just the following in a batch script the file opens fine.
set CSF="C:\Test Folder\Test.xlsm"
start "cmdTitle" /B excel %CSF% /e /automation
However, running the batch file when checking for a locked file always causes excel to say, "Excel found unreadable content in 'filename.xlsm' Do you want to recover the contents of this workbook?" which removes the macros from the file.
EDIT: In addition to the file not opening correctly, any excel add-ins that do something upon excel opening, for example, removing and recreating a command bar also fail to load: "Addin.xla cannot be accessed"
What is causing the difference in behavior between running the command alone and in redirection?
TIA

Examine the end of the file in a hex viewer and see what, if anything, is appended to the end.
Your code as posted works fine (echoing the excel command too). Some other code is likely to be the problem.

Related

How to read a text file to a variable in batch and pass it as a parameter to a powershell script

I have a powershell script that generates a report, and I have connected it to an io.filesystemwatcher. I am trying to improve the error handling capability. I already have the report generation function (which only takes in a filepath) within a try-catch loop that basically kills word, excel and powerpoint and tries again if it fails. This seems to work well but I want to embed in that another try-catch loop that will restart the computer and generate the report after reboot if it fails a second consecutive time.
I decided to try and modify the registry after reading this article: https://cmatskas.com/configure-a-runonce-task-on-windows/
my plan would be, within the second try-catch loop I will create a textfile called RecoveredPath.txt with the file path being its only contents, and then add something like:
Set-ItemProperty "HKLMU:\Software\Microsoft\Windows\CurrentVersion\RunOnce" -Name '!RecoverReport' -Value "C:\...EmergencyRecovery.bat"
Before rebooting. Within the batch file I have:
set /p RecoveredDir=<RecoveredPath.txt
powershell.exe -File C:\...Report.ps1 %RecoveredDir%
When I try to run the batch script, it doesn't yield any errors but doesn't seem to do anything. I tried adding in an echo statement and it is storing the value of the text file as a variable but doesn't seem to be passing it to powershell correctly. I also tried adding -Path %RecoveredDir% but that yielded an error (the param in report.ps1 is named $Path).
What am I doing incorrectly?
One potential problem is that not enclosing %RecoveredDir% in "..." would break with paths containing spaces and other special chars.
However, the bigger problem is that using mere file name RecoveredPath.txt means that the file is looked for in whatever the current directory happens to be.
In a comment your state that both the batch file and input file RecoveredPath.txt are located in your desktop folder.
However, it is not the batch file's location that matters, it's the process' current directory - and that is most likely not your desktop when your batch file auto-runs on startup.
Given that the batch file and the input file are in the same folder and that you can refer to a batch file's full folder path with %~dp0 (which includes a trailing \), modify your batch file to look as follows:
set /p RecoveredDir=<"%~dp0RecoveredPath.txt"
powershell.exe -File C:\...Report.ps1 "%RecoveredDir%"

How to upload a lot of files at once using FileZilla (possibly using a file containing the list of files to publish)?

Is there a way, using FileZilla, to publish many files at once (currently I have to choose them one by one every time, because they can be in different directories and I can't publish the whole directory)?
The ideal solution I am looking for is to use a single .txt file where I can paste the list of paths I want to publish and then somehow tell FileZilla to use it and publish each file to the remote server.
FileZilla lets you export the list of the files you have published with File -> Export in XML format. I am looking for something like this but I need to do the opposite operation.
If someone has some insights on it, please share them with me. Thanks!
P.S.: currently, I also use NetBeans IDE and publish files with it by clicking with the right button of the mouse and selecting Upload. If there's a way to do the same with NetBeans, that would be great (I write PHP code).
Thanks for the attention.
FileZilla does not allow any kind of automation.
See How do I send a file with FileZilla from the command line?
But you can use any other command-line FTP client.
For example WinSCP FTP client has Uploading a list of files example that exactly covers your task:
You may use following batch file that calls WinSCP script:
#echo off
set SESSION=ftp://user:password#example.com/
set REMOTE_PATH=/home/user/
echo open %SESSION% >> script.tmp
rem Generate "put" command for each line in list file
for /F %%i in (list.txt) do echo put "%%i" "%REMOTE_PATH%" >> script.tmp
echo exit >> script.tmp
winscp.com /script=script.tmp
set RESULT=%ERRORLEVEL%
del script.tmp
rem Propagating WinSCP exit code
exit /b %RESULT%

CMD: Export all the screen content to a text file

In command prompt - How do I export all the content of the screen to a text file(basically a copy command, just not by using right-clicking and the clipboard)
This command works, but only for the commands you executed, not the actual output as well
doskey /HISTORY > history.txt
If you want to append a file instead of constantly making a new one/deleting the old one's content, use double > marks. A single > mark will overwrite all the file's content.
Overwrite file
MyCommand.exe>file.txt
^This will open file.txt if it already exists and overwrite the data, or create a new file and fill it with your output
Append file from its end-point
MyCommand.exe>>file.txt
^This will append file.txt from its current end of file if it already exists, or create a new file and fill it with your output.
Update #1 (advanced):
My batch-fu has improved over time, so here's some minor updates.
If you want to differentiate between error output and normal output for a program that correctly uses Standard streams, STDOUT/STDERR, you can do this with minor changes to the syntax. I'll just use > for overwriting for these examples, but they work perfectly fine with >> for append, in regards to file-piping output re-direction.
The 1 before the >> or > is the flag for STDOUT. If you need to actually output the number one or two before the re-direction symbols, this can lead to strange, unintuitive errors if you don't know about this mechanism. That's especially relevant when outputting a single result number into a file. 2 before the re-direction symbols is for STDERR.
Now that you know that you have more than one stream available, this is a good time to show the benefits of outputting to nul. Now, outputting to nul works the same way conceptually as outputting to a file. You don't see the content in your console. Instead of it going to file or your console output, it goes into the void.
STDERR to file and suppress STDOUT
MyCommand.exe 1>nul 2>errors.txt
STDERR to file to only log errors. Will keep STDOUT in console
MyCommand.exe 2>errors.txt
STDOUT to file and suppress STDERR
MyCommand.exe 1>file.txt 2>nul
STDOUT only to file. Will keep STDERR in console
MyCommand.exe 1>file.txt
STDOUT to one file and STDERR to another file
MyCommand.exe 1>stdout.txt 2>errors.txt
The only caveat I have here is that it can create a 0-byte file for an unused stream if one of the streams never gets used. Basically, if no errors occurred, you might end up with a 0-byte errors.txt file.
Update #2
I started noticing weird behavior when writing console apps that wrote directly to STDERR, and realized that if I wanted my error output to go to the same file when using basic piping, I either had to combine streams 1 and 2 or just use STDOUT. The problem with that problem is I didn't know about the correct way to combine streams, which is this:
%command% > outputfile 2>&1
Therefore, if you want all STDOUT and STDERR piped into the same stream, make sure to use that like so:
MyCommand.exe > file.txt 2>&1
The redirector actually defaults to 1> or 1>>, even if you don't explicitly use 1 in front of it if you don't use a number in front of it, and the 2>&1 combines the streams.
Update #3 (simple)
Null for Everything
If you want to completely suppress STDOUT and STDERR you can do it this way. As a warning not all text pipes use STDOUT and STDERR but it will work for a vast majority of use cases.
STD* to null
MyCommand.exe>nul 2>&1
Copying a CMD or Powershell session's command output
If all you want is the command output from a CMD or Powershell session that you just finished up, or any other shell for that matter you can usually just select that console from that session, CTRL + A to select all content, then CTRL + C to copy the content. Then you can do whatever you like with the copied content while it's in your clipboard.
Just see this page
in cmd type:
Command | clip
Then open a *.Txt file and Paste. That's it. Done.
If you are looking for each command separately
To export all the output of the command prompt in text files. Simply follow the following syntax.
C:> [syntax] >file.txt
The above command will create result of syntax in file.txt. Where new file.txt will be created on the current folder that you are in.
For example,
C:Result> dir >file.txt
To copy the whole session, Try this:
Copy & Paste a command session as follows:
1.) At the end of your session, click the upper left corner to display the menu.
Then select.. Edit -> Select all
2.) Again, click the upper left corner to display the menu.
Then select.. Edit -> Copy
3.) Open your favorite text editor and use Ctrl+V or your normal
Paste operation to paste in the text.
If your batch file is not interactive and you don't need to see it run then this should work.
#echo off
call file.bat >textfile.txt 2>&1
Otherwise use a tee filter. There are many, some not NT compatible. SFK the Swiss Army Knife has a tee feature and is still being developed. Maybe that will work for you.
How about this:
<command> > <filename.txt> & <filename.txt>
Example:
ipconfig /all > network.txt & network.txt
This will give the results in Notepad instead of the command prompt.
From command prompt Run as Administrator. Example below is to print a list of Services running on your PC run the command below:
net start > c:\netstart.txt
You should see a copy of the text file you just exported with a listing all the PC services running at the root of your C:\ drive.
If you want to output ALL verbosity, not just stdout. But also any printf statements made by the program, any warnings, infos, etc, you have to add 2>&1 at the end of the command line.
In your case, the command will be
Program.exe > file.txt 2>&1

Open text file and program shortcut in a Windows batch file

I have two files in the same folder that I'd like to run. One is a .txt file, and the other is the program shortcut to an .exe. I'd like to make a batch file in the same location to open the text file and the shortcut then close the batch file (but the text file and program remain open).
I tried this with no luck:
open "myfile.txt"
open "myshortcut.lnk"
Also didn't work:
start "myfile.txt"
start "myshortcut.lnk"
I was able to figure out the solution:
start notepad "myfile.txt"
"myshortcut.lnk"
exit
This would have worked too. The first quoted pair are interpreted as a window title name in the start command.
start "" "myfile.txt"
start "" "myshortcut.lnk"
Don't put quotes around the name of the file that you are trying to open; start "myfile.txt" opens a new command prompt with the title myfile.txt, while start myfile.txt opens myfile.txt in Notepad. There's no easy solution in the case where you want to start a console application with a space in its file name, but for other applications, start "" "my file.txt" works.
The command-line syntax for opening a text file is:
type filename.txt
File types supported by this command include (but are not limited to): .doc, .txt, .html, .log
If the contents is too long, you can add "|more" after "type filename.txt", and it will pause after each screen; to end the command before the end of the file, you can hold Ctrl + C.
I use
#echo off
Start notepad "filename.txt"
exit
to open the file.
Another example is
#echo off
start chrome "filename.html"
pause
You can also do:
start notepad "C:\Users\kemp\INSTALL\Text1.txt"
The C:\Users\kemp\Install\ is your PATH. The Text1.txt is the FILE.
"location of notepad file" > notepad Filename
C:\Users\Desktop\Anaconda> notepad myfile
works for me! :)
In some cases, when opening a LNK file it is expecting the end of the application run.
In such cases it is better to use the following syntax (so you do not have to wait the end of the application):
START /B /I "MyTitleApp" "myshortcut.lnk"
To open a TXT file can be in the way already indicated (because notepad.exxe not interrupt the execution of the start command)
START notepad "myfile.txt"
The command start [filename] opened the file in my default text editor.
This command also worked for opening a non-.txt file.
If you are trying to open an application such as Chrome or Microsoft Word use this:
#echo off
start "__App_Name__" "__App_Path__.exe"
And repeat this for all of the applications you want to open.
P.S.: This will open the applications you select at once so don't insert too many.
Try using:
#ECHO off
ECHO Hello World!
START /MAX D:\SA\pro\hello.txt
Its very simple,
1)Just go on directory where the file us stored
2)then enter command i.e. type filename.file_extention
e.g type MyFile.tx
To open a file with default software just need to type the path of the file or, if you are at the file location, the file name.
C:\Users\MyName>C:\User\MyName\Desktop\hello.txt
or
C:\Users\MyName\Desktop>hello.txt
If you want specific program like notepad you can specify it first.
C:\Users\MyName>notepad C:\User\MyName\Desktop\hello.txt
or
C:\Users\MyName\Desktop>notepad hello.txt
Note that notepad is usually default text editor for .txt, in this case would make more sense to type notebook only to open a .cs/.cpp/.py file if your default for that files is any IDE and you just want to see the file on notebook
Regarding the batch file it will work the same way but to open them at the same time and let the command line go away you should use:
start "title" {filename}
So the command can open the file and return to next line immediately.
start "" C:\Users\MyName\MyFolder\foo.exe
start "" C:\Users\MyName\MyFolder\notes.txt
or
start "" foo.exe
start "" notes.txt
The last one only works if the batch file is on the same location of the files.
If you plan on using the console to open the batch file and you want the console to close at the end you should indeed write exit on last line.
When in doubt, it always helps to read the docs:
>help start
Starts a separate window to run a specified program or command.
START ["title"] [/D path] [/I] [/MIN] [/MAX] [/SEPARATE | /SHARED]
[/LOW | /NORMAL | /HIGH | /REALTIME | /ABOVENORMAL | /BELOWNORMAL]
[/NODE <NUMA node>] [/AFFINITY <hex affinity mask>] [/WAIT] [/B]
[command/program] [parameters]
"title" Title to display in window title bar.
path Starting directory.
B Start application without creating a new window. The
application has ^C handling ignored. Unless the application
enables ^C processing, ^Break is the only way to interrupt
the application.
I The new environment will be the original environment passed
to the cmd.exe and not the current environment.
MIN Start window minimized.
MAX Start window maximized.
SEPARATE Start 16-bit Windows program in separate memory space.
SHARED Start 16-bit Windows program in shared memory space.
LOW Start application in the IDLE priority class.
NORMAL Start application in the NORMAL priority class.
HIGH Start application in the HIGH priority class.
REALTIME Start application in the REALTIME priority class.
ABOVENORMAL Start application in the ABOVENORMAL priority class.
BELOWNORMAL Start application in the BELOWNORMAL priority class.
NODE Specifies the preferred Non-Uniform Memory Architecture (NUMA)
node as a decimal integer.
AFFINITY Specifies the processor affinity mask as a hexadecimal number.
Picture for the visual learners:

EmacsW32 renames buffers with old Windows shortened file names

Let's see if I can reach the EmacsW32 users on stackoverflow.
I've just installed the patched version of EmacsW32 from http://ourcomments.org/Emacs/EmacsW32.html
I find it very nice that .txt files are associated wth Emacs, so that when you click on one, emacsclient opens it in the running instance of Emacs.
Problem is, for some reason, the buffer is renamed with the old-style shortened file names, so, for example, the buffer with file "activities-2008.txt" is renamed to "ACTIV~1.TXT", which I don't like.
How do I get EmacsW32 not to rename the buffer, and use the whole file name as the buffer name instead ?
Ick, that sucks.
Why not just use the emacsclientw that comes with the standard Windows emacs distribution?
It does have a bit of an issue in that you get an annoying "No error" error box if Emacs isn't already running, but any real emacs user starts emacs first thing when they log on anyway. :-)
Solved.
The problem is not with emacs, but with the way Windows runs a program when a file type is associated in the registry.
In my registry, I had this value for the keys that associate txt files with Emacs:
C:\emacs-23.0.91.1\Emacs\bin\emacsclientw.exe -n "%1"
The problem is the %1, which is replaced by a short file name.
According to this message http://lists.gnu.org/archive/html/help-emacs-windows/2009-05/msg00022.html:
%L is long file names.
%1 is long file names IF
* Explorer can find the exe file (it does not look very hard)
AND
* The file header says it is Win 95 aware Win16 exe, or
* It is a 32 bit program
Else %1 will be a short name.
The solution is to use %L in place of %1 in the reg keys.