Get-ChildItem not detecting the existing drives - powershell

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

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
}

Related

Check if registry key is present before Get-ItemProperty [duplicate]

This question already has answers here:
Check if a Registry Path Exists in Remote Machine
(4 answers)
Test if registry value exists
(13 answers)
Closed 3 months ago.
I've been trying to create a script that checks which applications are installed on a remote server. So far I've been able to get it working to do the job when everything is in place.
However, one of my servers are a bit broken and the "uninstall" registry key is missing from the registry.
So before doing Get-ItemProperty "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\*" and Get-ItemProperty "HKLM:\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\*" I want to check if the registry key is present and if that isn't the case, I wish to run Get-WmiObject -Query "select * from win32_product"
Currently when I run it on the machine that is missing the "Uninstall" registry key I get
Cannot find path 'HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall' because it does not exist.
+ CategoryInfo : ObjectNotFound: (HKEY_LOCAL_MACH...rsion\Uninstall:String) [Get-ChildItem], ItemNotFoundException
+ FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.GetChildItemCommand
+ PSComputerName : ServerName001
Current script:
# Change to computer you wish to search.
$ComputerName = "ServerName001"
$ScriptPath = Get-Location
$GetWmiObject_Win32Product = $ScriptPath.ToString() + $ComputerName + "_Get-WmiObject-win32_Product.csv"
$GetItemProperty = $ScriptPath.ToString() + $ComputerName + "_Get-ItemProperty.csv"
Invoke-Command -ComputerName $ComputerName -ScriptBlock {
$directoryInfo64bit = Get-ChildItem HKLM:\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall | Measure-Object
$directoryInfo32bit = Get-ChildItem HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall | Measure-Object
$Apps = #()
if($directoryInfo64bit.count -eq 0){
Write-Output "No 64bit Uninstall folder"
}else{
$Apps += Get-ItemProperty "HKLM:\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\*"
}
if($directoryInfo32bit.count -eq 0){
Write-Output "No 32bit Uninstall folder"
}else{
$Apps += Get-ItemProperty "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\*"
}
$Apps | Select-Object -Property DisplayName, Publisher, DisplayVersion, InstallDate, InstallLocation, PSComputerName
} | Export-Csv -Path $GetItemProperty -NoTypeInformation -Encoding utf8
Get-WmiObject -Query "select * from win32_product" -ComputerName $ComputerName | Select-Object -Property Name, Vendor, Version, PSComputerName | Export-Csv -Path $GetWmiObject_Win32Product -NoTypeInformation -Encoding utf8

unable to append error messages to csv with powershell export-csv

I have written the following sample script that lets me collect information for all servers in the environment. However, i do not have access to all servers and sometimes i get error that i want to catch and store in the result.csv file.
$Servers = Get-Content .\servers.txt
foreach ($Server in $Servers){
try {
Get-CimInstance Win32_OperatingSystem -ComputerName $server -ErrorAction Stop | Select-Object CSName, Caption, Version, OSArchitecture, InstallDate, LastBootUpTime | Export-Csv -append .\result.csv
} catch {
$Error[0].Exception | Export-csv -Append .\resulttest.csv
}
}
Normally the script works but when i try to save the errors i get the message:
Export-csv : Cannot append CSV content to the following file:
.\resulttest.csv. The appended object does not have a property that
corresponds to the following column: CSName. To proceed with
mismatched properties, add the -Force switch and retry. At
C:\temp\script\serverdata.ps1:10 char:26
+ $Error[0].Exception | Export-csv -Append .\resulttest.csv
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidData: (CSName:String) [Export-Csv], InvalidOperationException
+ FullyQual
Any ideas on how to go around this?
You might try this:
$Servers = Get-Content .\servers.txt
$Servers | ForEach-Object {
$server = $_
try {
Get-CimInstance Win32_OperatingSystem -ComputerName $server -ErrorAction Stop |
Select-Object CSName, Caption, Version, OSArchitecture, InstallDate, LastBootUpTime, #{Name = 'Result'; Expression = {'OK'}}
}
catch {
# output an object with the same properties.
"" | Select-Object #{Name = 'CSName'; Expression = {$server}},
Caption, Version, OSArchitecture, InstallDate, LastBootUpTime,
#{Name = 'Result'; Expression = {'ERROR: {0}' -f $Error[0].Exception.Message}}
}
} | Export-Csv .\result.csv -NoTypeInformation

Check remote profile size

I am trying to figure out how to get correct numbers while checking size of user profiles.
While executing this code remotely, I get wrong numbers.
Invoke-Command -ComputerName $Server -Credential $credentials
-ScriptBlock {
$colItems = Get-ChildItem C:\Users | Where-Object {$_.PSIsContainer
-eq $true} | Sort-Object foreach ($i in $colItems) {
$subFolderItems = Get-ChildItem $i.FullName -recurse -force -ErrorAction Ignore | Where-Object {$_.PSIsContainer -eq $false} | Measure-Object -property Length -sum | Select-Object Sum
$i.FullName + " -- " + "{0:N2}" -f ($subFolderItems.sum / 1MB) + " MB" }
}
This gives me numbers like: C:\Users\admin -- 673.42 MB but when I run the same code locally it says 47.9 MB which is the true value.
Can anyone give me a tip or explain why is that. Thanks
$Server has the server name which I am passing earlier in the script. Everything works except the correct output from the code above.

How To Ignore Error In Powershell Script (ErrorAction: SilentlyContinue not suppressing error)

I have a Powershell script that lists all the users/groups in the local administrators group for all computers in a designated OU in Active Directory.
The script works perfectly locally (if I run it against the local machine only) but when I run it against remote machines, it technically works but it throws a consistent error that I don't know how to filter out.
Here is the script (NOTE: must be running from ActiveDirectory PS console to use Get-ADComputer):
Get-ADComputer -SearchBase 'OU=ou01,dc=domain,dc=local' -Filter 'ObjectClass -eq "Computer"' `
| ForEach-Object {
Get-WmiObject win32_groupuser -cn $_.name -ErrorAction SilentlyContinue `
| Where-Object { $_.groupcomponent -match 'administrators' } `
| ForEach-Object -ErrorAction SilentlyContinue {[wmi]$_.partcomponent } `
| Select-Object __SERVER,Caption
} | Format-Table -Property * -AutoSize
Here are the results (correct result is in first line, error below that):
__SERVER Caption
-------- -------
workstation_name workstation_name\Administrator
Cannot convert value "\\workstation_name\root\cimv2:Win32_Group.Domain="DOMAIN",Name="Domain Admins"" to type "System.Management.ManagementObject". Error: "Not found "
At line:1 char:306
+ Get-ADComputer -SearchBase 'OU=ou01,dc=domain,dc=local' -Filter 'ObjectClass -eq "Computer"' | ForEach-Object { Get-WmiObject win32_groupuser -cn $_.name -ErrorAction SilentlyContinue | Where-Object { $_.groupcomponent -match 'administrators' } | ForEach-Object -ErrorAction SilentlyContinue {[wmi]$_. <<<< partcomponent } | Select-Object __SERVER,Caption } | Format-Table -Property * -AutoSize
+ CategoryInfo : NotSpecified: (:) [], RuntimeException
+ FullyQualifiedErrorId : RuntimeException
I have unsuccessfully tried to use -ErrorAction SilentlyContinue, is there another way to suppress this message? Not sure what I am missing.

Pipeline Input/Output

I want to list the files of C: drive. First of all, I want to get the device ID from logical disk wmi object, and list it.
Below command returns:
Get-WmiObject -class Win32_logicaldisk
DeviceID : C:
DriveType : 3
ProviderName :
FreeSpace : 940371968
Size : 125809192960
VolumeName :
But this command:
Get-WmiObject -class Win32_logicaldisk | select deviceid | Get-ChildItem -path {$_}
gives below error:
Get-ChildItem : Cannot find drive. A drive with the name
'#{deviceid=C' does not exist. At line:1 char:60
+ Get-WmiObject -class Win32_logicaldisk | select deviceid | Get-ChildItem -path { ...
+ ~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (#{deviceid=C:String) [Get-ChildItem], DriveNotFoundException
+ FullyQualifiedErrorId : DriveNotFound,Microsoft.PowerShell.Commands.GetChildItemCommand
Get-ChildItem -path accepts pipeline input, how we can solve this ?
Your Select is returning an Object with a property named DeviceID.
Use -ExpandProperty to get the property value, then pipe that:
Get-WmiObject -class Win32_logicaldisk | select -expandproperty deviceid | Get-ChildItem -path {$_}
You could also just select the property in the Object that gets returned. In this case, $_.DeviceID
Get-WmiObject -class Win32_logicaldisk | select deviceid | Get-ChildItem -path {$_.DeviceID}