我正在尝试编写一个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与等于-FileType
的Leaf
参数一起使用来检查它是否是文件,或者使用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
我最初找到了解决方案here。官方引用是here。
关于powershell - 在PowerShell中检查路径是文件夹还是文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39825440/