【问题标题】:How to check all strings before doing the next step如何在执行下一步之前检查所有字符串
【发布时间】:2020-03-12 06:55:02
【问题描述】:

我想执行字符串比较。我使用了一个 foreach 循环,但我想在比较所有字符串之后执行move-item

我的概念是“如果所有字符串都不匹配,请执行move-item。”

我该怎么做?

这是我目前的代码,但它是“如果匹配,请执行 move-item

$Myfile=dir *my file name*
$directory=dir D:\example    (there are many directory)

foreach($dir in $directory){
 if($dir match $Myfile.basename ){
   move-item $Myfile.fullname -destination D:\example
 }
}

我想在字符串比较之后做move-item,以确保my file name不存在$directory 这是我想要实现的目标

if( ("all of the directory Name") -notmatch $myfile.basename ){
  move-item XXX to XXX
}

如果我使用 -notmatch ,它将在第一次循环时执行移动项目。所以我需要在检查完它们之后做move-item...

【问题讨论】:

  • 能否请您至少向我们提供您的代码的 foreach 循环?
  • @Nicicalu 更新我的代码
  • 上面的代码不行吗?
  • @VivekKumarSingh 嗨,它正在工作。但我想要一个相反的条件
  • 那为什么不用-notmatch 而不是-match

标签: powershell for-loop foreach logic string-comparison


【解决方案1】:

如果有匹配项,您可以将变量设置为 true:

$Myfile=dir *my file name*
$directory=dir D:\example    (there are many directory)

$move = $false
foreach($dir in $directory){
    if($dir match $Myfile.basename ){
        $move = $true
    }
}
if ($move){
    move-item $Myfile.fullname -destination D:\example
}

【讨论】:

  • 没问题!祝你有美好的一天
【解决方案2】:

您可以尝试使用 notcontains 运算符来检查文件基名是否出现在目录 files 中:

$myfile = get-childitem "filepath"
$directory = @(get-childitem "D:\Example" | foreach {$_.basename})
if ($directory -notcontains $myfile.basename) {
  move-item xxx to xxx
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-05
    • 1970-01-01
    • 2018-10-07
    • 1970-01-01
    • 2021-08-25
    相关资源
    最近更新 更多