EDUCBA

EDUCBA

MENUMENU
  • Explore
    • Lifetime Membership
    • All in One Bundles
    • Fresh Entries
    • Finance
    • Data Science
    • Programming and Dev
    • Excel
    • Marketing
    • HR
    • PDP
    • VFX and Design
    • Project Management
    • Exam Prep
    • All Courses
  • Blog
  • Enterprise
  • Free Courses
  • Login
Home Data Science Data Science Tutorials PowerShell Tutorial PowerShell if File Exists

PowerShell if File Exists

Updated March 10, 2023

PowerShell if File Exists

Introduction to PowerShell if File Exists

There are scenarios in PowerShell wherein a new file needs to be created. However, before creating the file it is advisable to check if the file exists or not so that the existing file will not be overwritten or if properly not happened an error might be thrown. To achieve this in PowerShell there are many ways that will be covered in this article. The most popular method is using Test-Path cmdlet. The other methods include Get-Item and Get-ChildItem.

Start Your Free Data Science Course

Hadoop, Data Science, Statistics & others

Syntax of PowerShell if File Exists

Syntax of powershell if file exists is given below:

Test-Path Cmdlet Syntax: This cmdlet is used to check not only a file exists but also it can be used to check if a path exists. It returns true if there is a match. An error is returned if the path is null.

NAME
Test-Path
SYNTAX
Test-Path [-Path] <string[]> [-Filter <string>] [-Include <string[]>] [-Exclude <string[]>] [-PathType {Any | Container
| Leaf}] [-IsValid] [-Credential <pscredential>] [-UseTransaction] [-OlderThan <datetime>] [-NewerThan <datetime>] [<CommonParameters>] Test-Path -LiteralPath <string[]> [-Filter <string>] [-Include <string[]>] [-Exclude <string[]>] [-PathType {Any |
Container | Leaf}] [-IsValid] [-Credential <pscredential>] [-UseTransaction] [-OlderThan <datetime>] [-NewerThan
<datetime>]  [<CommonParameters>] ALIASES
None

  • -Credential: This parameter fetches the credential that will be used to execute this cmdlet. The data type of this parameter is PSCredentail. None is the default value. It can process pipeline input however wildcard characters are not permitted.
  • -Exclude: This is used to exclude things from search check. String is the data type of this parameter. None is the default esteem. It doesn’t process pipeline input whereas wildcard characters are accepted.
  • -Filter: This is used to apply conditional filtering on the input. String is the data type of this parameter. None is the default esteem. It doesn’t process pipeline input whereas wildcard characters are accepted.
  • -Include: This includes the files and paths that needs to be checked for existence. String is the datatype of this parameter. None is the default esteem. It doesn’t recognize pipeline input and wild card characters are accepted.
  • -IsValid: This checks if the path or the file is valid or not. True is returned is the syntax if valid else false. Switch is the data type of this parameter. None is the default esteem. Pipeline input is not accepted, and wildcard characters are also not permitted.
  • -LiteralPath: This is also like the path to be tested. The only difference is that the value of this parameter is considered literal. String is the datatype of this parameter. Pspath and LP are the other alias for this. None is the default esteem. Pipeline input is accepted whereas wildcard characters are not permitted.
  • -NewerThan: This denotes the timeline that is greater that needs to be checked for the files and path. The data type of this parameter is datetime. None is the default esteem. Pipeline input is not recognized, and wild card characters are also not permitted.
  • -OlderThan: This denotes the timeline that is older that needs to be checked for the files and path. The data type of this parameter is datetime. None is the default esteem. Pipeline input is not recognized, and wild card characters are also not permitted.
  • -Pathtype: This denotes the type of path in which the file is being searched. It can accept containers, leaf, and any as values. An example of a container is a directory; an example of a leaf is a file, and any can be either of both. The data type of this parameter is TestPathType. The alias is Type. None is the default esteem. It doesn’t accept pipeline input and doesn’t accept wildcard characters.
  • Using .Net Method: In dot net class, there is a method called as exists(). This checks whether a file is there and if it exists true is returned.
  • Using Get-Item and Get-ChildItem: This is used to check for paths or files in one or more locations. In case if the file is not there an error is thrown.

Syntax:

NAME
Get-Item
SYNTAX
Get-Item [-Path] <string[]> [-Filter <string>] [-Include <string[]>] [-Exclude <string[]>] [-Force] [-Credential
<pscredential>] [-UseTransaction] [-Stream <string[]>]  [<CommonParameters>] Get-Item -LiteralPath <string[]> [-Filter <string>] [-Include <string[]>] [-Exclude <string[]>] [-Force] [-Credential
<pscredential>] [-UseTransaction] [-Stream <string[]>]  [<CommonParameters>] ALIASES
gi
AME
Get-ChildItem
SYNTAX
Get-ChildItem [[-Path] <string[]>] [[-Filter] <string>] [-Include <string[]>] [-Exclude <string[]>] [-Recurse] [-Depth
<uint32>] [-Force] [-Name] [-UseTransaction] [-Attributes {ReadOnly | Hidden | System | Directory | Archive | Device |
Normal | Temporary | SparseFile | ReparsePoint | Compressed | Offline | NotContentIndexed | Encrypted | IntegrityStream
| NoScrubData}] [-Directory] [-File] [-Hidden] [-ReadOnly] [-System]  [<CommonParameters>] Get-ChildItem [[-Filter] <string>] -LiteralPath <string[]> [-Include <string[]>] [-Exclude <string[]>] [-Recurse] [-Depth <uint32>] [-Force] [-Name] [-UseTransaction] [-Attributes {ReadOnly | Hidden | System | Directory | Archive |
Device | Normal | Temporary | SparseFile | ReparsePoint | Compressed | Offline | NotContentIndexed | Encrypted |
IntegrityStream | NoScrubData}] [-Directory] [-File] [-Hidden] [-ReadOnly] [-System]  [<CommonParameters>] ALIASES
gci
ls
dir

Examples of PowerShell if File Exists

Following are the examples are given below:

Example #1

Input:

Write-Host "Demo of if file exists" -ForegroundColor Green
$fi = 'c:\test.txt'
if (-not(Test-Path -Path $fi  -PathType Leaf)) {
try {
$null = New-Item -ItemType File -Path $fi  -Force -ErrorAction Stop
Write-Host "The file [$fi ] is created." -ForegroundColor Green
}
catch {
throw $_.Exception.Message
}
}
else {
Write-Host "Cannot create [$fi] because it is already available." -ForegroundColor Red
}

Output:

PowerShell if File Exists-1.1

PowerShell if File Exists-1.2

In the above example, when the script is run for the first time, the file was not there, and it got created. When the script is run for the second time since the file already exists it is not created.

Example #2

Input:

write-host “Demo of file check using get the item and get child item” -ForegroundColor Green

$fi = 'c:\test.txt'
Get-Item -Path $fi
Get-ChildItem -Path $fi
$fi1='c:\test1.txt'
Get-Item -Path $fi1
Get-ChildItem -Path $fi1
Write-Host "Demo of if file using net method" -ForegroundColor Green
[System.IO.File]::Exists($fi)
[System.IO.File]::Exists($fi1)

Output:

PowerShell if File Exists-1.3

Conclusion

Thus, the article showed in detail different ways of checking if a file exists in PowerShell. It explained the syntax of each cmdlet, its parameters, and its usage with appropriate examples. To learn more in detail it is better to write sample scripts and execute them.

Recommended Articles

This is a guide to PowerShell if File Exists. Here we also discuss the introduction and syntax of powershell if file exists along with different examples and its code implementation. You may also have a look at the following articles to learn more –

  1. PowerShell block Comment
  2. PowerShell Location
  3. PowerShell New Line
  4. PowerShell prompt for input
ADVERTISEMENT
All in One Excel VBA Bundle
500+ Hours of HD Videos
15 Learning Paths
120+ Courses
Verifiable Certificate of Completion
Lifetime Access
ADVERTISEMENT
Financial Analyst Masters Training Program
2000+ Hours of HD Videos
43 Learning Paths
550+ Courses
Verifiable Certificate of Completion
Lifetime Access
ADVERTISEMENT
All in One Data Science Bundle
2000+ Hour of HD Videos
80 Learning Paths
400+ Courses
Verifiable Certificate of Completion
Lifetime Access
ADVERTISEMENT
All in One Software Development Bundle
5000+ Hours of HD Videos
149 Learning Paths
1050+ Courses
Verifiable Certificate of Completion
Lifetime Access
Primary Sidebar
Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Live Classes
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Database Management
  • Machine Learning
  • All Tutorials
Certification Courses
  • All Courses
  • Data Science Course - All in One Bundle
  • Machine Learning Course
  • Hadoop Certification Training
  • Cloud Computing Training Course
  • R Programming Course
  • AWS Training Course
  • SAS Training Course

ISO 10004:2018 & ISO 9001:2015 Certified

© 2023 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you

Let’s Get Started

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA
Free Data Science Course

Hadoop, Data Science, Statistics & others

By continuing above step, you agree to our Terms of Use and Privacy Policy.
*Please provide your correct email id. Login details for this Free course will be emailed to you

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA Login

Forgot Password?

By signing up, you agree to our Terms of Use and Privacy Policy.

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

Loading . . .
Quiz
Question:

Answer:

Quiz Result
Total QuestionsCorrect AnswersWrong AnswersPercentage

Explore 1000+ varieties of Mock tests View more

🚀 Extended Cyber Monday Price Drop! All in One Universal Bundle (3700+ Courses) @ 🎁 90% OFF - Ends in ENROLL NOW