gpt4 book ai didi

powershell - 解析导入的csv并迭代管道值

转载 作者:行者123 更新时间:2023-12-03 00:08:43 25 4
gpt4 key购买 nike

我有一个名为Get-InstalledApps的函数,该函数可连接到所有带有-computers参数列出的计算机,该计算机通过管道接受输入。

将计算机名称传递给函数时,存在两个问题:

(a)我有一个可以传递给它的CSV文件,但是它解析这样的值:@{computername=HOSTNAME}而不是HOSTNAME

(b)当改为从Get-ADComputer -Filter *进行管道传输时,它只是获取最近传递的计算机名称。

这是我的功能:

function Get-InstalledApps {

Param (

[CmdletBinding()]

[Parameter(ValueFromPipeline=$true)]

[Alias('name')]

[string[]]$computers = $env:COMPUTERNAME

)

foreach($computer in $computers){

write-verbose -verbose -message "`nStarting scan on $computer"

Invoke-Command -Computername $computer -ErrorAction SilentlyContinue -ErrorVariable InvokeError -Scriptblock {

$installPaths = @('HKLM:\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall','HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall')

Get-ChildItem -Path $installPaths | Get-ItemProperty | Sort-Object -Property DisplayName | Select-Object -Property DisplayName, DisplayVersion, Publisher, UninstallString, Version

}

if ($invokeerror){

Write-Warning "Could not communicate with $computer"

}

}

}

更新:此问题已解决。这是那些想要的人的要点:

https://gist.github.com/TylerJWhit/f596c307cf87540842281a8a20149f9a

最佳答案

回复(a):

如果您的函数看到的是@{computername=HOSTNAME}而不是HOSTNAME,则表示您正在执行以下操作:

 Import-Csv ... | Select-Object ComputerName | Get-InstalledApps

而不是必需的:
 Import-Csv ... | Select-Object -ExpandProperty ComputerName | Get-InstalledApps

注意 -ExpandProperty开关,这是从输入中提取单个属性值所必需的;没有它,您将获得具有该属性的对象-有关更多信息,请参见 this answer

回复(b):

为了接受逐对象管道输入,您的函数必须具有 process { ... }块:
function Get-InstalledApps {
Param (
[CmdletBinding()]
[Parameter(ValueFromPipeline=$true)]
[Alias('name')]
[string[]]$computers = $env:COMPUTERNAME
)

process { # This ensures that the following code is called for each input object.
foreach ($computer in $computers){
# ...
}
}

}

参见 Get-Help about_Functions_Advanced

请注意,如果您只希望函数通过管道( ... | Get-InstalledApps)而不是参数( Get-InstalledApps -Computers ...)来接收计算机名称列表,则可以将 -Computers参数声明为 [string](而不是数组),从而避免了在 foreach块内需要 process { ... }循环。
有关这种差异的讨论,请参见 this GitHub issue

关于powershell - 解析导入的csv并迭代管道值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54445010/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com