我正在使用脚本删除远程服务器文件夹的内容:
$Servers = Get-Content "D:\servers.txt"
$Path = "\D$\Test"
$Folders = "\\$Servers$Path"
Get-ChildItem "$Folders" -Recurse -Force | Select-object -Property FullName, LastWriteTime
Foreach ($Item in $Servers)
{
Get-ChildItem -LiteralPath "$Folders" -Recurse -Force | Remove-Item -Recurse -Force -Whatif
}
我需要先列出内容,然后确认再删除。
我不知道是否必须使用Foreach,是否最好在Ineach循环中使用invoke-command或invoke-command等。
对不起,我对PS完全是菜鸟:(
此脚本的最佳结构是什么?
非常感谢:)
答案 0 :(得分:1)
再见@克里斯蒂安·坎切夫
这是最终的脚本:
$Servers = Get-Content "D:\servers.txt"
$Folder = "\D$\Test"
foreach ($Server in $Servers)
{
Write-output `n
Write-host -ForegroundColor Green List of content of "$Folder" in "$server"
Get-ChildItem "\\$server\$Folder" -Force | Select-object -Property FullName, LastWriteTime | Out-File "D:\result.txt"
Get-Content "D:\result.txt"
}
$delete = Read-Host Delete it Y/N?
Write-output `n
if($delete -eq "Y") {
foreach ($Server in $Servers)
{
Get-ChildItem "\\$server\$Folder" -Recurse -Force | Remove-Item -Recurse -Force
if( (Get-ChildItem "\\$server\$Folder" | Measure-Object).Count -eq 0)
{
Write-Host "Files and folders deleted from \\$server\$Folder" -ForegroundColor Green -BackgroundColor Black
}
}
}
elseif ($delete -eq "N") {
Write-Host "Deletion cancelled" -ForegroundColor Yellow -BackgroundColor Black
Write-output `n
}
else {
Write-Host "Script cancelled" -ForegroundColor Red -BackgroundColor
Black
Write-output `n
exit
}
最诚挚的问候;)
答案 1 :(得分:0)
是的,您可以在Get-ChildItem $Folders -Recurse -Force | Select-object -Property FullName, LastWriteTime | Out-File \\YOURPC\c$\Temp\result.txt
之前使用Invoke-Command。出于测试目的,我没有使用它。
希望下面的代码有帮助。
$Servers = Get-Content "C:\Temp\servers.txt"
$Path = "c$\Temp2"
$Folders = "\\$Servers\$Path"
ForEach ($server in $Servers) {
Get-ChildItem $Folders -Recurse -Force | Select-object -Property FullName, LastWriteTime | Out-File \\YOURPC\c$\Temp\result.txt
}
$delete = Read-Host "Should the listed files in C:\Temp\result.txt be deleted Y/N?"
if($delete -eq "Y") {
foreach ($server in $Servers) {
Get-ChildItem -LiteralPath "$Folders" -Recurse -Force | Remove-Item -Recurse -Force -WhatIf
Write-Host "Files/Folders deleted." -ForegroundColor Green -BackgroundColor Black
}
}
elseif ($delete -eq "N") {
Write-Host "Deletion cancelled." -ForegroundColor Yellow -BackgroundColor Black
}
else {
Write-Host "Invalid option, exiting script.." -ForegroundColor Red -BackgroundColor Black
exit
}