有人能帮我吗?我还是powershell的新手,我正在比较我的文档和桌面镜像,以使用几种不同的代码检查我的备份解决方案。下面的这个是为了检查文档/桌面及其镜像文件夹,并告诉我源和目标之间"不同"的文件,并将其输出到同一个output.txt文件中(不确定是否覆盖它(。当我单独为我的文档做这件事时,当我想为我的桌面尝试代码时,它就起作用了——它根本不输出任何东西。有什么建议吗?
function Get-Directories ($path)
{
$PathLength = $path.length
Get-ChildItem $path -exclude *.pst,*.ost,*.iso,*.lnk | % {
Add-Member -InputObject $_ -MemberType NoteProperty -Name RelativePath -Value $_.FullName.substring($PathLength+1)
$_
}
}
Compare-Object (Get-Directories $Folder3) (Get-Directories $Folder4) -Property RelativePath | Sort RelativePath, Name -desc | Out-File C:Usersdesktopoutput.txt
根据您问题的早期修订判断,您的问题不是您的代码根本没有输出任何东西,而是输出有空的Name
属性值。
因此,代码中唯一缺少的是Compare-Object
的-PassThru
开关:
Compare-Object -PassThru (Get-Directories $Folder3) (Get-Directories $Folder4) -Property RelativePath |
Sort RelativePath, Name -desc |
Out-File C:Usersdesktopoutput.txt
在没有-PassThru
的情况下,Compare-Object
输出具有.SideIndicator
属性(指示差异对象对哪一侧独占(的[pscustomobject]
实例,并且仅输出传递给-Property
的比较属性。
- 也就是说,在您最初的尝试中,
Compare-Object
输出对象只有.SideIndicator
和.RelativePath
属性,而没有源自Get-ChildItem
的原始[System.IO.FileInfo]
实例的任何其他属性,如.Name
、.LastWriteTime
使用-PassThru
,原始对象将被传递,并用ETS(扩展类型系统(.SideIndicator
属性进行装饰(以与添加.RelativePath
属性相同的方式进行装饰(,访问.Name
属性稍后将按预期工作。
注:
由于
Out-File
随后会接收到完整的(和修饰的([System.IO.FileInfo]
实例,因此您可能需要事先限制通过Select-Object
调用写入的属性
此外,您可以选择结构化输出格式,例如通过Export-Csv
,因为Out-File
应用的格式仅用于人类观察者,而不用于编程处理。Get-Directories
中的$_.FullName.substring($PathLength+1)
应该是$_.FullName.substring($PathLength)
,否则您将截断第一个字符。
由于在列出文件时不使用-Recurse
,因此可以只使用文件名,而不添加相对路径属性:
$folder1 = gci 'C:Usersusernamedesktop' -exclude *.pst,*.ost,*.iso,*.lnk
$folder2 = gci 'D:desktop' -exclude *.pst,*.ost,*.iso,*.lnk
Compare-Object $folder1 $folder2 -Property Name,Length
Name Length SideIndicator
---- ------ -------------
test.txt 174 =>
test.csv 174 <=
# Alternatively, use -PassThru to keep the whole object:
Compare-Object $folder1 $folder2 -Property Name,Length -PassThru | select SideIndicator,FullName,Length,LastWriteTime
SideIndicator FullName Length LastWriteTime
------------- -------- ------ -------------
=> D:desktop 174 7/14/2021 2:47:09 PM
<= C:Usersusernamedesktop 174 7/14/2021 2:47:09 PM
使用Out-File -Append
将输出附加到文件中。
对于当前脚本的故障排除,请尝试手动检查RelativePath属性是否设置正确:
(Get-Directories $Folder3).RelativePath
(Get-Directories $Folder4).RelativePath
最后,我建议在powershell上使用robocopy进行备份,因为它可以使用备份权限(用于锁定文件(,并且可以一次复制多个文件,但这是个人偏好:
robocopy source destination /b /mir /mt /r:0 /w:0 /b - Runs robocopy in backup mode. Will copy everything as long as you are an Administrator /mir - Mirrors everything from the source to the destination /mt - Copies up to 8 files at a time /r:0 - Sets it to not retry a file, default is like a million retries /w:0 - Sets the time to 0 seconds between retries - default is like 30 seconds
来源:https://community.spiceworks.com/topic/286190-transfer-user-profiles-using-robocopy