【问题标题】:Script works, but I cant figure out how to expand PSCustomObject脚本有效,但我不知道如何扩展 PSCustomObject
【发布时间】:2021-11-01 08:50:22
【问题描述】:
$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

我附上了我的输出图片以供参考。

我想做什么: 展开 IP,使其显示整个 IP 地址。 最长的字符串是 172.32.5.111 但它一直在:172.32.5......输出看起来也是这样。

我已经尝试使用 PSCustomObject 的 -expand 属性,但老实说,今天是我第一次使用对象。 我在 C:\Users\Administrator\Desktop\DAVID\TimeSyncFinal\CheckTime\allips.txt 中也有一个 ip 列表

在每行列出一个 ip 地址($srtComputer 是 ip 列表的变量,我尝试将其作为 PSCustomObject 的占位符,但没有帮助。)

-replace是去掉net time命令输出中添加的\\(可能不能扩展net time输出?)

【问题讨论】:

  • 这意味着您正在读取的文件中没有正确设置某些内容。因此您确实需要展示一个示例。由于 $ip 中的其他内容,显示的值被截断。如果这是一个真正的 .csv 文件,则使用 Import-Csv 而不是 Get-Content 通过点引用从文件中获取列名称/属性。如果它是一个平面文件,那么您需要将该文件中的 IPA 分隔到它自己的列中,或者使用正则表达式从 $ip 字符串中提取 IPA。
  • 天啊,我开始时经常使用 Import-csv,但后来由于某种原因切换到 txt 文件。一个简单的切换修复了一切,谢谢:)
  • 别担心,伙计,很高兴它有帮助。

标签: powershell variables expand


【解决方案1】:

继续我的评论。您的基本代码按设计工作:

如果您的文件只有国际音标,那么...

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
#>

或者这样,使用-replace和split(如果有其他东西混合)......

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]
    } 
}

或者使用正则表达式(如果还有其他内容)...

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
    }    
}

我做了什么来解决它:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-09-19
    • 2013-09-13
    • 2016-04-03
    • 1970-01-01
    • 2012-08-03
    • 1970-01-01
    • 2013-02-12
    • 1970-01-01
    相关资源
    最近更新 更多