【问题标题】:Run command dependent on OS and IF service is present运行命令依赖于操作系统和 IF 服务存在
【发布时间】:2016-05-09 16:06:17
【问题描述】:

我有 2 个脚本如下,用于获取 IIS 网站。

IIS 6 -

$website = Get-WmiObject -Class IIsWebServerSetting -Namespace "root\microsoftiisv2" | Select ServerComment | Format-Table -HideTableHeaders | out-file c:\website.txt
$b = Get-Content -Path C:\website.txt
$b | ForEach {$_.TrimEnd()} | ? {$_.trim() -ne '' } > C:\website.txt
$b = Get-Content -Path C:\website.txt
@(ForEach ($a in $b) {$a.Replace(' ', '')}) > C:\website.txt
Get-Content C:\website.txt

IIS 7+

Import-Module webadministration
$a = Get-Website | Select-Object Name
$a | ForEach-Object { 
$_.name = $_.name.replace(" ","")
}
$a | Format-Table -HideTableHeaders | Out-File $DeviceDrive\Apps\NetprobeNT\Auto-monitor\Website.txt
$b = Get-Content -Path $DeviceDrive\Apps\NetprobeNT\Auto-monitor\Website.txt
$b | ForEach {$_.TrimEnd()} | ? {$_.trim() -ne '' } > $DeviceDrive\Apps\NetprobeNT\Auto-monitor\Website.txt
$b = Get-Content -Path $DeviceDrive\Apps\NetprobeNT\Auto-monitor\Website.txt
@(ForEach ($a in $b) {$a.Replace(' ', '')}) > $DeviceDrive\Apps\NetprobeNT\Auto-monitor\Website.txt

我有一个用于 IIS 6(Windows 2003 主机)的不同脚本,因为 webadministration 模块不适用于 II6。

我需要添加一个if 语句,该语句将添加逻辑以运行依赖于主机操作系统的正确代码,以及是否存在 W3SVC 服务(万维网发布服务)(运行或停止)。有点像

如果存在 W3SVC
  检查主机操作系统
  IF 操作系统 = Windows 2003
    运行 II6 代码
  别的
    运行II7+代码

我不知道从哪里开始这个脚本。 PowerShell 和脚本对我来说是新的,这是我正在创建的第一个脚本的一部分。任何帮助将不胜感激。

我可以获得主机操作系统,但对如何将逻辑放入其中以获得所需的结果感到困惑。

(Get-WmiObject Win32_OperatingSystem).Name

【问题讨论】:

    标签: powershell iis powershell-2.0


    【解决方案1】:

    使用Caption 而不是Name。除此之外,您只需将例程插入伪代码:

    if ((Get-WmiObject Win32_OperatingSystem).Caption -eq 'Windows 2003') {
      # Run II6 code
    } else {
      # Run II7+ code
    }
    

    对于服务,您可以使用Get-Service cmdlet:

    if (Get-Service -Name w3svc -ErrorAction SilentlyContinue) {
      ...
    }
    

    如果 Get-Service cmdlet 在 PowerShell v2 中不可用(不确定),则在 Win32_Service 类上使用 Get-WmiObject

    if (Get-WmiObject Win32_Service -Filter "Name='w3svc'") {
      ...
    }
    

    【讨论】:

    • 感谢您的快速回复,这是否适用于不同版本的 Windows 2003 主机,即 Windows 2003 Service Pack 2。它在任何地方都不需要 * 吗?另外我如何将 IF 语句组合在一起?
    • 如果您需要处理不同的 Windows Server 版本(如 Standard 和 Enterprise),则需要通配符匹配。服务包信息不应显示在标题中。至于结合陈述:考虑你的家庭作业。应该不会太难,因为你已经有了伪代码。
    • 刚刚测试过合并。我在第一个 IF 语句中放置了一个 IF 语句。 Ive 尝试安装 Windows 2003*,但不断出错。我是否正确使用了通配符?
    • 你换过运营商吗?您需要使用-like 而不是-eq 进行通配符匹配。
    • 谢谢@Ansgar Wiechers,这很有效。我在 2008 主机上测试了以下内容 - if ((Get-WmiObject Win32_OperatingSystem).Caption -like " * Windows server 2008 * ")。只是为了确认通配符在单词之前是否有效?它似乎正在工作
    猜你喜欢
    • 2013-10-21
    • 1970-01-01
    • 2013-09-01
    • 2019-10-18
    • 2015-11-28
    • 2012-02-06
    • 2020-06-12
    • 2017-12-25
    • 2020-05-27
    相关资源
    最近更新 更多