【问题标题】:PowerShell - check .ini file, log issuesPowerShell - 检查 .ini 文件,记录问题
【发布时间】:2019-09-09 01:22:27
【问题描述】:

在两个 VNC 服务器强制关闭 MS 登录组时遇到问题。我正在对问题进行故障排除,我想做的一件事是监视配置 .ini 文件。我对 PowerShell 比较陌生,不能完全让它工作。

基本上,我希望脚本检查配置文件 (ultravnc.ini) 的内容并查看“MSLogonRequired=1”是否是该文件中的字符串。如果没有,我想将日期附加到日志文件中。最终我会做更多的事情,但这是我的基本需求。它目前不工作。

# Variables 
$outputFile = "vncMSLogonErrors.txt" 
$vncConfig = "C:\Program Files (x86)\uvnc bvba\UltraVNC\ultravnc.ini"
$checkString = "MSLogonRequired=1"


# Get VNC Config File, check for MS Logon setting, write date to file if missing
Get-Content $vncConfig
If (-not $checkString)
   {Add-Content $outputFile -Value $(Get-Date)}

【问题讨论】:

  • 使用Get-Content加载文件,遍历它,如果没有找到检查字符串,则添加它。
  • if((Get-Content $vncConfig -raw) -notmatch $checkString){Set-content $outputFile -Value $(Get-Date) -Append}

标签: powershell ini


【解决方案1】:

Shamus Berube's helpful answer 在概念上很简单并且效果很好,如果您可以假设:

  • 感兴趣的行正好是MSLogonRequired=1,空格没有变化。

  • 如果 INI 文件被细分为多个部分(例如,[admin]),则密钥名称 MSLogonRequired 在这些部分中是唯一的,以防止误报。

因此通常最好使用专用的 INI 文件解析命令;不幸的是:

  • PowerShell 没有自带,不过adding one is being debated
  • 与此同时,您可以使用流行的PsIni 第三方模块(有关如何安装它和背景信息,请参阅this answer):

使用PsIni模块的Get-IniContent函数:

注意:基于UltraVNC INI-file documentation,代码假定MSLogonRequired 条目位于INI 文件的[admin] 部分内。

# Variables 
$outputFile = "vncMSLogonErrors.txt" 
$vncConfig = "C:\Program Files (x86)\uvnc bvba\UltraVNC\ultravnc.ini"

# Check the VNC Config File to see if the [admin] section's 'MSLogonRequired'
# entry, if present, has value '1'.
if ((Get-IniContent $vncConfig).admin.MSLogonRequired -ne '1') {
   Add-Content $outputFile -Value (Get-Date) 
}

【讨论】:

    【解决方案2】:
    # Variables 
    $outputFile = "vncMSLogonErrors.txt" 
    $vncConfig = "C:\Program Files (x86)\uvnc bvba\UltraVNC\ultravnc.ini"
    $checkString = "MSLogonRequired=1"
    
    if ((get-content $vncconfig) -notcontains $checkString)) { Add-Content $outputFile -Value $(Get-Date) }
    

    【讨论】:

    • 见Get-Help about_Comparison_Operators 引用:Description: Containment operator. Tells whether a collection of reference values includes a single test value. Always eturns a Boolean value. Returns TRUE only when the test value exactly matches at least one of the reference values.
    • @LotPings:如果您正在寻找与MSLogonRequired=1 完全匹配的行(大小写变化除外),这种方法可以正常工作。
    • @mklement0 同意,重点在于精确,仅尾随空格不会完全匹配。
    猜你喜欢
    • 1970-01-01
    • 2011-01-10
    • 1970-01-01
    • 2019-04-04
    • 2019-01-26
    • 2010-09-29
    • 2023-03-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多