我是PowerShell的新手,但我写了一个脚本,在每个用户网络主目录中重命名4个文件夹 . 用户SAM帐户是从文本文件中提取的 .
脚本可以工作,但是在脚本运行后我得到这样的错误 . 我为什么要这个?
“Get-Item:找不到路径'C:\ Portability',因为它不存在 . 在行:3 char:5 Get-Item -Path”$ line \ Portability“| Rename-Item -NewName”Portability $(Get - ... ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~分类信息:ObjectNotFound:(C:\ Portability:String) [Get-Item],ItemNotFoundException FullyQualifiedErrorId:PathNotFound,Microsoft.PowerShell.Commands.GetItemCommand“
这是脚本:
#Import AD PowerShell Module
Import-Module ActiveDirectory
#Get Home Path for each user
$GetHD = Get-Content C:\Temp\UserList.txt | ForEach {Get-ADUser $_ -properties HomeDirectory | Select HomeDirectory} > C:\temp\UserInfo.txt
#Copy list of paths to C:\temp\dir.txt and safe content to variable $hdirpath
Get-Content C:\temp\UserInfo.txt | Select-Object -Skip 3 | Foreach {$_.TrimEnd()} | Out-File C:\Temp\dir.txt
$hdirpath = Get-Content C:\Temp\dir.txt
#Rename folder if exist adding current date at end of folder
ForEach ($line in $hdirpath) {
Get-Item -Path "$line\Portability" | Rename-Item -NewName "Portability$(Get-Date -Format ""MMddyyyy"")" -WhatIf
Get-Item -Path "$line\Profile" | Rename-Item -NewName "Profile$(Get-Date -Format ""MMddyyyy"")" -WhatIf
Get-Item -Path "$line\Profile.v2" | Rename-Item -NewName "Profile.v2$(Get-Date -Format ""MMddyyyy"")" -WhatIf
Get-Item -Path "$line\TSProfile.v2" | Rename-Item -NewName "TSProfile.v2$(Get-Date -Format ""MMddyyyy"")" -WhatIf
}
1 回答
您说“重命名文件夹(如果存在)”,但在对它们运行命令之前不检查文件夹是否存在,这就是您收到错误的原因:
您可以使用简单的
if
和Test-Path
更新代码,以检查文件夹是否存在,只有在尝试重命名时:EDIT:
这是一个版本,它不需要多个txt文件作为临时步骤,并添加了一个重命名功能,以避免重复代码行 .
我确定你为什么要跳过列表中的前三个用户(
Select-Object -Skip 3
),或者为什么需要删除任何尾随空格(Foreach {$_.TrimEnd()}
),因为这意味着当您尝试重命名时HomeDirectory路径将不匹配 .注意:我没有完全测试它,但是在单独测试时它可以正常工作 .