删除网络共享上的所有文档文件时,Powershell脚本接收错误

时间:2011-08-10 14:27:51

标签: powershell permissions network-drive

运行脚本时我一直收到错误。它将访问驱动器并按指定将文件名写入我的日志,但由于权限错误,不会删除共享驱动器上的文件。我以管理员身份登录并重新写入了整个驱动器的权限,但仍无法访问。

以下是代码:

$servers = Get-content "D:\Scripts\servers.txt"
$logpath = "d$\Documents"
$logFile = "D:\Scripts\log.txt"
$Date = Get-Date
$error.clear()

foreach($server in $servers){

$fail =" $Date - Failed.  $server did not respond to a ping command.  No files have been deletedfrom $server."
$notpresent = "$Date - Failed.  The specified log folder doesn't seem to be present on $server."
$nologs = "There are no log files to be deleted on $server."

$UNCpath = "\\" +$server+ "\" +$logpath
#Ping server to validate the server is online and accessible
If ($server|?{ (gwmi Win32_PingStatus -Filter "Address='$_'").StatusCode -eq 0 }){

    # The server IS pingable, but the folder does not exist.
    If (!(Test-Path $UNCpath)){Write-output $notpresent `r`n | Out-File $logFile -append}

    # The server IS pingable, and the folder does exist
    else{
        $files = (dir -r $UNCpath -include *.doc,*.pdf,*.docx,*.xls,*.xlsx | where {$_.lastwritetime -le (get-date).adddays(-90) -and !$_.psiscontainer})
        foreach ($file in $files){
            If ($file -eq $null){write-output $nologs `r`n | Out-File $logFile -append}
            Else{
                write-output $file.name | Out-File $logFile -append
                remove-item $file
            }
        }
    }
}

# The server is NOT pingable.
else{Write-output $fail `r`n | Out-File $logFile -append}

If ($error.count -ne "0"){write-output $error | Out-File $logfile -append}
Else{write-output "The log file removal script has completed successfully." | Out-File $logfile -append}'

1 个答案:

答案 0 :(得分:2)

OP发表了自己的回答作为评论。我把它作为一个“真正的”答案放在这里。我强调大胆/斜体。

  

在机器A上运行脚本以访问机器B上的文件。我想   解决方案 - 我只需在remove-item $ file后添加-force。   工作就像一个魅力。 - gp80586 8月10日20:48

请不要对这个答案投票,这不是来自我。