我正在编写一个脚本,该脚本接受非结构化的输入,将其重新格式化并吐出CSV。
在其中一个成员中,我想对另一个成员进行NSLOOKUP以获得与IP关联的DNS条目。然而,许多条目具有例如0.0.0.0的IP。这是一个侦听端口,尚无客户端连接。
这些正确地引发了来自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命令中的值,但是我确定我想做的事非常有可能,我只是想念一些东西!
有任何想法吗?
最佳答案
您对ScriptProperty而不是NoteProperty感兴趣:
$obj |Add-Member -MemberType ScriptProperty -Name Client_DNS -Value {
nslookup $this.Client_IP |Select-String Name
}
关于arrays - Powershell添加成员计算值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37135020/