简体   繁体   中英

CMD - redirect cd command output into new file

Is it Possible to Redirect cd command output into new file here is list of paths in C:\\ Partition

C:\Inetpub\vhosts\apnat\httpdocs
C:\Inetpub\vhosts\interline\httpdocs
C:\Inetpub\vhosts\dentin\httpdocs
C:\Inetpub\vhosts\archm\httpdocs
C:\Inetpub\vhosts\archacom\httpdocs
C:\Inetpub\vhosts\arowmom\httpdocs
C:\Inetpub\vhosts\myrin\httpdocs
...

Some Paths Are Openable with no error and some are not with Access Denied error i am trying to save all openable paths into new file and trying with this command

for /f %x in (paths.txt) do cd %x | echo %cd%>>C:\users\vb3\results.txt
for /f %x in (paths.txt) do (cd %x & echo %cd%>>C:\users\vb3\results.txt)

i am trying with these commands but the output file is empty or filled with same line

C:\Windows\SysWOW64\inetsrv
C:\Windows\SysWOW64\inetsrv
C:\Windows\SysWOW64\inetsrv
C:\Windows\SysWOW64\inetsrv
...
...

You have a delayed expansion problem (which causes %cd% to be the same value for each run).

But you don't really need it when you use conditional execution:

for /f "delims=" %x in (paths.txt) do cd "%x" 2>nul && echo %x >> "C:\users\vb3\results.txt"

Writing to a file line for line is slow (as the file has to be opened, read until the end of the file, written to, and closed for each single line (you probably won't notice it with just a few lines, but with thousands of lines, it is huge (we are speaking of a factor of 1000 and more). Better redirect the whole output in one go (in short: (loop with many echoes here)>file.txt instead of loop with many "echo>>file.txt" )

(for /f "delims=" %x in (paths.txt) do cd "%x" 2>nul && echo %x)>"C:\users\vb3\results.txt"

&& serves as "if previous command ( cd ... ) was successful, then".

If you need the oposite, use || ("if previous command failed, then"):

(for /f "delims=" %x in (paths.txt) do cd "%x" 2>nul || echo %x>"C:\users\vb3\denied.txt")

2>nul redirects any error messages ( access is denied ) to "nirvana" (suppresses them)
delims= processes the whole line (without it, it would just output the first word). Essential when there are spaces in the file- or folder-names.

Another way to do it using PowerShell. Perhaps more understandable and maintainable.

$ResultsFile = 'C:\users\vb3\results.txt'
if (Test-Path -Path $ResultsFile) { Remove-Item -Path $ResultsFile }
Get-Content -Path '.\paths.txt' |
    ForEach-Object {
        if ((Test-Path -Path $_) -and (Get-ChildItem -Path $_ -ErrorAction SilentlyContinue)) {
            Out-File -FilePath $ResultsFile -Encoding ascii -Append -InputObject $_
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM