I have tested a lot of commands and I seem to have come to a road block and looking for assistance.
- This code I have works when I run this on ComputerA. ComputerA has the HomeFolder directory located on the D: drive. The text file has 2 machine names for now for testing purposes. A folder called "NewCreation" is then created to both ComputerB and ComputerC. Which is perfect.
Get-Content "D:\HomeFolder\MachineNames.txt" | %{New-Item -ItemType Directory -Path "\\$_\d$\NewCreation" -Force -Verbose}
But the issue is when there's a computer in the environment that has this folder(NewCreation) already existed with tons of other sub-folders and files I am looking to make an if statement that if this folder exist, I want to rename it to "NewCreation_OLD" and create the folder "NewCreation".
- Here's my attempt and I know it's not perfect or it doesn't work I've spend hours and searching and I'm wasting a lot of time. So yeah... I would greatly appreciate all the pointers and help from everyone!
$Folder = Get-Content "D:\HomeFolder\MachineNames.txt"
foreach ($Folders in $Folder){
if (Test-Path -Path "\\$_\d$\NewCreation")
{
Rename-Item -Path "\\$_\d$\NewCreation" -NewName NewCreation_OLD -Force -Verbose
New-Item -Path "\\$_\d$\" -Name NewCreation -ItemType Directory -Force -Verbose
}
else{
Write-Host "Do something else"
}
}
CodePudding user response:
You were very close, the only real issue was the use of the automatic variable $_ (also known as $PSItem) instead of the $item from your $collection:
foreach ($<item> in $<collection>){<statement list>}
I have added some comments for guidance.
# $computers instead of $Folder, for clarity
$computers = Get-Content "D:\HomeFolder\MachineNames.txt"
foreach ($computer in $computers)
{
# If this folder exists in this host
if (Test-Path -Path "\\$computer\d$\NewCreation")
{
# Rename it
Rename-Item -Path "\\$computer\d$\NewCreation" -NewName "NewCreation_OLD" -Force -Verbose
}
# Here we can assume that the folder was not there or was renamed, so we can create it
New-Item -Path "\\$computer\d$\" -Name NewCreation -ItemType Directory -Force -Verbose
}
