Solved

issue with beginner powershell script.

Posted on 2016-11-26
5
67 Views
Last Modified: 2016-11-30
Hello,
I am new to powershell. this is my learning script. I created try and catch and in the catch it suppose to create file with failed computers.
Below is the line. It created failedcomp.txt but it is empty. "Notonline" computer name should be there because this computer doesn't exist.
 $computer = out-file failedcomp.txt
please help
0
Comment
Question by:creative555
5 Comments
 

Author Comment

by:creative555
ID: 41902722
Function Get-DJOSInfo {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory=$true,
        ValueFromPipeline=$true,
        ValueFromPipelineByPropertyName=$true)]
    [Alias('hostname')]
    [string[]]$ComputerName,
    [switch]$nameLog

)
Begin {
   if ($nameLog)
   {
       Write-Verbose "Finding name log file"
       $i = 0
    do {
    $logFile = "names-$i.txt"
    $i++
    } while (Test-Path $logFile)
    Write-verbose "Log file name will be stored $logfile"

    }
else {
write-verbose "Name logging off"
   } 


}
Process {
    if ($nameLog)
    {
        Write-Verbose "Name log on"
    }
    else
    {
       Write-Verbose "Name log off" 
    }

    foreach ($computer in $computername) {
    Write-Verbose "Now connecting to $computer"
    if ($nameLog){
    $computer | out-file $logFile -Append
    }

    try {
            $continue = $true
            $os = Get-WmiObject -ErrorAction 'Stop' -ComputerName $computer -class Win32_OperatingSystem |
            Select Caption,BuildNumber,OSArchitecture,ServicePackMajorVersion

        } catch {
            Write-Verbose "Connection to $computer failed"
            $continue = $false
            $computer = out-file failedcomp.txt
        }

        if ($continue) {
            Write-Verbose "Connection to $computer succeeded"
            $bios = Get-WmiObject -ComputerName $computer -Class Win32_BIOS |
                Select SerialNumber
            $processor = Get-WmiObject -ComputerName $computer -Class Win32_Processor |
                Select AddressWidth -first 1
            $osarchitecture = $os.osarchitecture -replace '-bit',''
            $properties = @{'ComputerName'=$computer;
                            'OSVersion'=$os.Caption;
                            'OSBuild'=$os.BuildNumber;
                            'OSArchitecture'=$osarchitecture;
                            'OSSPVersion'=$os.servicepackmajorversion;
                            'BIOSSerial'=$bios.SerialNumber;
                            'ProcArchitecture'=$processor.addresswidth}
            $obj = New-Object -TypeName PSObject -Property $properties
            Write-Output $obj
            }
 
}

}

End {}


}



Get-DJOSInfo -computername server01, notonline, server02.testtarget.local -Verbose -nameLog

Open in new window

0
 
LVL 80

Accepted Solution

by:
David Johnson, CD, MVP earned 500 total points
ID: 41902756
$computer = out-file failedcomp.txt change to
$computer | Out-File FailedComp.txt -Append
fixed and added output to csv
Function Get-DJOSInfo {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory=$true,
        ValueFromPipeline=$true,
        ValueFromPipelineByPropertyName=$true)]
    [Alias('hostname')]
    [string[]]$ComputerName,
    [switch]$nameLog

  )
  Begin {
    if ($nameLog)
    {
       Write-Verbose "Finding name log file"
       $i = 0
      do {
        $logFile = "names-$i.txt"
        $i++
      } while (Test-Path $logFile)
      Write-verbose "Log file name will be stored $logfile"

    }
    else {
      write-verbose "Name logging off"
    } 


  }
  Process {
  $namesobj = @()
    if ($nameLog)
    {
        Write-Verbose "Name log on"
    }
    else
    {
       Write-Verbose "Name log off" 
    }

    foreach ($computer in $computername) {
      Write-Verbose "Now connecting to $computer"
      if ($nameLog){
        $computer | out-file $logFile -Append
      }

      try {
            $continue = $true
            $os = Get-WmiObject -ErrorAction 'Stop' -ComputerName $computer -class Win32_OperatingSystem |
            Select-Object Caption,BuildNumber,OSArchitecture,ServicePackMajorVersion

        } catch {
            Write-Verbose "Connection to $computer failed"
            $continue = $false
            $computer | out-file failedcomp.txt -append
        }

        if ($continue) {
            Write-Verbose "Connection to $computer succeeded"
            $bios = Get-WmiObject -ComputerName $computer -Class Win32_BIOS |
                Select-Object -Property SerialNumber
            $processor = Get-WmiObject -ComputerName $computer -Class Win32_Processor |
                Select-Object -Property AddressWidth -First 1
            $osarchitecture = $os.osarchitecture -replace '-bit',''
            $properties = @{'ComputerName'=$computer;
                            'OSVersion'=$os.Caption;
                            'OSBuild'=$os.BuildNumber;
                            'OSArchitecture'=$osarchitecture;
                            'OSSPVersion'=$os.servicepackmajorversion;
                            'BIOSSerial'=$bios.SerialNumber;
                            'ProcArchitecture'=$processor.addresswidth}
            $obj = New-Object -TypeName PSObject -Property $properties
            Write-Output $obj
            $namesobj += $obj
            }
 
    }
    if ($nameLog) {
      $namesobj | export-csv -Path computerinfo.csv -NoTypeInformation
    }

  }

  End {}


}

Get-DJOSInfo -computername alpha, server01, notonline, server02.testtarget.local -Verbose -nameLog

Open in new window

0
 
LVL 11

Expert Comment

by:Ganesh Kumar A
ID: 41902995
You also can use Export-CSV filename.csv to export if you have data you want to get in Excel.
0
 
LVL 14

Expert Comment

by:frankhelk
ID: 41903167
I recommend to see i.e.
    https://msdn.microsoft.com/en-us/powershell/reference/5.1/microsoft.powershell.utility/out-file 
for the syntax of out-file.

Your command writes an empty string (because no string is given) to the log file and stores the resultcode in $computer.

I think the command should read

out-file -FilePath failedcomp.txt -InputObject $computer

Open in new window


By the way:
Get-WmiObject has a hell of timeout if the queried node is down, which results in an enormous long time to scan a long list with many down nodes. It would be better to first try a single ping on that node prior to query it with Get-WmiObject ... if the ping fails, the Get-WmiObject query would be senseless.
0
 

Author Closing Comment

by:creative555
ID: 41908080
thank you! This worked!!!
0

Featured Post

Are your AD admin tools letting you down?

Managing Active Directory can get complicated.  Often, the native tools for managing AD are just not up to the task.  The largest Active Directory installations in the world have relied on one tool to manage their day-to-day administration tasks: Hyena. Start your trial today.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Microsoft Windows Server Update Service (WSUS) is free for everyone, but it lacks of some desirable features like send an e-mail to the administrator with the status of all computers on the WSUS server. This article is based on my PowerShell script …
I thought I'd write this up for anyone who has a request to create an anonymous whistle-blower-type submission form created using SharePoint 2010 (this would probably work the same for 2013). It's not 100% fool-proof but it's as close as you can get…
Learn how to match and substitute tagged data using PHP regular expressions. Demonstrated on Windows 7, but also applies to other operating systems. Demonstrated technique applies to PHP (all versions) and Firefox, but very similar techniques will w…
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)

839 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question