当前位置:网站首页 > 更多 > 玩电脑 > 正文

[玩转系统] 如何在 PowerShell 中检查文件是否存在

作者:精品下载站 日期:2024-12-14 03:39:25 浏览:14 分类:玩电脑

如何在 PowerShell 中检查文件是否存在


在尝试在 PowerShell 中读取或写入文件之前,检查该文件是否确实存在非常重要。这将防止出现错误,从而导致脚本失败。在创建新文件之前或尝试删除文件时进行检查也很重要。

在本文中,我们将了解如何检查文件是否存在以及如何在脚本中使用它的不同方法。

检查文件是否存在

PowerShell 中基本上有两种方法来检查文件是否存在。推荐的方法是使用 Test-Path cmdlet,另一个选项是使用 Get-ChildItem cmdlet。

检查 PowerShell 中文件是否存在的最佳方法是使用 Test-Cmdlet。此 cmdlet 将返回一个布尔值,可以是 $True$False,使其易于在 If-Statement 等内部使用。

如果直接在控制台中运行 cmdlet,您将看到它将仅返回 True 或 False 作为字符串:

Test-Path -Path "c:\temp\random-file.txt"

[玩转系统] 如何在 PowerShell 中检查文件是否存在

一个更实际的示例是在创建新文件之前检查文件是否已存在。我们将路径存储在变量中,并使用 -Not 运算符,仅在 Test-Path 结果为 false 时运行代码:

$path = "C:\temp\File1.txt"

if (-not(Test-Path -path $path)) {
    # File doesn't exists, create the file
    New-Item -Path $path
}

您还可以在文件路径中使用通配符。这允许您做几件事。首先,如果您不知道确切的文件名,那么您可以搜索名称的一部分。

它还允许您检查文件夹中是否存在任何特定文件类型。例如,如果您想知道文件夹中是否有日志文件或bak文件。

# Check for specific file type
if (Test-Path -path "c:\temp\*.bak") {
    Write-Host "Bak file(s) found in the folder"
}

# Check on part of the file name
if (Test-Path -path "c:\temp\la-*.txt") {
    Write-Host "Found one or more files that start with la-"
}

使用 Get-ChildItem

检查 PowerShell 中是否存在文件的另一种方法是使用 Get-ChildItem cmdlet。此 cmdlet 用于从给定目录获取指定项目。但我们也可以使用 cmdlet 来检查文件是否存在。

Get-ChildItemTest-Path cmdlet 之间的区别在于后者仅返回 True False ,而第一个也返回文件信息。

使用 Get-ChildItem cmdlet 时,不能只提供完整的路径和文件名。这样做的原因是,如果该文件不存在,您将收到错误,这将停止您的脚本:

# This won't work if the file doesn't exist
$path = "c:\temp\non-existing-file.txt"
$file = Get-ChildItem -Path $path

if ($file) {
    # Do something with the file information
}else{
    Write-Host "File doesn't exist"
}

[玩转系统] 如何在 PowerShell 中检查文件是否存在

要使用 Get-ChildItem cmdlet 执行此操作,我们需要分别提供要查找的路径和文件名。

我们使用 Filter 属性来过滤掉路径中与我们要查找的文件匹配的文件:

$path = "c:\temp\"
$fileName = "non-existing-file.txt"

# Get all the files in the path and filter on filename
$file = Get-ChildItem -Path $path -Filter $fileName

if ($file) {
    # Do something with the file information
}else{
    Write-Host "File doesn't exist"
}

在子文件夹中搜索

Get-ChildItem cmdlet 的优点是我们还可以在子文件夹中搜索该文件。我们可以添加参数 -recurse,这样它也会在所有嵌套文件夹中搜索:

$path = "c:\temp\"
$fileName = "file1.txt"

$file = Get-ChildItem -Path $path -Filter $fileName -Recurse -File

if ($file) {
    # Do something with the file information
    Write-Host "File created on $($file.CreationTime)"
}

正如您在上面的示例中看到的,我还添加了参数 -File 。在示例中,我搜索了包括扩展名的文件名,那么它并不是真正必要的。但是,当您仅搜索文件名时,也可以包含目录。参数 -File 将结果限制为仅文件。

总结

如果您想检查 PowerShell 中是否存在文件,那么 Test-Path cmdlet 是最佳选择。它根据结果返回 True 或 False,使其成为在脚本内部使用的最佳选择。

当您不知道文件的确切位置或想要检查是否存在一个或多个具有特定名称的文件时,那么 Get-ChildItem 是一个不错的选择。

希望您喜欢这篇文章,如果您有任何疑问,请在下面发表评论。

您需要 登录账户 后才能发表评论

取消回复欢迎 发表评论:

关灯