检查路径是PowerShell中的文件夹还是文件
我正在尝试编写一个PowerShell脚本,它将遍历文件夹或文件路径的值列表,然后首先删除文件,然后删除空文件夹 到目前为止,我的剧本是:检查路径是PowerShell中的文件夹还是文件,powershell,Powershell,我正在尝试编写一个PowerShell脚本,它将遍历文件夹或文件路径的值列表,然后首先删除文件,然后删除空文件夹 到目前为止,我的剧本是: [xml]$XmlDocument = Get-Content -Path h:\List_Files.resp.xml $Files = XmlDocument.OUTPUT.databrowse_BrowseResponse.browseResult.dataResultSet.Path 现在我试着测试变量中的每一行,看看它是否是一个文件,然后先删除
[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}
}
}
下一节可以清理子文件夹和文件夹
有什么建议吗?考虑以下代码:
$Files = Get-ChildItem -Path $env:Temp
foreach ($file in $Files)
{
$_.FullName
}
$Files | ForEach {
$_.FullName
}
第一个foreach是用于循环的PowerShell语言命令,第二个foreach是foreach对象
cmdlet的别名,这是完全不同的
在ForEach对象
中,$指向循环中的当前对象,如从$Files
集合导入的,但在第一个ForEach中,$没有任何意义
在foreach循环中,使用循环变量$file
:
foreach ($file in $Files)
{
$file.FullName
}
我认为您的$Files
对象是一个字符串数组:
PS D:\PShell> $Files | ForEach-Object {"{0} {1}" -f $_.Gettype(), $_}
System.String D:\PShell\SO
System.String D:\PShell\SU
System.String D:\PShell\test with spaces
System.String D:\PShell\tests
System.String D:\PShell\addF7.ps1
System.String D:\PShell\cliparser.ps1
不幸的是,在字符串对象上找不到PSIsContainer
属性,而是在文件系统对象上,例如
PS D:\PShell> Get-ChildItem | ForEach-Object {"{0} {1}" -f $_.Gettype(), $_}
System.IO.DirectoryInfo SO
System.IO.DirectoryInfo SU
System.IO.DirectoryInfo test with spaces
System.IO.DirectoryInfo tests
System.IO.FileInfo addF7.ps1
System.IO.FileInfo cliparser.ps1
要从字符串获取文件系统对象,请执行以下操作:
PS D:\PShell> $Files | ForEach-Object {"{0} {1}" -f (Get-Item $_).Gettype(), $_}
System.IO.DirectoryInfo D:\PShell\SO
System.IO.DirectoryInfo D:\PShell\SU
System.IO.DirectoryInfo D:\PShell\test with spaces
System.IO.DirectoryInfo D:\PShell\tests
System.IO.FileInfo D:\PShell\addF7.ps1
System.IO.FileInfo D:\PShell\cliparser.ps1
请尝试下一个代码段:
$Files | ForEach-Object
{
$file = Get-Item $_ ### string to a filesystem object
if ( -not $file.PSIsContainer)
{
Remove-Item $file}
}
}
我找到了解决此问题的方法:使用Test Path
cmdlet,参数-FileType
等于Leaf
,用于检查它是否为文件或容器
用于检查它是否为文件夹:
# 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
我最初找到了解决办法。官方参考是。在循环中使用$file而不是$。