【问题标题】:Powershell close file to rename as last step in foreach loopPowershell关闭文件以重命名为foreach循环中的最后一步
【发布时间】:2014-01-07 12:42:15
【问题描述】:

在开始处理下一个文件之前,我正在努力将当前文件重命名为 foreach 循环(依次处理目录中的所有 .csv 文件)中的最后一步。

$rootpath = "C:\Somewhere\Working\"
$List = get-childitem $rootpath | where {$_.extension -eq ".csv"}
foreach($file in $List){
  foreach($Computer in (Import-CSV $rootpath\$file -Header Assett,Group,Location))
    {
    New-ADComputer -Name $Computer.Assett
    }
  Rename-Item $rootpath\$_ -NewName ($rootpath + "\" + $_.BaseName + '.bak')

                       }

返回错误:

Rename-Item : Cannot rename the item at 'C:\Somewhere\Working\' because it is in use.

在 foreach 循环完成后简单地重命名所有 csv 文件,使用以下方法可以按预期工作,但存在自脚本启动后可能已创建另一个输入文件并在未处理的情况下被重命名的风险。

get-childitem -path $rootpath | where {$_.extension -eq ".csv"} | Rename-Item -NewName {$_.BaseName + '.bak'}

我很感激有关如何关闭文件的线索,以便我可以在循环中执行重命名 - 或更好的方法。

【问题讨论】:

    标签: powershell foreach


    【解决方案1】:

    试试这个:

    $rootpath = "C:\Somewhere\Working\"
    
    # Get all csv files (filter is quicker than filtering all files using where)
    get-childitem $rootpath -filter "*.csv" | % {
    
      # import the csv (closes the file)
      $csv = Import-CSV -Path $_ -Header Assett,Group,Location
    
      # loop around file contents
      foreach($Computer in $csv)
      {
        New-ADComputer -Name $Computer.Assett
      }
    
      # rename the file
      Rename-Item $_ -NewName $_.BaseName + '.bak'
    
    }
    

    【讨论】:

    • @user3168914 欢迎来到 Stack Overflow!如果此答案对您有帮助,请务必通过单击左侧的复选标记将其标记为“已接受”。
    猜你喜欢
    • 2014-10-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-10
    • 1970-01-01
    • 1970-01-01
    • 2021-09-14
    • 2021-10-23
    相关资源
    最近更新 更多