Replacing a string in all config files across machines with a script - templates

I have the below task and I am wondering what would be the best and quick way to do this. I am thinking scripting rather than a C# app but struggling with scripting in DOS. I wanted to use powershell but not sure if all the machines have powershell installed :
I have around 15 windows machines and in each machine, I want to find all *.config files (in say C:\ and D:) and replace a specific word (db name).
I can execute this locally or execute this remotely, since I have login access to the machines. But the tough part is the script.
Any pointers would be great to start.
Thanks.

Wikipedia has some info on what versions of Windows have PowerShell.
PowerShell version 1.0 was released in 2006 for Windows XP SP2/SP3, Windows Server 2003, and Windows Vista....Version 2.0 is integrated with Windows 7 and Windows Server 2008 R2 and is released for Windows XP with Service Pack 3, Windows Server 2003 with Service Pack 2, and Windows Vista with Service Pack 1. Version 3.0 is integrated with Windows 8 and with Windows Server 2012. Microsoft has also made PowerShell 3 available for Windows 7 with Service Pack 1, for Windows Server 2008 with Service Pack 1, and for Windows Server 2008 R2 with Service Pack 1.
To install version 3 on Win 7 you need the WMF 3.0 package

This is untested and destructive so test it first.- it is designed to search C: and D: drives and all subdirectories and modifies all *.config files.
It is set to look in c:\abc and d:\abc trees atm so put some files and folders in there and test it.
#echo off
for /f "delims=" %%a in ('dir c:\abc\*.config d:\abc\*.config /b /s /a-d') do (
call :sar "%%a" "%%a.tmp" "db_name" "new_db_name"
move /y "%%a.tmp" "%%a" >nul
)
goto :EOF
:sar
:: inputfile outputfile regexp_search replacement
if "%~5"=="" (set global=true) else (set global=false)
set s=regex.replace(wscript.stdin.readall,"%~4")
>_.vbs echo set regex=new regexp
>>_.vbs echo regex.global=%global%
>>_.vbs echo regEx.IgnoreCase=True
>>_.vbs echo regex.pattern="%~3"
>>_.vbs echo wscript.stdOut.write %s%
cscript /nologo _.vbs <"%~1" >"%~2"
del _.vbs
goto :EOF

Related

Powershell getting values via regex

Normally , I can catch values beginning with Windows Server like below script. But I want to get version number for operating systems as well.
Windows Embedded
Windows XP
Windows 7
Windows 10
Windows ServerĀ® 2008 Standard
Windows ServerĀ® 2008 Enterprise
So , it will be only 7 ,XP , 10 , Embedded , 2008 inside version variable.
Script :
$server = Get-ADComputer -Filter "Name -eq '$computer'" -Properties OperatingSystem -ErrorAction SilentlyContinue
$version = ([regex]'Windows Server (\d+)').Match($server.OperatingSystem).Groups[1].Value
This match every line and capture exactly what you want :
Windows(?: Server)?[^\w\r\n]+(\w+).*

Print colorful ascii art in CPP console [duplicate]

I'm building a lightweight version of the ncurses library. So far, it works pretty well with VT100-compatible terminals, but win32 console fails to recognise the \033 code as the beginning of an escape sequence:
# include <stdio.h>
# include "term.h"
int main(void) {
puts(BOLD COLOR(FG, RED) "Bold text" NOT_BOLD " is cool!" CLEAR);
return 0;
}
What needs to be done on the C code level, in order that the ANSI.SYS driver is loaded and the ANSI/VT100 escape sequences recognized?
[UPDATE] For latest Windows 10 please read useful contribution by #brainslugs83, just below in the comments to this answer.
While for versions before Windows 10 Anniversary Update:
ANSI.SYS has a restriction that it can run only in the context of the MS-DOS sub-system under Windows 95-Vista.
Microsoft KB101875 explains how to enable ANSI.SYS in a command window, but it does not apply to Windows NT. According to the article: we all love colors, modern versions of Windows do not have this nice ANSI support.
Instead, Microsoft created a lot of functions, but this is far from your need to operate ANSI/VT100 escape sequence.
For a more detailed explanation, see the Wikipedia article:
ANSI.SYS also works in NT-derived systems for 16-bit legacy programs executing under the NTVDM.
The Win32 console does not natively support ANSI escape sequences at all. Software such as Ansicon can however act as a wrapper around the standard Win32 console and add support for ANSI escape sequences.
So I think ANSICON by Jason Hood is your solution. It is written in C, supports 32-bit and 64-bit versions of Windows, and the source is available.
Also I found some other similar question or post which ultimately have been answered to use ANSICON:
How to load ANSI escape codes or get coloured file listing in WinXP cmd shell?
how to use ansi.sys in windows 7
How can I get cmd.exe to display ANSI color escape sequences?
ansi color in windows shells
enable ansi colors in windows command prompt
Starting from Windows 10 TH2 (v1511), conhost.exe and cmd.exe support ANSI and VT100 Escape Sequences out of the box (although they have to be enabled).
See my answer over at superuser for more details.
Base on #BrainSlugs83 you can activate on the current Windows 10 version via register, with this command line:
REG ADD HKCU\CONSOLE /f /v VirtualTerminalLevel /t REG_DWORD /d 1
For Python 2.7 the following script works for me fine with Windows 10 (v1607)
import os
print '\033[35m'+'color-test'+'\033[39m'+" test end"
os.system('') #enable VT100 Escape Sequence for WINDOWS 10 Ver. 1607
print '\033[35m'+'color-test'+'\033[39m'+" test end"
Result should be:
[35mcolor-test[39m test end
color-test test end
Starting from Windows 10, you can use ENABLE_VIRTUAL_TERMINAL_PROCESSING to enable ANSI escape sequences:
https://msdn.microsoft.com/en-us/library/windows/desktop/mt638032(v=vs.85).aspx
If ANSICON is not acceptable since it requires you to install something on the system, a more lightweight solution that parses and translates the ANSI codes into the relevant Win32 API console functions such as SetConsoleTextAttribute.
https://github.com/mattn/ansicolor-w32.c
For coloring the cmd you need Windows.h and use SetConsoleTextAttribute() more details can be found in http://msdn.microsoft.com/en-us/library/windows/desktop/ms686047%28v=vs.85%29.aspx
In lastest win10, it can be done by SetConsoleMode(originMode | ENABLE_VIRTUAL_TERMINAL_PROCESSING). See https://learn.microsoft.com/en-us/windows/console/console-virtual-terminal-sequences#example
Maybe ANSICON can help u
Just download and extract files, depending on your windows os: 32bit or 64bit
Install it with: ansicon -i
I personally like clink. It not only processes ANSI codes, it also adds many other features so Windows Console behaves like bash (history, reverse history search, keyboard shortcuts, etc.):
The same line editing as Bash (from GNU's Readline library).
History persistence between sessions.
Context sensitive completion;
Executables (and aliases).
Directory commands.
Environment variables
Thirdparty tools; Git, Mercurial, SVN, Go, and P4.
New keyboard shortcuts;
Paste from clipboard (Ctrl-V).
Incremental history search (Ctrl-R/Ctrl-S).
Powerful completion (TAB).
Undo (Ctrl-Z).
Automatic "cd .." (Ctrl-PgUp).
Environment variable expansion (Ctrl-Alt-E).
(press Alt-H for many more...)
Scriptable completion with Lua.
Coloured and scriptable prompt.
Auto-answering of the "Terminate batch job?" prompt.
Ansi.sys (in the system32 folder) is an "MSDOS driver" provided as part of Windows XP, 2000, and earlier versions of NT. In 2000 and XP, it is located in the system32 folder (I don't remember the structure of earlier versions of NT). Programs that run in the DOS subsystem and use standard output can use ANSI.SYS just as they could running over MSDOS.
To load ansi.sys, you must use the device= or devicehigh= command in config, just as you would in MSDOS. On Windows NT 5 (2K & XP), each copy of the DOS subsystem can be given a separate config file in the pif/shortcut (use the "advanced" button), and there is a default file called CONFIG.NT (also in the system32 folder), which is used if the pif/shortcut does not specify a special config file.
When ansi.sys is loaded correctly, mem /d will report that it is loaded. On earlier versions of NT, you can and must load a proper DOS environment to load ansi.sys, and ansi art will work at the prompt. On Win 2K and XP, loading ansi.sys will have no effect on your "CMD prompt" because CMD is not a DOS program: it is a 32 bit Windows console program. For some reason that I do not understand, on WinXP, even if you load a fixed copy of command.com using "command.com /p", the command prompt will not be ansi enabled: perhaps when you do it that way it only emulates loading command.com?
In any case, when you use an actual DOS version of command.com, ansi is enabled after being loaded: you can demonstrate it's use with a bit of ansi art like this:
command /c type ansiart.ans
(here is an example: http://artscene.textfiles.com/ansi/artwork/beastie.ans)
CONFIG.NT (in the system32 folder) contains an example of the syntax for loading device drivers. You will need to be an Administrator to edit that default file, or you can make a copy of it.
On Win 2K and XP, the default "shortcut" for MSDOS is a .PIF file, not a .LNK file. If you create a .lnk file to CMD, you won't be able to set special config and autoexec files, it will use the default CONFIG.NT. If you want to use a special config file for just one DOS application, you can make a copy of the "MSDOS shortcut", or you can make a copy of "_default.pif", found in your Windows folder.
Had the same issue. I installed ConEmu and that one solved my problem.
I found this tool to be working for my end.
Microsoft Color Tool from GitHub
Unzip the compressed file then open CMD with Administration permission.
Go to the folder where you unzip the file in CMD.
Then execute this command "colortool -b scheme-name"
The scheme-name needs to be replaced with any of these options below:
campbell.ini
campbell-legacy.ini
cmd-legacy.ini
deuternopia.itermcolors
OneHalfDark.itermcolors
OneHalfLight.itermcolors
solarized_dark.itermcolors
solarized_light.itermcolors
In my case, the command would be like this "colortool -b solarized_dark.itermcolors"
Click right on the console window and select Properties.
You don't need to change any value just click "OK" to save the setting. (You will notice that your font already contains colors).
Console Property
Then restart your cmd or powerShell.
The ANSI color should be enabled and working with the color scheme you chose before.
Somehow in Windows you just need to call any shell command first, rather call the system function. Just in start of your main method put system("");, and don't forget to include stdlib.h.
I noticed this when I looked at some of my old programs that also used ANSI codes to understand why they work, but my new code is not

Visual Studio cross platform makefile project, command not found

I'm trying to build a cross platform project for Ubuntu. In my makefile I have the line
"PSPSDK=$(shell psp-config --pspsdk-path)"
which gives the error "psp-config: Command not found."
psp-config is in my path and running make from the Ubuntu system on the files that get copied over from Visual Studio works fine. It also works if I manually ssh into the Ubuntu system from windows and run the command from there.
Why can't it find the command when run through Visual Studio?
You should update PATH at the beginning of "~/.bashrc" file (and not at the end) because it starts with somethign like:
# If not running interactively, don't do anything
case $- in
*i*) ;;
*) return;;
esac
Also, if you add code before these lines, it will be invoked for every subshell execution, so it is better to add a guard for it as well so it is invoked only once per session:
if [ -z $HOME_OPT_PATH_SET ]; then
export PATH=$PATH:$HOME/opt
export HOME_OPT_PATH_SET=1
fi
# If not running interactively, don't do anything
...

batch file to check existance of directory if not exists then use alternate directory for file copy

I am trying to write a batch file that copies an exe file from a network location to a local location. It currently works but depending on windows version (xp or win7) the user has to select the correct .bat file due to different local paths needed for the copy. (they are going to the startup folder to be ran every time user starts machine). This is the first time i've ever worked with writing batch files and am completely lost when looking at the syntax for if statements. If i could get some help figuring this out it would be great.
Here is what I currently have that works for XP:
REM #ECHO OFF
ECHO STARTING MOVEFILES
SET EXITRC=0
SET EXITMSG=EXITRC INITIALIZED
ECHO %EXITRC% -- %EXITMS
COPY "\\networkDrive\install\Individual\program\MOVEFILES.EXE" "C:\DOCUMENTS AND SETTINGS\ALL USERS\START MENU\PROGRAMS\STARTUP\"
ECHO COPIED FILES TO YOUR PC
SET EXITRC=%ERRORLEVEL%
IF NOT %EXITRC% == 0 GOTO :EXIT
SET EXITMSG=PROCESSING COMPLETE
:EXIT
ECHO STEP: %EXITMSG% RC: %EXITRC%
ECHO FINISHING MOVEFILES
PAUSE
EXIT %EXITRC%
Here is what I have for Windows 7:
#ECHO OFF
ECHO STARTING MOVEFILESWIN7
SET EXITRC=0
SET EXITMSG=EXITRC INITIALIZED
ECHO %EXITRC% -- %EXITMS
COPY "\\networkDrive\install\Individual\program\MOVEFILES.exe" "C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Startup"
ECHO COPIED MOVEFILESWIN7 TO YOUR PC - All Users / Public Startup folder
SET EXITRC=%ERRORLEVEL%
IF NOT %EXITRC% == 0 GOTO :EXIT
SET EXITMSG=PROCESSING COMPLETE
:EXIT
ECHO STEP: %EXITMSG% RC: %EXITRC%
ECHO FINISHING MOVEFILESWIN7
PAUSE
EXIT %EXITRC%
I would like to have only one batch file that will cover both scenarios so there is no confusion to the user on which batch file to run.
You can utilise the environment variable %ALLUSERSPROFILE%.
On WinXP the default is C:\Documents and Settings\All Users
On Win7/2008 the default is C:\ProgramData
There is a table available here: http://ss64.com/nt/syntax-variables.html
I see you also copy a different file. Not sure why you do that. Maybe you could detect using a method here: https://stackoverflow.com/a/2788764/1553090 -- Otherwise perhaps you should take advantage of the %ProgramFiles% and %ProgramFiles(x86)% variables.
Just to elaborate on how you might choose to use these variables... You can test the Win7 startup folder for existence, and if it's not there just fallback to the XP (regardless of whether it exists).
set STARTUP_WIN7=%ALLUSERSPROFILE%\Microsoft\Windows\Start Menu\Programs\Startup
set STARTUP_WINXP=%ALLUSERSPROFILE%\Start Menu\Programs\Startup
if EXIST "%STARTUP_WIN7%" (
set STARTUP=%STARTUP_WIN7%
) else (
set STARTUP=%STARTUP_WINXP%
)

Build Boost C++ WinCE

I know that are similar question but doesn't help me.
I want to build boost for Windows CE 6 on an x86 Platform.
I've build STLPort in release moded as shared library for WINCE with success, I've also add some patch and integrate the OpenCE Time library and implemented some missing ANSI C function. STLPort test is ok (just an issue with wcout, wcin and wcerr in_avail() function, I don't know exactly where is the problem).
To build boost I created a batch file and change the user-config.jam in this way. The build is ok but seems that I'm compiling for my Windows Xp Platform instead of WinCE.
The boost build system is very complicated and I'm not understanding how it work (the documentation isn't very good and on google there's no much). The build of boost is ok but I cannot run application. It seems that is missing some DLL or that the Boos DLL's are wrong. The message I get when I'm attacched with debugger is "Nessun processo all'estremita' della PIPE" -> "No process at the end of the PIPE". When I try to launch the application from the target device it has no effect. Am I wrong something? How can I tell boost to use specific configuration?
Another problem is that i cannot see the build log. I don't know what exactly I'm building. Is there a way to see what actually is done?
The batch file that I call to build boost (I start the shell of Visual Studio 2008):
#echo off
cls
bjam --with-chrono --with-date_time --with-thread toolset=msvc-CEPlatformName variant=release threading=multi link=shared runtime-link=shared
This is the user-config.jam located in tools/build/v2
using msvc : CEPlatformName:
<compileflags>-D_CRT_SECURE_NO_WARNINGS
<compileflags>-D_CRT_SECURE_NO_DEPRECATE
<compileflags>-DBOOST_PROTO_MAX_ARITY=10
<compileflags>-DBOOST_MPL_CFG_NO_PREPROCESSED_HEADERS
<compileflags>-DBOOST_MPL_LIMIT_METAFUNCTION_ARITY=10
<compileflags>-D_WIN32_WCE=0x600
<compileflags>-DUNDER_CE
<compileflags>-DWINCE
<compileflags>-Dx86
<compileflags>-D_x86_
<compileflags>-D_UNICODE
<compileflags>-DUNICODE
<linkflags>/subsystem:windowsce,6.00
<linkflags>/MACHINE:X86
<linkflags>/NODEFAULTLIB:oldnames.lib
<linkflags>/NODEFAULTLIB:libc.lib
<linkflags>coredll.lib
<linkflags>corelibc.lib
<linkflags>ole32.lib
<linkflags>oleaut32.lib
<linkflags>uuid.lib
<setup>C:/boost_1_53_0/CEPlatformNameConfig.bat.bat
;
using stlport : 5.2 :
C:/celib/stlport/stlport :
C:/celib/stlport/bin
;
And this is the script file for configuration
#echo off
echo CONFIGURAZIONE PER LA COMPILAZIONE DI BOOST SU WINCE
echo.
rem ------------------------------------------------------------
set BOOST_DIR=c:\boost_1_53_0\boost
set PLATFORM=CEPlatformName
set TARGETCPU=x86
set OSVERSION=WCE600
set STLPORT_DIR=C:\celib\stlport
set STLPORT_INC=%STLPORT_DIR%\stlport
set STLPORT_LIB=%STLPORT_DIR%\bin\%PLATFORM%
rem ------------------------------------------------------------
if not %1==%&TARGETCPU% goto error
echo Setting Boost directory to %BOOST_DIR%
echo Setting OS Platform to %PLATFORM%
echo Setting target CPU to %TARGETCPU%
echo Setting OS Versione to %OSVERSION%
echo Setting STLPORT_INC to %STLPORT_INC%
echo Setting STLPORT_LIB to %STLPORT_LIB%
rem settin visual studio 2008 variable path
set SDKROOT=C:\Programmi\Windows CE Tools
set PATH=%VSINSTALLDIR%\VC\ce\bin\x86_cex86;%VSINSTALLDIR%\VC\bin;%VSINSTALLDIR%\Common7\IDE;%PATH%
set PLATFORMROOT=%SDKROOT%\%OSVERSION%\%PLATFORM%
set INCLUDE=%STLPORT_INC%;%PLATFORMROOT%\include\;%PLATFORMROOT%\include\%TARGETCPU%;%VCINSTALLDIR%\ce\include;%VCINSTALLDIR%\ce\atlmfc\include;%VSInstallDir%\SmartDevices\SDK\SQL Server\Mobile\v3.0;
set LIB=%STLPORT_LIB%;%PLATFORMROOT%\lib\%TARGETCPU%;%VCINSTALLDIR%\ce\ATLMFC\LIB\%TARGETCPU%;%VCINSTALLDIR%\ce\LIB\%TARGETCPU%
echo PATH at %PATH%
echo.
echo INCLUDE is %INCLUDE%
echo.
echo LIB is %LIB%
echo.
goto exit
:error
echo Invali Target CPU
goto exit
:exit
echo impostazioni avvenute con successo
EDIT
Seems that the compileflags in the user-config.jam has no effect... or better seems that the user-config.jam has no effect
EDIT 2
I've found an issue
using msvc : CEPlatformName :
<compileflags>-D WINCE
The issue is that this instruction does not define anything. I've also tried
using msvc : CEPlatformName :
<compileflags>/D_CRT_SECURE_NO_WARNINGS
But the result is the same.
I've found the problem
I'm finally build boost.chrono boost.date_time boost_system and boost.thread fow Windows CE 6.0 on a custom x86 target.
I've changed user-config.jam in this way
using msvc : 9.0~CEPlatformName : "C:\...\cl.exe" :
<compileflags>-D_CRT_SECURE_NO_WARNINGS
<compileflags>-D_CRT_SECURE_NO_DEPRECATE
...
<setup>CEPlatformNameConfig.bat
;
in this way the bjam call the correct batch file for configure the build system. If the compiler is not specified bjam will call vcvarsall.bat and the compiler flags will be ignored.
Now the bjam call is:
bjam ... toolset=msvc-9.0~CEPlatformName ...
It's also important to correctly define the `x86` and `_X86_`. Note that `X86` will casue STLPort to assume wrong directory for ANSI C library files.
But I've an Issue on boost::this_thread::sleep_for() function. I know that boost use TLS for this operation and I know that TLS is not fully implemented in WinCE. I can replace this function with a simple ::Sleep() of the Win32 Library.
I'm only sure the WinCE has `TlsAlloc()`, `TlsFree()`, `TlsGetValue()` and `TlsSetValue()` functions, and has at least `TLS_MINIMUM_AVAILABLE` slot for TLS that is defined at least to 64.
Finaly I'm able to build Boost.Thread Boost.System Boost.Chrono Boost.DateTime Boost.Regex in debug and release mode.
The issue is according to this port (http://stackoverflow.com/questions/16016637/boost-c-and-windows-ce-6-0) that WinCe doesn't support long names. DLL name's can be larger then 32 chars.
The same problem of name length caused this_thread::sleep_for to don't work.
Thanks for all people the helped me.