gpt4 book ai didi

arrays - 在Powershell中打印阵列

转载 作者:行者123 更新时间:2023-12-03 14:35:37 24 4
gpt4 key购买 nike

我正在尝试打印一个数组(我尝试了一个for循环,并直接尝试了.ToString()),但是我总是得到System.Object输出。

数组的内容是此命令的结果:

$singleOutput = Invoke-Command -ComputerName $server -ScriptBlock {
Get-ChildItem C:\*.txt -Recurse |
Select-String -Pattern "password" -AllMatches
}

这是我得到的输出:
System.Object[]

What am I missing?

EDIT:

This is the whole function:

foreach ($server in $servidores) {
$result = @()
Write-Output ("---Searching on Server:---" + $server + "----at:" +
(Get-Date).ToString() + "----")
$singleOutput = Invoke-Command -ComputerName $server -ScriptBlock {
Get-ChildItem C:\*.txt -Recurse |
Select-String -Pattern "password" -AllMatches
}
$result += $singleOutput

Write-Host $result.ToString()
}
Read-Host -Prompt "Press Enter to exit"

我也尝试过:
foreach ($i in $result) {
$result[$i].ToString()
}

最佳答案

您正在使用Select-String,它会生成MatchInfo对象。因为看起来您想要文件中的所有匹配行,所以您可能应该只返回Line对象的MatchInfo属性的值。另外,数组处理也太复杂了。只需输出Invoke-Command返回的任何内容,并将循环输出捕获到变量中即可。对于循环内的状态输出,请使用Write-Host,这样消息就不会被$result捕获。

$result = foreach ($server in $servidores) {
Write-Host ("--- Searching on Server: $server at: " + (Get-Date).ToString())
Invoke-Command -ComputerName $server -ScriptBlock {
Get-ChildItem C:\*.txt -Recurse |
Select-String -Pattern "password" -AllMatches |
Select-Object -Expand Line
}
}

如果还需要主机名,则可以添加一个 calculated property并返回自定义对象:
$result = foreach ($server in $servidores) {
Write-Host ("--- Searching on Server: $server at: " + (Get-Date).ToString())
Invoke-Command -ComputerName $server -ScriptBlock {
Get-ChildItem C:\*.txt -Recurse |
Select-String -Pattern "password" -AllMatches |
Select-Object @{n='Server';e={$env:COMPUTERNAME}},Line
}
}

您只需通过回显array变量即可输出数组:
PS C:\> $resultServer    Line------    ----...       ...

To get custom-formatted output you can for instance use the format operator (-f):

$result | ForEach-Object {
'{0}: {1}' -f $_.Server, $_.Line
}

关于arrays - 在Powershell中打印阵列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39534143/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com