无论我做什么,CSV文件的输出都是空白的。请告诉我我做错了什么。我只需要找出输出没有到达CSV文件的原因。
$servers = Get-Content "C:\temp\servers.txt"
foreach ($Server in $servers) {
Get-IPAddress -ComputerName $servers -IPV4only
}
Select-Object Name, IP | Export-CSV c:\temp\final.txt
函数Get-IPAddress
的实现如下:
function global:Get-IPAddress {
#Requires -Version 2.0
[CmdletBinding()]
Param (
[Parameter(Position=1,
ValueFromPipeline=$true,
ValueFromPipelineByPropertyName=$true)]
[String[]]$ComputerName = $env:COMPUTERNAME,
[Switch]$IPV6only,
[Switch]$IPV4only
)#End Param
Begin {
Write-Verbose "`n Checking IP Address . . .`n"
$i = 0
}#Begin
Process {
$ComputerName | ForEach-Object {
$HostName = $_
Try {
$AddressList = @(([net.dns]::GetHostEntry($HostName)).AddressList)
} Catch {
"Cannot determine the IP Address on $HostName"
}
If ($AddressList.Count -ne 0) {
$AddressList | ForEach-Object {
if ($IPV6only) {
if ($_.AddressFamily -eq "InterNetworkV6") {
New-Object psobject -Property @{
IPAddress = $_.IPAddressToString
ComputerName = $HostName
} | Select ComputerName,IPAddress
}
}
if ($IPV4only) {
if ($_.AddressFamily -eq "InterNetwork") {
New-Object psobject -Property @{
IPAddress = $_.IPAddressToString
ComputerName = $HostName
} | Select ComputerName,IPAddress
}
}
if (!($IPV6only -or $IPV4only)) {
New-Object psobject -Property @{
IPAddress = $_.IPAddressToString
ComputerName = $HostName
} | Select ComputerName,IPAddress
}
}#Foreach-Object(IPAddress)
}#IF
}#Foreach-Object(ComputerName)
}#Process
}#Get-IPAddress
答案 0 :(得分:2)
您没有提供任何可供选择的内容(您在Get-IPAddress
循环中运行foreach
,但输出未传递到Select-Object
cmdlet中。此外,您的函数生成具有ComputerName
属性的对象,但您尝试选择属性Name
。
将您的代码更改为:
Get-Content 'C:\temp\servers.txt' | ForEach-Object {
Get-IPAddress -ComputerName $servers -IPV4only
} | Select-Object ComputerName, IP | Export-Csv 'c:\temp\final.txt' -NoType
作为旁注,您可能希望将开关-IPV4only
和-IPV6only
互斥,方法是将它们放入不同的参数集中:
[CmdletBinding(DefaultParameterSetName='all')]
Param (
[Parameter(Position=1,
ValueFromPipeline=$true,
ValueFromPipelineByPropertyName=$true)]
[String[]]$ComputerName = $env:COMPUTERNAME,
[Parameter(ParameterSetName='v6')]
[Switch]$IPV6only,
[Parameter(ParameterSetName='v4')]
[Switch]$IPV4only
)
答案 1 :(得分:2)
查看您的代码段,两个语句(foreach(...)
构造和Select-Object|Export-Csv
表达式)完全断开连接。
将foreach
内的表达式的输出分配给变量,并将其输出到Select-Object
而不是
$servers = Get-Content "C:\temp\servers.txt"
$Output = foreach ($Server in $Servers)
{
Get-IPAddress -ComputerName $server -IPV4only |Select IP,@{Name="Name";Expression={$server}}
}
$Output | Select-Object Name, IP | Export-CSV c:\temp\final.txt