Скрипт IF EXIST
Помогите, пожалуйста написать скрипт по установке компонента Win7. Условие: если есть файл в директории, то запустить службу, если нет — запустить установку. Что-то начал воять, но даже не знаю на каком языке. Результата нет. Само собой, ведь программист из меня не оч) Заготовка:
Cmd Torrent exist .
Есть очень замечательная утилита WGet Но в наших сетях создали торрент трэкер чтобы обойти.
Paradox СУБД — Table does not exist. File or Directory does not exist
Создал базу данных в Paradox потом начал создавать СУБД, выдало ошибку Table does not exist. File.
Cmake does not exist
Уже очень долгое время не могу найти информацию по данной ошибке, английский немного знаю, читать.
IF EXIST — синтаксис
С чем может быть связано такое? Версия SQL server 2016. Microsoft SQL Server Management.
если ты админ или собираешься им стать,
то для подобных задач можно порекомендовать освоение Ansible
вместо ‘вояния’ на незнамо каком языке.
Решение
lacostewin, всё правильно.
Только переменную нужно раскрывать через знаки %
И скрипт запускать с повышенными привилегиями.
И немного поправить синтаксис.
Заказываю контрольные, курсовые, дипломные и любые другие студенческие работы здесь или здесь.
Shared memory does not exist
Доброе утро! Столкнулся с такой проблемой, Oracle 8.1, лет 20 крутится около 18 схем и начала.
File .prg does not exist
При попытке использовать любые функции или ключевые слова, кроме самых простых, типа «SELECT, FROM.
How can connect to DB that exist on Server when .
How can connect t DB that exist on Server, when my ASP Pages are existing on other Server. Two.
The flow pattern does not exist
Всем привет. суть вопроса проста. Мне необходимо создать Рандомный лист, с которым я буду в.
Check whether a file/folder exists, with cmd command-line (NOT batch script)
I am on the windows console trying to find out whether a file/folder exists or not.
EXIST could be used in batch, but it is not available on the command-line:
5 Answers 5
The solution when the resource is a file it is pretty straight-forward as indicated by others:
Unfortunately, the above does not work for directories. The EXIST function returns the same result for both missing and present folders. Fortunately, there is an obscure workaround:
It turns out that to support constructs like appending >NUL on command statements, there is a sort of virtual file named «NUL» in every directory. Checking for its existence is equivalent to a check for the directory’s existence.
This behavior is documented in a Microsoft knowledge base article ( https://support.microsoft.com/en-us/kb/65994 ) and I have confirmed its behavior on FreeDOS 1.1 and in a Windows 7 command shell.
EXTRA: The KB article indicates this technique can also be used to see if a drive is present. In the case of checking for drive existence, however, caveats exist:
An Abort, Retry, Fail? error occurs if the drive is not formatted.
Using this technique to check for drive existence depends on device driver implementation and may not always work.
How to test if a path is a file or directory in Windows batch file?
I searched here, found someone using this
but didn’t work, when %1==c:\this is a file with spaces.csproj , the test still success, which means it will still be treated as a folder.
anyone knows the answer, i guess this is a very common problem and Windows has existed for many many years, it should have a very simple solution.
6 Answers 6
I know the if exist path\nul test for a folder used to work on MS-DOS. I don’t know if it was broken with the introduction of long file names.
I knew that if exist «long path\nul» does not work on Windows batch. I did not realize until today that if exist path\nul works on Vista and beyond as long as path is in the short 8.3 form.
The original code appears to work on Vista. It seems like it should work on XP as well, but I believe the following XP bug is getting in the way: Batch parameter %
The original code does not need the FOR loop, it could simply use %
Here is a variation that fully classifies a path as INVALID, FILE or FOLDER. It works on Vista, but does NOT work on XP because of the %
s1 bug. I’m not sure how it performs on MS-DOS.
EDIT 2015-12-08: There are a number of Windows situations where this fails
I believe this variation will work with nearly all versions of Microsoft batch, including MS-DOS and XP. (it obviously won’t work on early versions of DOS that don’t support PUSHD)
UPDATE 2014-12-26
I’m pretty sure the following will work on all versions of Windows from XP onward, but I have only tested on Win 7.
Edit 2015-12-08: This can fail on network drives because the folder test can falsely report a file as a folder
UPDATE 2015-12-08
Finally — a test that truly should work on any Windows version from XP onward, including with network drives and UNC paths
Note — This technique is intended to be used for a path without any wildcards (a single specific file or folder). If the provided path includes one or more wildcards, then it provides the result for the first file or folder that the file system encounters. Identical directory structures may give different sort order results depending on the underlying file system (FAT32, NTFS, etc.)
How to verify if a file exists in a batch file?
I have to create a .BAT file that does this:
- If C:\myprogram\sync\data.handler exists, exit;
- If C:\myprogram\html\data.sql does not exist, exit;
- In C:\myprogram\sync\ delete all files and folders except ( test , test3 and test2 )
- Copy C:\myprogram\html\data.sql to C:\myprogram\sync\
- Call other batch file with option sync.bat myprogram.ini .
If it was in the Bash environment it was easy for me, but I do not know how to test if a file or folder exists and if it is a file or folder.
3 Answers 3
You can use IF EXIST to check for a file:
If you do not need an «else», you can do something like this:
Here’s a working example of searching for a file or a folder:
Type IF /? to get help about if, it clearly explains how to use IF EXIST.
To delete a complete tree except some folders, see the answer of this question: Windows batch script to delete everything in a folder except one
Finally copying just means calling COPY and calling another bat file can be done like this:
Here is a good example on how to do a command if a file does or does not exist:
We will take those three files and put it in a temporary place. After deleting the folder, it will restore those three files.
Use the XCOPY command:
I will explain what the /c /d /h /e /i /y means:
Call other batch file with option sync.bat myprogram.ini.
I am not sure what you mean by this, but if you just want to open both of these files you just put the path of the file like
If it was in the Bash environment it was easy for me, but I do not know how to test if a file or folder exists and if it is a file or folder.
You are using a batch file. You mentioned earlier you have to create a .bat file to use this:
I have to create a .BAT file that does this:
CMD — If exists
The below commands (with debug lines added — indented) should only redirect the echo’s output to a file, should it already exist, according to my understanding.
However, it would seem that if exist %test0% always fills the file (creating it if non-existant) with the echo’s output.
Does anyone know what is wrong?
And the file gets created(!)
EDIT: This above was a simplified example, and unfortunately MSalters answer doesn’t help me solve the full command (I had hoped it would). The full one line if statement is:
if exist %test0% (echo.&echo.&echo ————————————————-&echo.&echo.) else (set /p .= >%test0%&set errorlevel=0||set errorlevel=1
How would I have whichever condition of the if matched output to the file (Hopefully with only one reference to the file, i.e., not one in each if conditional), and have the errorlevel set based on the exist ance of the file?
Could anyone help with the actual full command issue?
2 Answers 2
You should never set ERRORLEVEL directly. That name is reserved for reporting on the results of the prior command. When you set the value directly, you override the intended functionality and it ceases to expand to the actual ERRORLEVEL, it expands to the value you set instead. That can break all kinds of code.
You can force the ERRORLEVEL to a value by running a command with known result, redirecting output to nul if necessary: ver >nul sets ERRORLEVEL to 0, set /p .= sets ERRORLEVEL to 1.
You can force the ERRORLEVEL to any particular value of your choosing by using cmd /c exit /b N , where N is an integral value.
You also have faulty logic. Your IF command succeeds (has no error) regardless whether the condition evaluates to TRUE or FALSE. If you want to set the ERRORLEVEL, then you need to do it within your parenthesized blocks.
There is nothing wrong with putting everything on one line, but I find the code easier to read when using multiple lines for complex statements like yours. I believe the following is what you are looking for.
Edit in response to comments