运行 命令依赖于 OS 且 IF 服务存在

Run command dependent on OS and IF service is present

我有如下 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 主机)的不同脚本,因为 Web 管理模块不适用于 II6。

我需要添加一个 if 语句,该语句将根据主机操作系统以及 W3SVC 服务(万维网发布服务)是否存在(运行宁或停止)。沿线的东西

IF W3SVC is present
  Check host operating system
  IF operating system = Windows 2003
    Run II6 code
  Else
    Run II7+ code

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

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

(Get-WmiObject Win32_OperatingSystem).Name

使用 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-WmiObjectWin32_Service class 上,如果 Get-Service cmdlet 在 PowerShell v2 中不可用(对此不确定):

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