我正在寻找一个PowerShell解决方案,将给定的filename.txt从具有不同域登录凭据的多个服务器unc路径复制到给定文件夹 - 以及根据名称列表重命名文件名(或case / if-stmt)并将每个服务器路径的子文件夹名称导出到csv,其中server和filename为列。
以下是我用于一个服务器的代码 - 我刚刚添加了一些服务器和文件名。
你能帮我做这项工作吗?
我使用的是Powershell版本4。
示例:
$serverNames = @(
"\\serverA\folderA";
"\\serverB\folderA";
"\\serverC\folderA";
)
$fileNames = @(
"fileServerA";
"fileServerB";
"fileServerC";
)
foreach ($element in $serverNames) {
Try {
If (Test-Path Q:){
Remove-PSDrive -Name "Q" -Force
# two server paths are in a different domain,
# so I need a case or if-stmt to pass login credentials
New-PSDrive -Name "Q" -PSProvider FileSystem -Root $element -Credential
}
else{
New-PSDrive -Name "Q" -PSProvider FileSystem -Root $element -Credential
}
#copy filename.txt (always the same name)
robocopy $element\SubFolder\ C:\temp\ filename.txt /R:2 /W:3 /XO
#rename filename.txt according to fileName
Move-Item C:\temp\filename.txt C:\temp\$name.xml -Force
#scan dir and write foldernames (only "first" child folders) to .txt file with the according serverName AND fileName as columns
dir -Directory \\serverA\folderA | Select-Object -ExpandProperty Name
}
}
答案 0 :(得分:3)
如果构建包含所有这些细节的对象数组,该怎么办?然后,您可以使用自己的凭据单独循环每个。
$servers = @()
$servers += [pscustomobject]@{
name = "\\serverA\folderA"
files = "fileServerA"
creds = Get-Credential
}
$servers += [pscustomobject]@{
name = "\\serverB\folderA"
files = "fileServerB"
creds = Get-Credential
}
$servers += [pscustomobject]@{
name = "\\serverC\folderA"
files = "fileServerC"
creds = Get-Credential
}
$servers | ForEach-Object{
#.... Stuff here
}
如果服务器共享凭证,那么您可以在显示的声明之外声明凭证集以多次使用它们。在循环内,您现在可以调用New-PSDrive
并使用参数-Credential $_.creds