如何在 if 语句中写多个 AND OR?

how to write multiple AND OR inside an if statement?

我正在尝试为我的 SharePoint 2013 编写一个 PowerShell 脚本。我的想法是 select 所有引用 /documents/ 文件夹的链接,并且以 .doc, .docx, 或者 .pdf, 所以我写了下面的 if 语句:

$links = $file.ForwardLinks;
foreach ($link in $links) {
    if ($link.url -like '*/Documents/*' -and ($link.url -like '.doc' -or $link.url -like '.docx'  -or $link.url -like '.pdf')) {

我对 -and-or 的使用正确吗?

你的子句组合是正确的:A -and (B -or C -or D)。但是,对于与 -like 运算符的部分匹配,您需要在字符串中使用通配符,否则该运算符的行为将与 -eq 运算符相同。

if (
  $link.url -like '*/Documents/*' -and
  ($link.url -like '*.doc' -or $link.url -like '*.docx' -or $link.url -like '*.pdf')
) {
  ...
}

但是,在您的情况下,更好的方法可能是从 URL 中提取扩展名并检查它是否包含在扩展名列表中:

$extensions = '.doc', '.docx', '.pdf'

$ext = [IO.Path]::GetExtension($link.url)
if ($link.url -like '*/Documents/*' -and $extensions -contains $ext) {
  ...
}