How to replace the given line of text file in looping structure using windows batch file - powershell

set instance=3
for /L %%A in (1,1,%instance%) do (
set /p var=LogfileName: trial.txt
set rep=LogfileName: logfile.txt
echo %var%
powershell -Command "(gc InputFile.txt) -replace '%var%', '%rep%' | Out-File InputFile.txt"
)
I am not able to replace the line in text file using this commands. And also I am not getting how to take the line number and store the string in that particular lile in file into a batch file variable.

% variables in batch files are expanded at parse time (when the statement is read). Since the entire for statement, including the action block, is read as one statement, %var% and %rep% are expanded before the loop is executed, meaning they evaluate to empty strings.
To have the variables inside the loop expanded at execution time you need to enable delayed expansion and use ! notation:
setlocal EnableDelayedExpansion
set instance=3
for /L %%A in (1,1,%instance%) do (
set /p var=LogfileName: trial.txt
set rep=LogfileName: logfile.txt
echo !var!
powershell -Command "(gc InputFile.txt) -replace '!var!', '!rep!' | Out-File InputFile.txt"
)
For further explanation see Raymond Chen's blog.

Related

How to use a PowerShell function return as a variable in a batch file

I was trying to use the return from myPowershellScript.ps1 to use as a variable in my batch file.
myPowershellScript.ps1
function GetLatestText
{
return "Hello World"
}
I was trying to use the For /F function. There may be a better way.
myBatch.bat
for /f "delims=" %%a in (' powershell -command "\\Rossi2\Shared\myPowershellScript.ps1" ') do set "var=%%a"
echo %var%
Desired output, would be to have 'Hello World' output in the cmd window.
I was trying to use the batch file as some old processes use them. For newer processes I do everything in PowerShell and it works fine.
The current output is blank.
Your syntax for trying to capture output from a PowerShell script from a batch file is correct (assuming single-line output from the script),[1] except that it it is more robust to use the -File parameter of powershell.exe, the Windows PowerShell CLI than the -Command parameter.
See this answer for when to use -File vs. -Command.
Your problem is with the PowerShell script itself:
You're defining function Get-LatestText, but you're not calling it, so your script produces no output.
There are three possible solutions:
Place an explicit call to Get-LatestText after the function definition; if you want to pass any arguments received by the script through, use Get-LatestText #args
Don't define a function at all, and make the function body the script body.
If your script contains multiple functions, and you want to call one of them, selectively: in your PowerShell CLI call, dot-source the script file (. <script>), and invoke the function afterwards (this does require -Command):
for /f "delims=" %%a in (' powershell -Command ". \"\\Rossi2\Shared\myPowershellScript.ps1\"; Get-LatestText" ') do set "var=%%a"
echo %var%
[1] for /f loops over a command's output line by line (ignoring empty lines), so with multiline output only the last line would be stored in %var% - more effort is needed to handle multiline output.
You can combine the batch and the powershell in single file (save this as .bat ):
<# : batch portion
#echo off & setlocal
for /f "tokens=*" %%a in ('powershell -noprofile "iex (${%~f0} | out-string)"') do set "result=%%a"
echo PS RESULT: %result%
endlocal
goto :EOF
: end batch / begin powershell #>
function GetLatestText
{
return "Hello World"
}
write-host GetLatestText

How to pass batch file variables to PowerShell script? [duplicate]

This question already has an answer here:
Displaying SET variable
(1 answer)
Closed 3 years ago.
I am attempting to pass a number of variables processed by my batch file to a Powershell script. The problem I face is that firstly the entire results from the batch file come up in command prompt and next to the variables I intend to pass are not passed to the Powershell Script. Additionally, the variable I have to output the contents of the log file in just send the command back to the screen.
I have tried the following links and these links got me as far as I am now:
Batch file to execute a Powershell script
Pass variable from batch to powershell
Pass parameter from a batch file to a PowerShell script
Pass batch variables with spaces in them to powershell script?
Batch File side
set LOG_FILE = "GDGAGnklasj;oks;fk;dkf lkl;"
set oName = Name
set oStart = "%YYYY%%MM%%DD% %TIME%"
set oStatus = 0
set oEnd = "%YYYY%%MM%%DD% %TIME%"
set oDateRan = %YYYY%%MM%%DD%
set oLog =for /f "delims=" %%i in (%LOG_FILE%) do set content=%content% %%i
echo Updating Database >> %LOG_FILE% 2>&1
cmd /S powershell.exe -ExecutionPolicy Bypass -File "C:\Reporting\updateTool.ps1" "%oName%" "%DateRan%" "%oStart%" "%oEnd%" "%oStatus "%oLog%
PowerShell Script
param (
[string]$oName
)
"This is $oName"
My intent is to set the variables within the batch file then send them to Powershell for processing.
Be very careful of spaces.
set oName=taco
PowerShell.exe -NoProfile -ExecutionPolicy Bypass -Command "& '.\ScriptName.ps1' -oName '%oName%' "
Oh Easy-Peasy, I do this for my Power shells that we need CMD wrappers for quite a bit.
I have to run to the train so this is going to be a bit meh at the moment I will firm it up in a bit, right now just going to paste in some example code so I can make it your code
Okay, what, umm, what did you intend for this Particular code to.l do ? I can't seem to figure out what you were intending with this, is it just some dummy code?
set oLog =for /f "delims=" %%i in (%LOG_FILE%) do set content=%content% %%i
echo Updating Database >> %LOG_FILE% 2>&1
Okay on further review I think you want to read the log into a couple of sttring variables in CMD, then use one of them in your call of the script..... but, why?
The strings will append to each other and you will be limited to 8191 characters max, and PowerShell can easily read the content of the log file because you pass the name to Powershell.
That seems like a better plan, no?
All your code where you have YYYY MM DD those are variables you will need to define before using, not sure if that is understood if so all good.
.CMD Script:
#(
SETLOCAL ENABLEDELAYEDEXPANSION
ECHO OFF
SET "_PSScript=C:\Reporting\UpdateTool.ps1"
REM SET "_DebugPreference=Continue"
SET "_DebugPreference="SilentlyContinue"
SET "_LOG_FILE=GDGAGnklasj;oks;fk;dkf lkl;"
SET "_oName=Name."
SET "_oStart=%YYYY%%MM%%DD% %TIME: =0%"
SET /a "_Status=0"
SET "_oEnd=%YYYY%%MM%%DD% %TIME: =0%"
SET "_oDateRan=%YYYY%%MM%%DD%"
)
SET "_PSCMD=Powershell "%_PSScript%" -DebugPreference "%_DebugPreference%" -LOG_FILE "%_LOG_FILE%" -oName "%_oName%" -oStart "%_oStart%" -Status %_Status% -oEnd "%_oEnd%" -oDateRan "%_oDateRan%" "
%_PSCMD% 2>&1 >> "_LOG_FILE"
PS1:
## Script: UpdateTool.ps1
#
param(
[String]$LOG_FILE = 'c:\admin\default.log',
[String]$oName = 'default name'
[String]$oStart = $(Get-date -F "yyyyMMdd HH:mm:ss.ms"),
[Int]$oStatus = 0,
[String]$oEnd = $(Get-date -F "yyyyMMdd HH:mm:ss.ms"),
[String]$oDateRan = $(Get-date -F "yyyyMMdd"),
$DebugPreference = "SilentlyContinue"
)

Double quotes not escaping from string when calling Powershell command from within Batch script?

Double quotes structure is not retained in my test message when passed through a powershell instance called through a batch script, as detailed below:
set test={"this":"is","a":"test"}
FOR /F "delims=" %%i in (' powershell -Command "& {$message = '%test%'; echo $message}" ') DO SET message=%%i
echo %test%
echo %message%
the output is as follows:
{"this":"is","a":"test"}
{this:is,a:test}
I would like to retain the quotes to further process the string in powershell, but as you can see, they are stripped when introduced into the $message variable.
Any insight as to how I might fix this?
Echoing %test% containing double quotes inside the d-quoted powershell command will break the enclosing d-quotes.
One way to overcome this, is using batch string substitution to escape the inner d-quotes with a backslash on the fly
:: Q:\Test\2019\04\25\SO_55855412.cmd
#Echo off
set "test={"this":"is","a":"test"}"
FOR /F "delims=" %%i in ('
powershell -Command "& {$message = '%test:"=\"%'; echo $message}"
') DO SET "message=%%i"
echo %test%
echo %message%
returns here:
> SO_55855412.cmd
{"this":"is","a":"test"}
{"this":"is","a":"test"}
Another solution is to NOT pass %test% as an argument, but to get the variable from the inherited environment
powershell -Command "& {$message = $env:test; echo $message}"
Sadly this doesn't work to pass a variable back, as on terminating the spawned app the inherited environment is discarded.

Using output from a PowerShell command in a windows batch file

I have a path in variable (script parameter) %2.
I need to do the following:
Extract the leaf (last folder from the path) to a variable.
Run the following command: robocopy %2 \\somepath\%leaf
I was told this could be done in PowerShell (cause I've tried going with batch file alone and failed miserably) Here's a pseudocode representation of what I'd like to achieve:
set leaf = powershell -command (split-path %2 -leaf)
robocopy %2 \\somepath\%leaf
Any idea how to write this correctly?
Thank you.
Whenever you want to set a batch variable to the output of a command, use for /f. Here's an example:
#echo off
setlocal
set "psCommand=powershell -command "(split-path '%~2' -leaf)""
for /f "delims=" %%I in ('%psCommand%') do set "leaf=%%I"
echo %leaf%
But this is a terribly inefficient way to retrieve the last folder of a path. Instead of invoking PowerShell, what you should do is this:
#echo off
setlocal
for %%I in ("%~2") do set "leaf=%%~nxI"
echo %leaf%
The %%~dpnxI notation gets
d = drive
p = path
n = name
x = extension
It's traditionally intended for files, rather than directories; but it works just as well for directories anyway. See the last couple of pages of for /? in a console window for complete details.
FOR %%a IN ("%~2") DO FOR %%b IN ("%%~dpa.") DO ECHO %%~nxb
Batch one-liner. Take the parameter (second parameter here), remove any quotes and re-apply them. Select the drive and path, add '.' then select the name and extension of the result making leaf required.
Obviously, if you require this in a variable,
FOR %%a IN ("%~2") DO FOR %%b IN ("%%~dpa.") DO set "leaf=%%~nxb"

Command Prompt "dir /b /s > file.txt" need to remove directories from results

I am using the following command to dump the complete file listings recursively from a directory.
dir /b /s c:\myfolder > c:\mylist.txt
This works fine but it is display the results with the full path as well, beacuse I am using a regex expression on the results I need them to display only the filenames.
Anyone any ideas?
Kind of an old question but if someone stumbles across this hoping for an answer, perhaps this will help them out.
Running this from the windows command line (CMD.exe) use:
setlocal enabledelayedexpansion
for /f "delims=" %a in ('dir /b /s c:\myfolder"') do (#echo %~nxa >>c:\mylist.txt)
endlocal
Running this from a windows .BAT script use:
setlocal enabledelayedexpansion
for /f "delims=" %%a in ('dir /b /s c:\myfolder"') do (#echo %%~nxa >>c:\mylist.txt)
endlocal
The output might look something like this depending on what files are in the folder you're running the code in:
file1.fil
file2.fil
file3.fil
UNDERSTANDING WHAT THE CODE IS DOING
for /f
means to run a loop through files in this case using the dir /b /s command to help get those files names from directories (folders) and subdirectories (subfolders). As stated in the question, this will give you complete paths to the files. So instead of file.txt you will get C:\folder\file.txt.
"delims="
in this case tells the for loop that it wants the variable %a or %%a
to only have 1 folderpath and filename for every loop.
%a (CMD.exe) %%a (.BAT)
as mentioned above is a variable that changes with each loop. so
everytime the command dir /b /s finds a new filename the variable
%%a changes to the filename.
example:
Loop 1: %%a = c:\folder\file1.fil
Loop 2: %%a = c:\folder\file2.fil
dir /b /s
is the command to print out the files of a directory (folder). By
using the /b and /s the questioner is adding additional criteria.
the command dir not only prints out the files and directories
(folders) in that directory (folder) but also some additional
information about the directory.
the /b tells the command dir that it doesn't want the additional
information.. just the filenames.
The /s tells the command dir to include all the files and
subdirectories (subfolders) in that folder.
do
is the part of the loop that tells what to do during that particular
loop. So in this case it is only doing this one command every loop
(#echo %%~nxa >>c:\mylist.txt)
#echo
is a simple command that prints out whatever you want either to your
computer screen or in this case to a txt file by using #echo %%~nxa
>>c:\mylist.txt
the >> before c:\mylist.txt is especially important. Every time a
loop happens it starts a new line in the txt file and writes the
variable to that line. If only one > is specified it will overwrite
the line in the txt file everytime the loop happens. Which will
defeat the purpose of what this script is designed to do.
%~nxa (CMD.exe) %%~nxa (.BAT)
is the variable %%a as mentioned above except it is parsed (edited)
out the way the questioner #fightstarr20 asked for. Instead of
printing out the variable as C:\myfolder\myfile.fil the variable
will print out as myfile.fil
the ~ in %%~nxa tells the program you want to modify the variable
%%a. In this case by adding n and x.
the n in %%~nxa tells the program you want to modify the variable %%a by
excluding the path from the variable.
example.
-variable %%a = C:\folder\filename.fil
-variable %%~na = filename.
-If you notice however that it leaves the extension .fil off of the filename.
the x in %%~nxa tells the program you want to modify the variable %%a
by excluding the path and the filename from the variable, so all you will get is the extension of the filename.
example.
-variable %%a = C:\folder\filename.fil
-variable %%~xa = .fil
so if you combine both of the modifiers n and x to the variable %%a
you will get the full filename including the extension.
example:
-variable %%a = c:\folder\filename.fil
-variable %%~nxa = filename.fil
setlocal enabledelayedexpansion
explained simply is a command that needs to be in the script before
the for loop in order to allow the variable %%a to be modified or "expanded".
endlocal
this turns off the setlocal enabledelayedexpansion command
To get a very helpful explanation and reference for CMD commands I recommend reading ss64.com and for a great forum to get CMD answers I'd recommend dostips.com
Change your regex to get the filename from the entire path.
If you can use powershell, look at Get-ChildItem. You can have more powerful options with it.
Use it like this
dir /b /s C:\myfolder>C:\temp.txt
echo exit>>C:\temp.txt
goto loop
:loop
set /p _x=<temp.txt
findstr /v /c:"%_x%" temp.txt>temp2.txt
type temp2.txt>temp.txt
set _x=%_x:*\=%
echo %_x%>file.txt
if "%_x%" == "exit" (
del temp.txt
del temp2.txt
exit
)
goto loop
You can use for instead of goto if you like, but it will be basicaly the same.
Sorry about the last one...
I know I'm a bit late, but it hurts me that nobody said to take away the /s
dir /b c:\myfolder > c:\mylist.txt
That should do it.
This would surely work, as it works for me.
dir D:(Path to files) /s /b >d:\filelist.txt
You can just use this code:
dir /b > A_fileslist.txt
Copy inside a notepad editor and save as "Fileslist.bat".