I have a powershell script below which should logically work but throws below error saying "A drive with the name 'E" does not exist." But in fact it exists. This error comes when I input the drive using a variable, but if I input the drive that is path manually like "E:" it will work ok. Do no know what I am doing wrong.
Get-ChildItem : Cannot find drive. A drive with the name 'E' does not exist.
At line:24 char:10
$list = Get-ChildItem -path $CDDriveLetterToText
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
CategoryInfo : ObjectNotFound: (E:String) [Get-ChildItem], DriveNotFoundExcepti
on
FullyQualifiedErrorId : DriveNotFound,Microsoft.PowerShell.Commands.GetChildItemCommand
My code is as below.
Function Image-Windows10 () {
$CDDrives = Get-WmiObject win32_volume | where {$_.DriveType -eq '5'} | Select-Object -Property name
$FlashDrives = get-wmiobject win32_diskdrive | where {$_.InterfaceType -eq 'SCSI'} | select-object -property index, size
[int]$NumberOfFlashDrives=$FlashDrives.Count
[int]$NumberOfCDDrives=$CDDrives.Count
$CDDriveLetterToText = Out-String -inputObject $CDDrives.Get($NumberOfCDDrives-1)
$CDDriveLetterToText = $CDDriveLetterToText.Replace("name","").Replace("----","").Replace("`n","").Replace(" ","")
$list = Get-ChildItem -Path $CDDriveLetterToText
}
Image-Windows10
CodePudding user response:
instead of selecting the name you might want to go for the property DriveLetter
. the parameter -ExpandProperty
will return an array of the specified value - thus no need to manipulate the string'
# get all drive letters from devices of type 'CDRom'
$driveArray = Get-WmiObject win32_volume | where {$_.DriveType -eq '5'} | Select-Object -ExpandProperty DriveLetter
# this array can then be iterated like
foreach($drive in $driveArray) {
$list = Get-ChildItem -Path $drive
}