我正在编写一个采用非结构化输入的脚本,重新格式化并吐出CSV。
在其中一个成员中,我想要对另一个成员执行NSLOOKUP以获取与IP关联的DNS条目。但是,许多条目的IP为0.0.0.0,例如它是一个监听端口,还没有连接的客户端。
这些错误来自NSLOOKUP,因为它没有DNS条目。
所以,如果IP不是0.0.0.0,我修改了我的代码只执行NSLOOKUP,否则返回一个空字符串。
但我无法使其发挥作用。
以下内容不会引发任何错误:
$srcdata -split "`r`n"|foreach {
$obj = New-Object System.Object
$obj|Add-Member -MemberType NoteProperty -Name Connection_ID -Value $_.Split(",")[0]
$obj|Add-Member -MemberType NoteProperty -Name Filename -Value $_.Split(",")[1]
$obj|Add-Member -MemberType NoteProperty -Name MCP_Port -Value $_.Split(",")[2]
$obj|Add-Member -MemberType NoteProperty -Name Client_Port -Value $_.Split(",")[3]
$obj|Add-Member -MemberType NoteProperty -Name Port_State -Value $_.Split(",")[4]
$obj|Add-Member -MemberType NoteProperty -Name Client_IP -Value $_.Split(",")[5]
$obj|Add-Member -MemberType NoteProperty -Name Client_DNS -value {If ($obj.Client_IP -ne "0.0.0.0") {(NSLOOKUP $obj.Client_IP|Select-String Name).Line.ToString().Replace(" ","").Split(":")[1]} else {""}}
$obj|Add-Member -MemberType NoteProperty -Name Protocol_Stack -Value $_.Split(",")[6]
$outfile += $obj
}
但是如果我检查数组中的一个对象,我会看到:
Connection_ID : 1
Filename : CCF_MARC1
MCP_Port : 2001
Client_Port : 0
Port_State : LISTEN
Client_IP : 0.0.0.0
Client_DNS : If ($obj.Client_IP -ne "0.0.0.0") {(NSLOOKUP $obj.Client_IP|Select-String Name).Line.ToString().Replace(" ","").Split(":")[1]} else {""}
Protocol_Stack : LEGACY
如果我用括号而不是脚本块包装,那么设置Client_DNS的行如下:
$obj|Add-Member -MemberType NoteProperty -Name Client_DNS -value (If ($obj.Client_IP -ne "0.0.0.0") {(NSLOOKUP $obj.Client_IP|Select-String Name).Line.ToString().Replace(" ","").Split(":")[1]} else {""})
我明白了:
If : The term 'If' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
At K:\CodeSnippets\PowerShell\NW_CONN_TO_CSV.ps1:21 char:91
+ ... NS -value (If ($obj.Client_IP -ne "0.0.0.0") {(NSLOOKUP $obj.Client_IP|Selec ...
+ ~~
+ CategoryInfo : ObjectNotFound: (If:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
我确定我可以将它作为两行单独的代码工作,所以做If语句并将结果放在变量中,然后将该变量用作add-member命令中的值,但是我确定我想要做的事情显然是可能的,我只是错过了一些东西!
有什么想法吗?
答案 0 :(得分:4)
您对 ScriptProperty 而不是 NoteProperty 感兴趣:
$obj |Add-Member -MemberType ScriptProperty -Name Client_DNS -Value {
nslookup $this.Client_IP |Select-String Name
}
答案 1 :(得分:0)
您可以使用正则表达式来提取名称,如下所示:
$outfile = $srcdata -split "[\r\n]" | % {
$v = $_.Split(",")
$re = [regex]::match((NSLOOKUP $v[5]), '(?<=Name:\s+)[^\s]+')
New-Object psobject -Property @{
Client_DNS = @('', $re.value)[$re.success]
Connection_ID = $v[0]
Filename = $v[1]
MCP_Port = $v[2]
Client_Port = $v[3]
Port_State = $v[4]
Client_IP = $v[5]
Protocol_Stack = $v[6]
}
}