Powershell脚本清空某些文件夹之外的共享文件夹

虽然我必须运行一个脚本来定期删除Windows Server共享文件夹的内容(除了其某些子文件夹及其内容),但我对Powershell专家的了解不是很多。 有人可以帮忙吗?

谢谢

liang88474754 回答:Powershell脚本清空某些文件夹之外的共享文件夹

因此,根据您的陈述,您正在寻找一个脚本来定期枚举文件共享中的文件和文件夹列表。

还必须确保至少不删除某些文件。

您可以使用类似于以下代码的方法来实现此目的:

#Define your SMB server share (You can always add this as an input paramter to the script if you have multiples or even just create an array that contains all of the shares up to you
$SmbServer = "\\FileServer.Contoso.com\TestShare"

#Connect to the SMB Server share (you probably need creds here for your environment but,#for my test it is not needed
Set-Location $SmbServer

#You need a way of determining which files are not to be deleted,for this test,I have files in a share labeled delete and no.delete,this script will delete the "deletes" and bypass the "no.deletes"
$protectedFileString = "no.delete"

#Get the list of files and folders in the directory
$filesList = Get-ChildItem

#Clear the screen for ease of reading
Clear-Host

    #Delete files and bypass protected files
    foreach($file in $filesList)
    {

        #Find protected files
        if($file.Name -Match $protectedFileString)
        {
        #Notify user that we are skipping a protected file due to a match in $protectedFileString
            Write-Host "Skipping " $file.FullName -ForegroundColor Green
        }
        #Find files to be deleted
        else
        {
        #Notify user we are deleting file due to a NOT match of $protectedFileString
            Write-Host "Deleting" $file.FullName -ForegroundColor Yellow
        }

    }

#Is this list of protected and not-protected files correct?
$correct = Read-Host "`nIs this the correct set of files to protect and delete? (Y/N)"

    #If NO,fix the script to correctly identify the files and folders to protect and delete
    if ($correct -eq "N")
    {
        Write-Host "`nFix the script to correctly identify your list of protected files and folders"
        Set-Location c:\
        return
    }
    #else,delete the non-protected files
    else
    {
        foreach($file in $filesList)
        {
           if($file.Name -NotMatch $protectedFileString)
           {
           Remove-Item $file
           }
        }
        #Set location back to the root of c on local machine
        Set-Location c:\
    }

Output should be something like this:
Deleting \\FileServer.Contoso.com\TestShare\delete
Skipping  \\FileServer.Contoso.com\TestShare\no.delete
Deleting \\FileServer.Contoso.comTestShare\delete.txt
Skipping  \\FileServer.Contoso.com\TestShare\no.delete.txt

Is this the correct set of files to protect and delete? (Y/N): Y

Deleting file:  \\FileServer.Contoso.com\TestShare\delete

Deleting file:  \\FileServer.Contoso.com\TestShare\delete.txt

PS C:\> 
本文链接:https://www.f2er.com/3144003.html

大家都在问