gpt4 book ai didi

windows - Powershell - 如果不工作(Windows 服务检查)

转载 作者:行者123 更新时间:2023-12-05 01:53:52 27 4
gpt4 key购买 nike

我正在尝试构建自己的脚本来检查一些 Windows 服务(状态和启动模式),但我在 IF 上遇到了问题......例如,即使服务“正在运行”,它也永远不会运行 IF 内的代码...

让我在下面分享我的代码(我是 powershell 的新手所以要温柔 xD)

关于信息,我将在 IF 和 ELSE 中执行更多操作,这只是为了示例。

# import computers list, 1 by line
$Computers = get-content .\computers.txt

# define variable of services we want to check
$ServiceNetbios = "netbt"

# define variable to ask credentials
$Cred = Get-Credential

# declare Function to open a session a remote computer
Function EndPSS { Get-PSSession | Remove-PSSession }

EndPSS

########################################################
# BEGINNING OF SCRIPT #
# by xxx #
# 2022-02-03 #
########################################################


# loop for each computer imported from the file
foreach ($computer in $computers) {

# show name of computer in progress
$computer

# connect remotely to the computer
$session = New-PSSession -ComputerName $computer -Credential $Cred

# check Netbios service
$StatusServiceNetbios = Invoke-Command -Session $session -ScriptBlock { Get-Service -Name $Using:ServiceNetbios | select -property * }

# Check Netbios service started or not
write-host $StatusServiceNetbios.Status

if ($StatusServiceNetbios.Status -eq 'Running')
{
Write-host "IF Running"
}
else
{
write-host "IF NOT Running"
}

EndPSS

}

什么返回我的脚本:

computername
Running (<= the variable $StatusServiceNetbios.Status )
IF NOT Running (<= the ELSE action)

预先感谢您的帮助,这让我发疯,也许这很简单......

最佳答案

补充Cpt.Whale's helpful answer ,这很可能是由 Invoke-Command 完成的序列化反序列化引起的:

using namespace System.Management.Automation

$service = Get-Service netbt
$afterInvokeCmd = [PSSerializer]::Deserialize(([PSSerializer]::Serialize($service)))

$service.Status -eq 'Running' # => True
$afterInvokeCmd.Status -eq 'Running' # => False
$afterInvokeCmd.Status.Value -eq 'Running' # => True
$afterInvokeCmd.Status.ToString() -eq 'Running' # => True

为了说明我的回答的背景,这是来自 about_Remote_Output 的一段很好的引用这可以更好地解释为什么以及发生了什么:

Because most live Microsoft .NET Framework objects (such as the objects that PowerShell cmdlets return) cannot be transmitted over the network, the live objects are "serialized". In other words, the live objects are converted into XML representations of the object and its properties. Then, the XML-based serialized object is transmitted across the network.

On the local computer, PowerShell receives the XML-based serialized object and "deserializes" it by converting the XML-based object into a standard .NET Framework object.

However, the deserialized object is not a live object. It is a snapshot of the object at the time that it was serialized, and it includes properties but no methods.

关于windows - Powershell - 如果不工作(Windows 服务检查),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70973590/

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