syntax error powershel script for check hard disk

Viewed 32

hi there I am recently starting to work with PowerShell and I have some issue with the following script can you please help me to fix it I need to print in 1 row the state of the drive and if the memory is bellow 20%

$Computers = Get-Content -Path C:\Users\gbekari\unbackup\Servers.txt


Foreach ($Computer in $Computers)
    {
    Get-WmiObject Win32_Volume -Filter "DriveType='3'" -ComputerName $Computer | ForEach {
           New-Object PSObject -Property @{
           #Where-Object { $_.DriveType -eq "3" } # Select-Object SystemName,VolumeName,DeviceID
   
           Computername = $computername
           date         = (Get-Date -format "dd.MM.yy HH:mm")
           size         = $_.Size/1GB
           freeSpace    = ([Math]::Round($_.FreeSpace /1GB,2))
           Status       = if ([Math]::Round($_.FreeSpace /1GB,2) -contains -19) {'Warning'} else {'NONE'}
           empty        = "Diskcheck"
           }
        }
    }|ConvertTo-Csv -NoTypeInformation -Delimiter "|" | % {$_-replace'"',''} | Select-Object -skip 1 | Out-File -FilePath Get-Content -Path C:\Users\gbekari\unbackup\Sers.txt -Encoding ascii
1 Answers

You have a random Get-Content command in your Out-File statement. You also can't pipe a foreach statement. You can simply collect the results first.

I would recommend Set-Content over Out-File though.

$Computers = Get-Content -Path C:\Users\gbekari\unbackup\Servers.txt

$results = foreach ($Computer in $Computers){
    Get-WmiObject Win32_Volume -Filter "DriveType='3'" -ComputerName $Computer | ForEach {
           New-Object PSObject -Property @{
           #Where-Object { $_.DriveType -eq "3" } # Select-Object SystemName,VolumeName,DeviceID

           Computername = $computername
           date         = (Get-Date -format "dd.MM.yy HH:mm")
           size         = $_.Size/1GB
           freeSpace    = ([Math]::Round($_.FreeSpace /1GB,2))
           Status       = if ([Math]::Round($_.FreeSpace /1GB,2) -contains -19) {'Warning'} else {'NONE'}
           empty        = "Diskcheck"
           }
        }
}

$results | ConvertTo-Csv -NoTypeInformation -Delimiter "|" | % {$_-replace'"',''} | Select-Object -skip 1 | Set-Content -Path C:\Users\gbekari\unbackup\Sers.txt 

A couple of other notes. The WMI cmdlets have been replaced by the CIM cmdlets. You can also use the [PSCustomObject] type accelerator to create your objects. Both of these require powershell 3.0 or higher.

Related