【问题标题】:Powershell Inconsistency stringPowershell不一致字符串
【发布时间】:2021-08-13 14:18:28
【问题描述】:
$ServName = "" 

$UnnecessaryService = get-service

$UnnecessaryService | Out-File "UnnecessaryServices.txt"

$UnnecessaryService = gc UnnecessaryServices.txt | Select-String "CryptSvc"

$UnnecessaryService = Out-String -InputObject $UnnecessaryService

$UnnecessaryService = $UnnecessaryService.Split(' ')

$UnnecessaryService = $UnnecessaryService[0]

$NowName = " Cryptographic Services"
write $UnnecessaryService

if ($UnnecessaryService -eq "Running")
{
    $ServName = $ServName + $NowName
    write $ServName
}
else
{
    $result = "good"
    write $result
}

我认为此代码输出必须是$ServName,但它打印的是$result。 所以我找出了问题所在。

然后$UnnecessaryService 链接中断。 底线是我想要$UnnecessaryService -eq "Running" 是正确的代码。帮帮我。

UnnecessaryServices.txt的内容是:

Status   Name               DisplayName                           
------   ----               -----------                                         
Running  CryptSvc           Cryptographic Services                

【问题讨论】:

  • 我的建议是完全重做这段代码,因为有太多看似不必要的文件交互。 $service = Get-Service <service name>; if ($service.status -eq 'Running') # run code

标签: string powershell


【解决方案1】:

无需将Get-Service 的输出写入文件 - 相反,您需要检查Get-Service 返回的对象的Status 属性:

# Get CryptSvc service controller
$cryptSvc = Get-Service CryptSvc

# test if it's running or not
if($cryptSvc.Status -eq 'Running'){
    # CryptSvc IS running
    '{0} is running...' -f $cryptSvc.DisplayName
}
else {
    # CryptSvc is NOT running
}

【讨论】:

    猜你喜欢
    • 2014-05-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-09
    • 2016-04-19
    • 2014-01-05
    • 2021-08-03
    • 2018-02-07
    相关资源
    最近更新 更多