我想检查“ 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
答案 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
。