从不同位置复制相同名称的文件

时间:2019-05-31 19:18:00

标签: powershell

出于事件响应的目的,我正在尝试创建一个将通过所有c:\ users目录并复制ntuser.dat的powershell脚本,然后将其粘贴到该脚本创建的新目录中。我有一些难题,但是我很难把所有的难题放在一起。 我无法解决的一些问题是 1.查找所有c:\ users * \ ntuser.dat并取消隐藏 2.重命名所有ntuser.dat以包括文件夹名称 3.将所有新重命名的ntuser.dat复制到新文件夹中 4.将c:\ users中的所有ntuser.dat重命名为正常。

#1 Unhides the ntuser.dat
$h = gci C:\Users\Test1\NTUSER.DAT -Force
$h.Attributes = $h.Attributes -bxor [System.IO.FileAttributes]::Hidden

#2 Renames ntuser.dat as foldername_ntuser.dat
Get-ChildItem C:\users\test1\ -Filter *.dat -Recurse | Rename-Item -NewName {$_.Directory.Name+'_'+$_.Name}

#3 Creating a new folder and copying the newly named test_ntuser.dat 
$SourceFile = "c:\users\test1\*.dat"
$DestinationFile = "c:\users\user2\desktop\test\test_netuser.dat"
If (Test-Path $DestinationFile) {
    $i = 0
    While (Test-Path $DestinationFile) {
        $i +=1
        $DestinationFile = "c:\users\user2\desktop\test\"
    }
}Else {
    New-Item -ItemType file -Path $DestinationFile -Force
}
Copy-Item -Path $SourceFile -Destination $DestinationFile -Force

最后,我希望脚本取消隐藏,重命名并从以下位置移动到新文件夹 c:\ users \ test1 \ c:\ users \ test2 c:\ users \ test3 无需参考每个用户的路径

1 个答案:

答案 0 :(得分:0)

好吧,这样做会遇到一些问题,因为如果正在使用用户,则将NTUSER.dat加载到内存中。因此,您无法在登录计算机时复制自己的NTUSER.dat。另外,如果有以用户名运行的服务,您将无法获得这些以太币。

因此,让我们回顾一下您想要的东西以及为什么不需要它。

1 查找所有c:\ users \ ntuser.dat并取消隐藏*: 无需取消隐藏原始文件。您只需要取消隐藏副本即可。

2 重命名所有ntuser.dat以包括文件夹名称:无需重命名原始文件,而只是副本。

3 将所有新重命名的ntuser.dat复制到新文件夹中:通过复制本身,您无需任何前两个步骤即可为文件命名。

4 将c:\ users中的所有ntuser.dat重命名为正常:无需执行此步骤,因为从未重命名原始文件。

Function Copy-NTUser($SavePath){
    Get-ChildItem C:\Users\ -Directory | %{
        $Name = $_.Name
        Get-ChildItem "$($_.FullName)\ntuser.dat" -File -force -ErrorAction SilentlyContinue | %{
            $FullName = $_.FullName
            try{
                Copy-Item -Path $_.FullName -Destination "$($SavePath)\$($Name)_$($_.name)" -Force -PassThru  | %{
                    $_.Attributes = $_.Attributes -bxor [System.IO.FileAttributes]::Hidden
                }
            }catch{
                "$($FullName) could not be copied as its currently in use."
            }
        }
    }
}

Copy-NTUser -SavePath C:\Test\NTUSER
相关问题