2017-06-22 58 views
1
if ((Get-ChildItem "I:\temp").Length -ne 0) { 
    $locations = (Get-Item "I:\temp"), (Get-ChildItem "I:\temp" -Directory -Recurse) | % { 
     Get-ChildItem -File $_.FullName | 
      Select-String -List -Pattern '^\d{3}-?\d{2}-?\d{4}$' | 
      % Path 
    } 

    if ($locations) { 
     $locations | Out-File "I:\temp\SSN_FILES.txt" 
    } else { 
     Get-ChildItem "I:\temp" -Exclude "fullpath.txt", "SSN_FILES.txt" | Remove-Item 
    } 
} 

我需要确定$locations是否为true。如果它是真的,它执行第一个操作,如果为false,则执行第二个操作。我遇到的问题是,我找不到一种方法来确定$locations是否为真(等于匹配的正则表达式)或不。如何确定一个变量是否返回可比较的语句

+0

'如果($地点)...'测试,看看它的'$ null'或为零,或等效的。您应该查看'-match'运算符(请参阅['Get-Help about_Comparison_Operators'](https://msdn.microsoft.com/zh-cn/powershell/reference/5.1/microsoft.powershell.core/)约/ about_comparison_operators))。 –

+0

[相关](https://blogs.msdn.microsoft.com/powershell/2006/12/24/boolean-values-and-operators/)。 –

回答

2

其中if返回true如果变量存在之前面对这个问题,并且设置为一个非假值(不一定是真实的,但一些价值)。

这样做:

if($locations -eq $true){ # to check it is set to the boolean true 
if($locations -ne $null){ # to check if it contains a value 
+0

我以前就是这样,我不相信这是有效的。原因是我不认为$地点返回布尔语句。我之前有过这个,我不相信这是按照我的意图工作的。 – schnipdip

+0

到文件中的输出是“真”。 '$ locations'应该有等于正则表达式的文件的路径。 – schnipdip

+0

也许你之后的测试是'$ locations -ne $ null'?就好像它包含值一样,应该不为null。如果没有由正则表达式返回的值,应该为null。 – gms0ulman

相关问题