Search code examples
powershellshellparsingscriptingpowershell-3.0

Powershell Cannot find drive. A drive with the name ' C' does not exist


Wrote a PS script that reads a .ini file for certain parameters to copy files from folder_a to folder_b,c ..and so on. I get the dreaded "

Cannot find drive. A drive with the name ' C' does not exist."

I have tried carrots, quotations and no luck. Not sure what is causing the failure. I'm curious as to why it put a space before the "C" drive when the .ini file does not contain this.

# Load the contents of the abc_derp.ini file
$iniContent = Get-Content "C:\cfg\abc_derp.ini" -Raw | ConvertFrom-StringData

# Get values from the abc_derp.ini file
$amount = [int]$iniContent["AMT"]
$partialNames = $iniContent["PTN"] -split ";"
$sourceDirectory = $iniContent["SRC"]
$targetDirectories = $iniContent["TRG"] -split ";"
$logFile = $iniContent["LOG"]

# Create log file with timestamp
$logFileName = "log_$(Get-Date -Format yyyy-MM-dd-HHmmss).txt"
$logFilePath = Join-Path $sourceDirectory $logFileName

foreach ($partialName in $partialNames) {
    $filesToCopy = Get-ChildItem -Path $sourceDirectory -Filter "*$partialName*" -File | Select-Object -First $amount

    foreach ($targetDirectory in $targetDirectories) {
        foreach ($fileToCopy in $filesToCopy) {
            $destinationPath = Join-Path $targetDirectory $fileToCopy.Name
            Copy-Item -Path $fileToCopy.FullName -Destination $destinationPath
            $logMessage = "Copied $($fileToCopy.FullName) to $destinationPath"
            $logMessage | Out-File -FilePath $logFilePath -Append
        }
    }
}

Here is the .ini file content being read in by the script

AMT=300
PTN=BURGERS_A; ALIENS_A
SRC=C:\\base\\test\\source
TRG=C:\\base\\test\\dest1; C:\\base\\test\\dest2
LOG=C:\\base\\log

Solution

  • You can use trim() function.

    # Get values from the abc_derp.ini file
    $amount = [int]$iniContent["AMT"]
    $partialNames = $iniContent["PTN"].Split(";").Trim()
    $sourceDirectory = $iniContent["SRC"].Trim()
    $targetDirectories = $iniContent["TRG"].Split(";").Trim()
    $logFile = $iniContent["LOG"].Trim()