检查文件内容时,if语句不起作用

时间:2018-11-06 12:26:47

标签: powershell active-directory

我想检查“ C:\ test.txt”是否存在,如果该文件中存在“完成”。如果没有,请设置域策略并创建文件“ C:\ test.txt”并向其写入“完成”。

如果我同时使用两个条件...

if (!(Select-String -Path c:\test.txt -Pattern "Done") -or !(Test-Path C:\log.txt)) {
    Set-ADDefaultDomainPasswordPolicy -Identity ad.contoso.com -ComplexityEnabled $true -MinPasswordLength 7 -MinPasswordAge 1 -MaxPasswordAge 30 -LockoutDuration 00:30:00 -LockoutObservationWindow 00:30:00 -LockoutThreshold 3
    write-output "test" | out-file C:\Users\tfl.AD\Desktop\test.txt -Append
}

然后我得到:

Select-String : Cannot find path 'C:\test.txt' because it does not exist.

Set-ADDefaultDomainPasswordPolicy没有输出,这就是为什么我添加了第二条命令来将Done写入log.txt

的原因

2 个答案:

答案 0 :(得分:3)

As JohnLBevan say in the comments,您应该在-or周围切换子句的顺序。

$filetoCheck = "C:\test.txt"
!(Test-Path $filetoCheck) -or !(Select-String -Path $filetoCheck -Pattern "Done")

因此,如果文件不存在,则无需执行该语句的右侧。您可以从about_logical_operators

获得更长的解释
  

PowerShell逻辑运算符仅评估确定语句真值所需的语句。如果包含and运算符的语句中的左操作数为FALSE,则不评估右操作数。 如果包含or语句的语句中的左侧操作数为TRUE,则对右侧操作数进行求值。因此,可以像使用If语句一样使用这些语句。

重点增强


您还提到了

  

Set-ADDefaultDomainPasswordPolicy没有输出

是的...默认为 。许多cmdlet,例如Set-ADDefaultDomainPasswordPolicy,都支持-PassThru开关。因此,如果您愿意,可以输出通过管道传递的部分或部分对象。

Set-ADDefaultDomainPasswordPolicy -Identity ad.contoso.com .... -PassThru | Export-CSV -NoTypeInformation c:\log.csv -Append

您可能需要在其中添加Select才能获得满足您需求的确切输出。

答案 1 :(得分:0)

-ErrorAction SilentlyContinue添加到Select-String中,例如:

Select-String -Path c:\test.txt -Pattern "Done" -ErrorAction SilentlyContinue

或首先使用Test-Path