![](/img/trans.png)
[英]How to move folder from local drive to Sharepoint folder using PowerShell?
[英]Powershell to bulk move files from local directory to network drive taking folder names
请原谅我,但我对 Powershell 非常陌生,即这是我尝试编写的第一个脚本。 我想将文件从一个驱动器上的文件夹 \Export 的子目录移动到网络驱动器位置上的相同文件夹名称。 我在下面的测试(-WHatIf)示例中的两个位置都使用了我的本地驱动器,但我正在尝试像这样的测试;
$_SourcePath = "C:\exports"
$_dest = "c:\temp\exports\"
$_FileType= @("*.xml")
# Get all files and group by base name
$_command = Get-ChildItem -recurse ($_sourcePath) -include ($_FileType) | Where-Object {$_.CreationTime -lt (Get-Date).AddMinutes(-5)} | ForEach-Object {
"move-Item -Path $($_sourcepath)\$($_.Directory.Name)\$($_.Name) -Destination $($_dest)$($_.Directory.Name)\$($_.Name) -WHatif" }
$_command | ForEach-Object { $_
Invoke-Expression $_command }
所以脚本应该(最终一旦我删除了 -WhatIf)将 all.xml 文件从 \export\folder、\export\folder2 等移动到 temp\export\folder1、temp\export\folder2 等,同时保留相同文件名。
问题是 -destination object 不会将(看起来像有效的)字符串值传递给它。 我敢肯定还有 1001 种其他方法可以做到这一点,但是尝试了几种方法后,我现在已经完全掌握了我的谷歌搜索和知识技能。 谢谢大家。
当我按照编写的方式运行您的代码时,出现此错误:
Invoke-Expression : Cannot convert 'System.Object[]' to the type 'System.String' required by parameter 'Command'.
这是因为Invoke-Expression
需要将$_
作为其参数才能运行每个命令。
在纠正该问题时,我遇到了目标目录不存在的问题 - 但我确定您已经创建了目标目录C:\temp\exports
?
只需让Move-Item -WhatIf
命令在第一个循环内运行,就可以进一步减少代码,这意味着无需构建命令列表以使用invoke-expression
运行 - 但是我可以看到生成的好处如果您希望在某处记录它们或在执行之前查看它们的命令列表(但-WhatIf
提供了该功能)。 这是单循环版本:
$_SourcePath = "C:\exports"
$_dest = "c:\temp\exports\"
$_FileType= @("*.xml")
# Get all files and group by base name
Get-ChildItem -recurse ($_sourcePath) -include ($_FileType) | `
Where-Object {$_.CreationTime -lt (Get-Date).AddMinutes(-5)} | `
ForEach-Object {
move-Item -Path "$_.FullName" `
-Destination "$($_dest)$($_.Directory.Name)\$($_.Name)" `
-WHatif
}
其他变化:
Move-Item
中的输入路径更改为$_.FullName
,因为Get-ChildItem
命令提供完整路径属性作为其 output 的一部分$_command
变量 - 不再需要
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.