我们正在删除大量XP配置文件以节省磁盘空间。存在一些用于XP的配置文件文件夹以及用于Windows 7的.V2的相同用户的文件夹.Id喜欢使用powershell仅返回存在的那些XP配置文件。
到目前为止,这是我的代码
$path = "\\server01\profiles"
#Get User Folder names into variable for ForEach Loop
$UserFolders = get-childitem -path $path\*.V2 | where-object {$_.Psiscontainer -eq "True"} |select-object name
#Loop through folders in Directory
foreach ($UserFolder in $UserFolders){
#remove the last .V2 from the folder name
$UserFolder = $UserFolder.name.substring(0,$UserFolder.name.length-3)
write-output $path\$userfolder
test-path $path\$userfolder #returns True or false
}
我不能让最后一点工作。我怎样才能只显示那些存在的文件夹(返回True)
答案 0 :(得分:1)
您只需要重新排列内容,以便Write-Output
仅在Test-Path
验证路径存在时才会出现foreach ($UserFolder in $UserFolders){
$UserFolder = $UserFolder.name.substring(0,$UserFolder.name.length-3)
if (test-path $path\$userfolder)
{
# Code at this level will only be executed if Test-Path was true.
write-output $path\$userfolder
}
}
。除了if语句之外,我不会在代码中添加任何新内容,例如:
write-output
因此,通过将Test-Path
放入if语句的scope,我们确保只有在{{1}}为真时才会执行。