Home > Software engineering >  Script works, but I cant figure out how to expand PSCustomObject
Script works, but I cant figure out how to expand PSCustomObject

Time:09-17

$computers = get-content 
"C:\Users\Administrator\Desktop\DAVID\TimeSyncFinal\CheckTime\allips.txt"
foreach ($strComputer in $computers) {
$TextOutput = net time \\$strComputer 
$ip,$time,$time1 = ($TextOutput -split ' ')[3,6,7]

[PSCustomObject] @{
IP = $ip -replace ".*\\" 
Time = $time $time1

}
}

Output

I attached a picture of my output for reference.

What i want to do: Expand the IP so it shows the whole ip address. The longest string is 172.32.5.111 But it keeps cutting off at: 172.32.5...... that's how the output looks also.

I've tried -expand property with PSCustomObject but honestly today is my first use of objects. i also have an ip list in C:\Users\Administrator\Desktop\DAVID\TimeSyncFinal\CheckTime\allips.txt

listed with an ip address on each line ($srtComputer is the varible for the ip list and ive tried putting it in as a place holder for the PSCustomObject but that didnt help.)

The -replace is to remove the \ \ added to the output of net time command (maybe you cant expand net time output?)

CodePudding user response:

Continuing from my comment. Your base code works as designed:

If your file has only an IPA, then...

Clear-Host
$computers = '127.0.0.1'

foreach ($strComputer in $computers) 
{
    $TextOutput = net time \\$strComputer 
    $ip, $time, $time1 = ($TextOutput -split ' ')[3,6,7]

    [PSCustomObject] @{
            IP   = $ip -replace ".*\\" 
            Time = $time   $time1
        }
}

# Results
<#

IP        Time     
--        ----     
127.0.0.1 5:31:37PM
#>

Or this way, using -replace and split (if there is other stuff in the mix)......

Clear-Host
$computers = '127.0.0.1', '172.25.83.95'

foreach ($strComputer in $computers) 
{
    $TextOutput = (net time \\$strComputer) -Replace '.*\\\\' -split ' is '

    [PSCustomObject] @{
        IP   = $TextOutput[0]
        Time = $TextOutput[1]
    } 
}

Or using RegEx (if there is other stuff in the mix)...

Clear-Host
$computers = '127.0.0.1'

foreach ($strComputer in $computers) 
{
    $TextOutput = net time \\$strComputer 

    [PSCustomObject] @{
        IP   = [regex]::Matches($TextOutput, '\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}').Value
        Time = [regex]::Matches($TextOutput, '(\d )\/(\d )\/(\d ).(\d ):(\d ):(\d ).[A|P]M').Value
    }    
}

What i did to fix it:

REPLACE GET-CONTENT WITH IMPORT-CSV
$strComputer with $ip 
$computers to $computers.IP
And add an IP header to .csv file ip address list
* i wanted to edit my original as little as possible
  • Related