Home > Blockchain >  powershell better way to test if both directories exists or one only on all pc's from domain an
powershell better way to test if both directories exists or one only on all pc's from domain an

Time:01-29

could you please help me to correct this script (gathered by pieces from internet) or better change logic how it should work (not working currently). The goal is to get pc's where only one folder exist (oracle11) and not both (11 12) and export it to csv. Oracle is a real pain in the .... Thank you in advance for your advice.

Import-Module ActiveDirectory
$computers = Get-ADComputer -Filter * -Properties * | Select -Property Name
$output = @()

#$computers = get-adcomputer -filter * | Select-Object -Expand Name | foreach-object {

Foreach ($Computer in $computers){
  if ( (test-path "\\$Computer\C$\oracle\product\11.2.0\" ) -and !( test-path "\\$Computer\C$\oracle\product\12.2.0" )) {
    $output  = $Computer
  }
} 
$output | Export-Csv -NoTypeInformation -Path c:\temp\test.csv

CodePudding user response:

The problem is that the path strings you construct inside the loop are not as you expect.

When you pipe the output from Get-ADComputer to Select-Object -Property Name, it creates a new object with a single property Name for each input object.

When you then implicitly convert one of these objects to a string, the resulting value is going to be "@{Name=Computer01}", instead of just "Computer01".

You can observe this yourself, by calling Write-Host instead of Test-Path:

Get-ADComputer -Filter * |Select-Object -Property Name |ForEach-Object {
  Write-Host "\\$_\C$"
}

To extract just the value of the Name property from each ADComputer, use ForEach-Object -MemberName instead of Select-Object -Property:

$computerNames = Get-ADComputer -Filter * -Properties * | ForEach-Object -MemberName
$output = @()

foreach($ComputerName in $computerNames){
  if ( (Test-Path "\\$ComputerName\C$\oracle\product\11.2.0\" ) -and !( Test-Path "\\$ComputerName\C$\oracle\product\12.2.0" )) {
    $output  = $ComputerName
  }
} 
$output | Export-Csv -NoTypeInformation -Path c:\temp\test.csv

Note that passing -Properties * to Get-ADComputer is unnecessary, the object name is always part of the default property set sent back by the Get-AD* cmdlets.

  •  Tags:  
  • Related