Powershell:在if语句中管道变量$ _?

时间:2016-01-14 14:58:47

标签: powershell powershell-v3.0

我有以下简短的脚本来获取OU中的计算机和显示器的序列号,这可以正常工作:

svn commit

在尝试获取WMIObject之前,此脚本不会检查计算机是否处于联机状态,因此如果计算机处于脱机状态,则在RPC调用超时之前需要很长时间。

在尝试获取WMIObject之前,我尝试修改脚本以使用Test-Connection cmdlet:

Import-Module ActiveDirectory

$searchbase = "OU=some,OU=organisational,OU=units,DC=somedomain,DC=local"

Write-Host ""
Write-Host "Serial Numbers for Computers and Monitors in" $searchbase
Write-Host "--"
Get-ADComputer -SearchBase $searchbase -Filter '*' | `
Select-Object -Expand Name | %{Write-Host ""; echo $_ ; Get-WMIObject -Class Win32_BIOS -ComputerName $_ | Select-Object -Expand SerialNumber; `
$monitor = gwmi WmiMonitorID -Namespace root\wmi -computername $_; ($monitor.SerialNumberID | foreach {[char]$_}) -join ""};

我确定我在做一些语法上很愚蠢的事情。有人能指出我正确的方向吗?

2 个答案:

答案 0 :(得分:6)

您不能直接管道到if语句,只能管道到cmdlet。

ForEach-Object语句放在<{em}里面%块(ForEach-Object... | Select-Object -Expand Name | ` %{ if (Test-Connection -ComputerName $_ -Quiet) { # Get-WmiObject in here } else { Write-Host ""; Write-Host $_ "is offline"; } } 的别名):

Where-Object

如果您不关心将每台计算机的状态写入主机,您还可以使用?(别名... | Select-Object -Expand Name | ?{ Test-Connection $_ -Quiet } | % { Get-WmiObject -ComputerName $_ } )过滤掉离线计算机:

ldapsearch -H ldaps://172.22.5.52/ -b "OU=XXX" -x -d5
ldap_url_parse_ext(ldaps://172.22.5.52/)
ldap_create
ldap_url_parse_ext(ldaps://172.22.5.52:636/??base)
ldap_sasl_bind
ldap_send_initial_request
ldap_new_connection 1 1 0
ldap_int_open_connection
ldap_connect_to_host: TCP 172.22.5.52:636
ldap_new_socket: 3
ldap_prepare_socket: 3
ldap_connect_to_host: Trying 172.22.5.52:636
ldap_pvt_connect: fd: 3 tm: -1 async: 0
TLS: can't connect: The signature algorithm is not supported..
ldap_err2string
ldap_sasl_bind(SIMPLE): Can't contact LDAP server (-1)

答案 1 :(得分:2)

除了@Mathias R. Jessen的答案之外,你还可以摆脱线条延续的反对。

如果行的结尾推断出该语句需要另一个代码块,则不需要它们。与$args = array( 'post_type' => 'listing', 'post_status' => 'publish', 'post__not_in' => array($post->ID), 'orderby' => 'date', 'order' => 'DESC', 'meta_query' => array( 'relation' => 'AND', array( 'key' => 'featured_calendar', 'value' => 'on', 'compare' => '=' ), array( 'key' => 'theend', 'value' => time(), 'compare' => '>', 'type' => 'NUMERIC' // Not sure if you want a TIME here ), ), 'posts_per_page' => 7 ); $featured = new WP_Query($args); |{一样。

(

工作得很好......