kiw*_*san 2 arrays variables powershell scope
在以下 Powershell 示例中,如何$server在第 5 行内进行填充?我正在尝试将Get-EventLog查询的结果保存到每次$server循环迭代的数组中。
例子:
$serversArray = @("one", "two", "three")
ForEach ($server in $serversArray) {
echo $server "Variable array iteration populates here correctly"
$eventArray = @()
$eventArray += Get-EventLog -computerName $server #But not here, where I need it
$eventArray #Yet it populates from calling the second array correctly
}
Run Code Online (Sandbox Code Playgroud)
与往常一样,提前致谢。
编辑好的,ISE 正在缓存一些变量(或一些奇怪的东西),因为上面的示例在我重新启动 ISE 后开始工作。无论如何,问题在于$servers数组输入,它在完整脚本中来自 MySQL 查询。如果我用服务器名称静态分配数组(如上例所示),脚本将起作用。如果我使用 MySQL 查询的输入,则Get-EventLog失败并显示The network path was not found. 因此,即使服务器值看起来正确(并且某些内容可能会扩展),它也可能是文本编码问题等。很抱歉浪费时间,但讨论它有助于缩小范围。这是实际脚本的相关部分:
#Open SQL Connection
[System.Reflection.Assembly]::LoadWithPartialName("MySql.Data")
$connectionString = "server=dbserver;uid=odbc;pwd=password;database=uptime;"
$connection = New-Object MySql.Data.MySqlClient.MySqlConnection
$connection.ConnectionString = $connectionString
$connection.Open()
#Get server names from db
$sqlGetServers = "select server_nm from servers limit 3;"
$command = New-Object MySql.Data.MySqlClient.MySqlCommand($sqlGetServers, $connection)
$dataAdapter = New-Object MySql.Data.MySqlClient.MySqlDataAdapter($command)
$dataSet = New-Object System.Data.DataSet
$recordCount = $dataAdapter.Fill($dataSet, "sample_data")
$server_names = @()
$server_names += $dataSet.Tables["sample_data"]
#$server_names = @("server-1","server-2") <-- this works
#loop through array of server names
foreach($server in $server_names) {
$eventData = @()
$eventData += Get-EventLog -computerName $server -LogName System -Newest 10
foreach($event in $eventdata) {Do-Stuff}
}
Run Code Online (Sandbox Code Playgroud)
我不能 100% 确定您遇到的问题是什么。我假设问题是您$eventArray最终得到的只是最后一个结果。
如果这是正确的,那么原因是因为您在第 4 行的每次迭代中都将其重新初始化为空: $eventArray = @()
尝试这个:
$serversArray = @("one", "two", "three")
$eventArray = @()
ForEach ($server in $serversArray) {
echo $server "Variable array iteration populates here correctly"
$eventArray += Get-EventLog -computerName $server #But not here, where I need it
$eventArray #Yet it populates from calling the second array correctly
}
Run Code Online (Sandbox Code Playgroud)
或者,或者,ForEach-Object像这样:
$serversArray = @("one", "two", "three")
$eventArray = $serversArray | ForEach-Object {
echo $_ "Variable array iteration populates here correctly"
Get-EventLog -computerName $_ #But not here, where I need it
#Yet it populates from calling the second array correctly
}
Run Code Online (Sandbox Code Playgroud)
在循环开始之前声明$eventArray为空数组,然后在循环的每次迭代中向其中添加项目,而不是在每次迭代时对其进行初始化。
你拥有它的方式,$eventArray每次都会被重置为一个空数组,最后它只包含最后一个结果。
ForEach-Object是一个管道 cmdlet 并返回其代码块的结果(对于通过管道传输到其中的每个对象运行一次。
在这种情况下,我们使用$_来表示单个对象。我们不将结果赋值给Get-EventLogto $eventArray,而是简单地调用它,允许从块中返回返回值。
我们将整个ForEach-Object调用分配到$eventArray,这将最终得到整个调用的结果集合。