Search code examples
batch-filecmdmkdirxcopy

Cannot Create New Directory Under C Drive and copy to it


I'm writing a batch file to setup an environment for a project and I need to create a new directory directly under C: drive. Here's what I wrote. First I check that the file is being executed as Admin, then I check if the file already exists, if it doesn't, create it and go to it. Then I do other things.


  :check_Permissions
    echo Administrative permissons required. Detecting permissions...

    net session >nul 2>&1
    if %errorLevel% == 0 (
      echo Success : Administrative permissions confirmed.
    ) else (
      echo Failure : Current permissions inadequate.
      echo Please, run this file as administrator.
    )

    pause >nul

  if not exist "\C:\NewDir" (
    echo NewDir directory will be created under C: drive. 
    mkdir "\C:\NewDir"
    echo Created NewDir Folder under C: drive.
  ) else (
    echo Directory already exists.
    cd C:\NewDir
  )
  if not exist "\C:\NewDir" ( 
    echo Directory was not created. 
  )
  :next

I don't know why the directory is not created since the file is run as admin, it can't be for lack of permissions...

I also need to copy the contents of a remotely shared directory on another server into the newly created folder. XCOPY is not working. Here's the code:


  XCOPY /s "\\remoteserver\directory\sub-dir\directory-to-copy" "C:\NewDir"

Solution

  • With the help of what BoogieMan2718 and Mofi said, I fixed my batch file. Here's the fixed verison :

    :check_Permissions
      echo Administrative permissons required. Detecting permissions...
    
      net session >nul 2>&1
      if %errorLevel% == 0 (
        echo Success : Administrative permissions confirmed.
      ) else (
        echo Failure : Current permissions inadequate.
        echo Please, run this file as administrator.
      )
    
      pause >nul
    
    cd C:\
    if %cd% == "C:\" ( echo In C:\ drive. )
    
    if not exist "C:\NewDir" (
      echo NewDir directory will be created under C: drive. 
      mkdir "C:\NewDir"
      echo Created NewDir Folder under C: drive.
      echo NewDir will now be copied to your computer. This action may take a few minutes...
      ROBOCOPY /E /V /Z "\\remoteServer\pathToDirectoryToCopy" "C:\NewDir"
    ) else (
      echo Directory already exists.
    )
    if not exist "C:\NewDir" ( 
      echo Directory was not created. 
    )
    

    Thank you for your help.