Returning object from scriptblock

Welcome Forums General PowerShell Q&A Returning object from scriptblock

Viewing 2 reply threads
  • Author
    • #214947
      Topics: 2
      Replies: 3
      Points: 32
      Rank: Member


      I struggle with understanding why I dont get the $infoObject returned from the scriptBlock and written to the CSV file afterwards

      Invoke-command -ComputerName $sourceServerName -Credential $CredentialInitializedEarlier -ScriptBlock {
      $infoObject = New-Object PSObject

      $MacInfo = Get-NetAdapter | Select-Object-Object MacAddress, ifIndex
      $IpV4Info = Get-NetIpAddress | Where-Object {($_.Interfaceindex -eq $MacInfo.ifIndex ) -and ($_.AddressFamily -eq "IPv4")} | Select-Object-Object IPAddress

      Add-Member -inputObject $infoObject -memberType NoteProperty -name "Mac" -value $MacInfo.MacAddress
      Add-Member -inputObject $infoObject -memberType NoteProperty -name "IpV4Info" -value $IpV4Info
      Add-Member -inputObject $infoObject -memberType NoteProperty -name "ServerName" -value $sourceServerName

      } | ConvertFrom-Csv | Export-Csv F:\data\MACAddressBaseline.csv -NoTypeInformation -append


    • #214962
      Topics: 5
      Replies: 349
      Points: 632
      Helping Hand
      Rank: Major Contributor

      Remove ConvertFrom-Csv

    • #214965
      Topics: 12
      Replies: 547
      Points: 1,345
      Helping Hand
      Rank: Community Hero

      Well, you gotta a number of errors:
      1- Lines 3 and 4 show ‘Select-Object-Object’ instead of ‘Select’ or ‘Select-Object’
      2- $IpV4Info line 4 assumes incorrectly that there’s a single $MacInfo, where the code must consider that $MacInfo is a collection of objects that you need to iterate through as in:

      3- Line 4 should return the (string) value of the the IPAddress, not an object that has a property called IPAddress. Using Select-Object at the end of line 4 returns an object like @{IPAddress=} which would not even show up in CSV – See how line 4 is corrected in the final code below.
      4- Lines 5 and 6 should account for having multiple values for MAC and IPAddress, especially when outputting to CSV. The corrected code below joins the values using the -join operator
      5- In the last line #9, ConvertFrom-Csv is not required
      6- In the last line #9, it’s recommended to use

      to exclude the scriptblock automatic variables such as RunSpaceId, PSComputerName, …
      7- Line 7 must use

      to grab the desired value inside the script block which was assigned in the parent scope

      Suggested code:

      Alternatively use the Get-PCInfo function of the AZSBTools PS module as in:

Viewing 2 reply threads
  • The topic ‘Returning object from scriptblock’ is closed to new replies.