Franklin
Franklin

Reputation: 905

How to create folders dynamically using PowerShell?

Requirement: I am trying to create the BKP folder in 10 server using the below code but some how it is not creating the new folder in servers.

foreach ($instance in Get-Content "C:\servers\List.txt")
{
    $local = Get-Location;
    $final_local = "C:\BKP";

    if (!$local.Equals("C:\"))
    {
        cd "C:\";
        if ((Test-Path $final_local) -eq 0)
        {
            mkdir $final_local;
            cd $final_local;
        }

        ## if path already exists
        ## DB Connect
    }
}

Upvotes: 2

Views: 610

Answers (3)

Ashu
Ashu

Reputation: 1

Try using the invoke-command i am assuming credentials are needed for the servers you can skip it if it works for you.

$credentials = Get-Credential

$create = { $local = Get-Location;
            $final_local = "C:\BKP"

             if(!$local.Equals("C:\")){
                cd "C:\";
                 if((Test-Path $final_local) -eq 0){
                      New-Item -ItemType Directory -Force -Path "$final_local";
                      cd $final_local;
               }
         ## if path already exists
           ## DB Connect
     }
 }
ForEach ($instance in Get-Content "C:\servers\List.txt")  {
Invoke-Command -ScriptBlock $create -ComputerName $instance -Credential $credentials
}

Upvotes: 0

saftargholi
saftargholi

Reputation: 980

use this command to create directory :

ForEach ($instance in Get-Content "C:\servers\List.txt") 

{ 
$local = Get-Location;
$final_local = "C:\BKP";

if(!$local.Equals("C:\"))
{
    cd "C:\";
    if((Test-Path $final_local) -eq 0)
    {
        New-Item -ItemType Directory -Force -Path "$final_local";
        cd $final_local;

    }

    ## if path already exists
    ## DB Connect

}

} 

Upvotes: 0

JPBlanc
JPBlanc

Reputation: 72680

First : you are using the wrong test, you should use :

if($local.Path -eq "C:\")

The equal method is there to compare objects have a look to :

$local | get-member
$local | fl *

Be careful PowerShell CmdLet return objects.

Second : if $local.Path is equal to "C:\", you create nothing.


Your code would look like :

ForEach ($instance in $(Get-Content "C:\servers\List.txt")) 
{ 
  $local = Get-Location;
  $final_local = "C:\BKP";

  if($local.Path -ne "C:\")
  {
    cd "C:\";
    if((Test-Path $final_local) -eq 0)
    {
      mkdir $final_local;
      cd $final_local;
    }

    ## if path already exists
    ## DB Connect
}

Upvotes: 2

Related Questions