powershell - 在PowerShell中检查路径是文件夹还是文件

标签 powershell

我正在尝试编写一个PowerShell脚本,该脚本将遍历值列表(文件夹或文件路径),然后首先删除文件,然后删除空文件夹。

到目前为止,我的脚本是:

[xml]$XmlDocument = Get-Content -Path h:\List_Files.resp.xml
$Files =  XmlDocument.OUTPUT.databrowse_BrowseResponse.browseResult.dataResultSet.Path

现在,我尝试测试变量中的每一行,以查看它是否是文件,并首先将其删除,然后再遍历并删除子文件夹和文件夹。这只是一个干净的过程。

我不能完全理解这一点,但我认为我需要以下内容:
foreach ($file in $Files)
{
    if (! $_.PSIsContainer)
    {
        Remove-Item $_.FullName}
    }
}

下一部分可以清理子文件夹和文件夹。

有什么建议么?

最佳答案

我找到了解决此问题的方法:将Test-Path cmdlet与等于-FileTypeLeaf参数一起使用来检查它是否是文件,或者使用Container来检查它是否是文件夹:

# Check if file (works with files with and without extension)
Test-Path -Path 'C:\Demo\FileWithExtension.txt' -PathType Leaf
Test-Path -Path 'C:\Demo\FileWithoutExtension' -PathType Leaf

# Check if folder
Test-Path -Path 'C:\Demo' -PathType Container

Demo

我最初找到了解决方案here。官方引用是here

关于powershell - 在PowerShell中检查路径是文件夹还是文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39825440/

相关文章:

windows - 注册表不匹配 Get-NetAdapter

powershell - 使用 Powershell 同步文件夹 - 新建和编辑的文件

powershell - 如何使用 Start-Process 在 session 中使用本地 PowerShell 变量?

使用 SSL/TLS 安全通道的 Powershell Invoke-WebRequest 失败

powershell - 使用 powershell 将带有模板参数的操作添加到 azure api

azure - 如何从 Azure DevOps 管道将 secret 写入 azure key Vault?

powershell - Windows 7上的Get-ComputerInfo失败

sql-server - 如何从Powershell执行存储过程?

powershell - 如何让 Powershell 在计划任务中执行?

powershell - 使用基于环境变量的路径运行脚本