【问题标题】:Output of Get-content as variable?Get-content 作为变量的输出?
【发布时间】:2018-07-04 14:07:53
【问题描述】:

我正在尝试在 get-content 和 convertfrom-json cmd 上运行 foreach 循环。现在我知道这可能存在变量中的多值结果的问题,我想知道如何继续将此信息传递给脚本的其余部分。

$testconv = Get-device * |select ID
$testid = $testconv.id

$conv = foreach ($id in $testid) 
{
get-content "\\HDC-PRTG-03\System Information Database\Services\Device$id.Services" | Convertfrom-json 
} 

$rpccheck =$conv.message
$snmpcheck = $conv.message
$svcname = $conv.data.displayname
$svcstate=$conv.data.properties.state

if($RPCon = $rpccheck |select-string -pattern RPC -AllMatches){
write-host RPC Not enabled
}else{
write-host No RPC Enabled - Moving to Services List 

现在当我在没有 $conv= 的情况下运行它时,它会返回

kind         : Services 
recievetime  : 29-01-2018 14:43:32
error        : 106
Message      : SNMP Channels Not Available. 

这是我所期望的。但是,当我用 $conv= 定义它的变量时,它只是开始说它找不到文件路径,我发现抛出一个奇怪的错误,但是嘿嘿。

你们中的任何一个聪明人都知道如何将这些 fromjson 对象保存在内存中,以便我可以继续对它们运行 foreach 循环。该脚本的终极功能是查询本地 .services 文件以了解设备上正在运行哪些服务,然后创建传感器以在我们的 PRTG 安装中监控它们。因此我需要能够引用 deviceID 并将其应用于它。

我怀疑我可能在整个脚本中使用了太多的 foreach 循环,但坦率地说,我 100% 超出了我的深度

非常感谢任何指导

山姆

【问题讨论】:

    标签: powershell loops foreach


    【解决方案1】:

    如果我理解正确,您应该有所有设备 ID 的 json 文件。如果缺少具有特定设备名称的文件,您将收到“找不到文件”错误。

    至于代码,你可以试试这个:

    $testconv = Get-Device * | select ID
    $testid = $testconv.id
    
    $oldErrorAction = $ErrorActionPreference
    $ErrorActionPreference = 'Stop'
    
    foreach ($id in $testid) {
        try {
            $conv = Get-Content -Path "\\HDC-PRTG-03\System Information Database\Services\Device$id.Services" -Raw | ConvertFrom-Json 
            $rpccheck  = $conv.message  # These look the same to me...
            $snmpcheck = $conv.message  # These look the same to me...
            $svcname   = $conv.data.displayname
            $svcstate  = $conv.data.properties.state
    
            $Matches = ($rpccheck | Select-String -Pattern "RPC*" -AllMatches)
            if ($Matches.Matches.Count) {
                Write-Host "RPC Not enabled"
            }
            else {
                Write-Host "No RPC Enabled - Moving to Services List "
            }
        }
        catch {
            Write-Warning $_.Exception.Message
        }
    } 
    
    $ErrorActionPreference = $oldErrorAction
    

    您也可以在执行 Get-Content 之前直接使用 Test-Path 测试是否存在具有该名称的文件,而不是 try{}..catch{}。

    【讨论】:

    • @Samuel A 这有帮助吗??
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-11-19
    • 1970-01-01
    • 1970-01-01
    • 2020-07-10
    • 1970-01-01
    • 2019-12-30
    • 1970-01-01
    相关资源
    最近更新 更多