循环网络共享并列出所有用户文件夹并创建/删除文件

时间:2017-03-21 13:00:27

标签: loops powershell foreach

我们有1个主要网络共享名称如下,在下划线后有8个位置是" abc $"," def $"," ghi $ "," jkl $"," mno $"," pqr $"," stu $",& #34; VWXYZ $"

根据用户首字母的用户名,创建一个文件夹,其中包含用户主页区域。

示例用户名 - AdamB将被放入Networkshare1_abc$

示例2用户名 - EdwardB将被放入Networkshare1_def$

在此文件夹中,所有用户的列表为文件夹

Networkshare1_abc$  
Networkshare1_def$  
Networkshare1_ghi$  
Networkshare1_jkl$  
Networkshare1_mno$  
Networkshare1_pqr$  
Networkshare1_stu$  
Networkshare1_vwxy$ 

我需要一个

的脚本
  1. 将仅循环用户

  2. 的顶级文件夹列表
  3. 检查文本文件是否存在以及是否删除它(在下面有此工作)

    $Wantedfile = "Networkshare1_stu$\user1\test.txt"
    $timeStamp = (Get-Date -Format "dd-MM-yyyy-hh-mm")
    $FileName = $timeStamp + ".txt"
    
    if ((Test-Path $Wantedfile$FileName) -eq $false) {
      Write-Host "file does not exists"
    } elseif ((Test-Path $Wantedfile$FileName) -eq $true) {
      Write-Host "file present..removing file"
      Remove-Item $Wantedfile$FileName
    }
    
  4. 我正在努力的一点是循环,以及如何让它检查上述位置的每个文件夹尽可能简化。

1 个答案:

答案 0 :(得分:0)

我不确定您的文件是否真的命名为

  

" Networkshare1_stu $ \ USER1 \ test.txt03-21-2017-19-41.txt"

但基本上你需要的是foreach循环。您需要获取顶部文件夹中的所有文件夹。在$directories,您将拥有abc$def$等文件夹。然后,您将遍历每个文件并使用Where-Object搜索文件。

$nameOfFile = "test.txt"
$fullPathFile = "\\Networkshare1_abc$\user1\test.txt"
$directories = Get-ChildItem "\\Networkshare1" -Directory

foreach($directory in $directories)
{
    Write-Host "Searching in $directory.FullName ..."
    $files = Get-ChildItem $directory -Recurse | Where-Object{$_.FullName -like "*$nameOfFile"}
    # or to use fullPathFile
    # $files = Get-ChildItem $directory -Recurse | Where-Object{$_.FullName -eq $fullPathFile}

    foreach($file in $files)
    {
        Write-Host "Removing $file.FullName - continue?"
        Read-Host ""
        Remove-Item $file -Force
    }
}
相关问题