Connect and share knowledge within a single location that is structured and easy to search. Misspellings are irritating, aren't they? Check your spelling of empty , but then also try this:. Notice incidentally that I have swapped the roles of empty. While the other answers are correct, using the "-s" option will also show the file is empty even if the file does not exist.
By adding this additional check "-f" to see if the file exists first, we ensure the result is correct. More than once I have had misread the top answer here to mean the opposite. Anyway, thought I'd share! How are we doing? Please help us improve Stack Overflow.
Take our short survey. Stack Overflow for Teams — Collaborate and share knowledge with a private group. Create a free Team What is Teams? Collectives on Stack Overflow. Learn more. If you want your script to be portable, you should prefer using the old test [ command, which is available on all POSIX shells.
The new upgraded version of the test command [[ double brackets is supported on most modern systems using Bash, Zsh, and Ksh as a default shell. When checking if a file exists, the most commonly used FILE operators are -e and -f.
The first one will check whether a file exists regardless of the type, while the second one will return true only if the FILE is a regular file not a directory or a device. NET method, you can also use ternary operations such as the example below. Instead of showing the default true or false results, you may customize the result message with a shorter implementation. This example script updates the text file by appending a new GUID value. However, the content update only happens if the file exists.
Otherwise, the script shows a message and does nothing else. Copy the script below and save it as Update-FileContents.
Then run the script in PowerShell to test. You can see in the screenshot below, the script updated the file during each run.
The update happened because the [System. It is good practice to check the presence of a file before making any file-related modifications. As well as the [System. NET method. The examples showed you how to use techniques and how to combine them with error-handling logic. Stop enduring those error messages. Overcome them by adding code to check if a file exists before any file-related operations.
Get this interactive comic book to learn how Veeam and AWS can help you fight ransomware, data sprawl, rising cloud costs, unforeseen data loss and make you a hero! ATA is known for its high-quality written tutorials in the form of blog posts. Improve this question. Siva 8, 8 8 gold badges 50 50 silver badges 82 82 bronze badges. Steven Audy Steven Audy 43 1 1 gold badge 1 1 silver badge 7 7 bronze badges.
Did you mean to use -n? Add a comment. Active Oldest Votes. Improve this answer. Siva Siva 8, 8 8 gold badges 50 50 silver badges 82 82 bronze badges.
0コメント