利用PowerShell脚本获取IIS绑定的网站地址和状态

来源:互联网 发布:数据冗余 编辑:程序博客网 时间:2024/06/14 03:38

最近接到一个客户的项目需求方案是这样子的,需要用脚本实现获取windows server系列服务器的iis绑定的主机域名和运行状态。


话不多说直接上脚本代码


<#
Script Editor: Snail Yu
Date: 2017-12-13
#>


foreach($ip in (ipconfig) -like '*IPv4*') { ($ip -split ' : ')[-1]}  #获取服务器IP地址
$IISsetting=Get-Content "C:\windows\system32\inetsrv\config\applicationHost.config"
$BindingInformation=((($IISsetting -match "bindinginformation") -split "information="-replace '"',"") -match ":"   
$BindingPort=(($BindingInformation -split ":") -match "[0-9]$") -notmatch "\." 
 
echo $BindingPort |sort -unique  #列出iis绑定端口
IIS的配置文档是"C:\windows\system32\inetsrv\config\applicationHost.config"; 

参数说明:

split: 以引号中的文本参数来分割整行文本,并返回分割后的结果文本;

match: 匹配包含文本所在的行,并显示匹配的行;

notmatch:匹配包含文本所在的行,并显示不匹配的行;

-replace 'var1',"var2"   :用var2来替代文本中的var1,并返回替代后的文本;

sort: 排序;“-unique”返回唯一值,避免重复显示;

IIS中每个网站可以绑定多个IP地址或者端口号,使用PowerShell可以获取这些配置的链接,并用来访问该网站。

要求

  • 如果一个网站有绑定的主机名或者域名,优先以域名作为域名。
  • 如果没有域名配置,以配置的绑定的IP地址作为主机名。
  • 如果IP地址未配置,则获取本机的IPV4地址作为主机名。
  • 如果端口为80端口,在网站地址中不予显示。

脚本

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
Import-Module WebAdministrationImport-Module : 进程应具有提升的状态才能访问 IIS 配置数据。

functionGet-IISWebsiteUrl([string]$name)
{
     (Get-Website$name).bindings.Collection | foreach{
     $bindingTokens$_.bindingInformation-split':'
     $siteHost=''
     $port=''
     $protocol=$_.protocol
     if($bindingTokens[2] -ne'')
     {
        $siteHost=$bindingTokens[2]
     }
     elseif($bindingTokens[0] -ne'*')
     {
       $siteHost=$bindingTokens[0]
     }
     else    
     {
        $siteHost[net.dns]::GetHostAddresses('') |
        where { $_.AddressFamily -eq'InterNetwork'} |
        select-ExpandPropertyIPAddressToString  -First 1
     }
      
     if($bindingTokens[1] -eq'80')  { $port=''}
     else{$port":"+$bindingTokens[1]}
          
      '{0}://{1}{2}'-f$protocol,$siteHost,$port
    }   
}

测试

Get-IISWebsiteUrl -name 'PrivateMemory.CN' http://192.168.190.84:8080http://www.pstips.net

powershell创建iis站点、应用程序及应用程序池

try{    Import-Module WebAdministration -ErrorAction Stop}catch [System.SystemException]{    Write-Host -foregroundColor "Red" "请先安装IIS管理脚本和工具:"    Write-Host -foregroundColor "Red" "Win2008 *,角色-->添加角色--->功能工具下面的'IIS管理脚本和工具'"    Write-Host -foregroundColor "Red" "Win7 在卸载程序中,点击'打开或关闭Windows功能'"    break}function CreateWebSite([string]$siteName,[string]$physicalPath,[string]$ports){    if(GetSite $siteName)    {        #todo: 待优化        Write-Host "站点已经存在"        return    }    $bindings = CheckBindingInfo $ports    try    {        $site = New-Item IIS:\Sites\$siteName -bindings $bindings -physicalPath $physicalPath -ErrorAction Stop        #todo: 待优化                $site.enabledProtocols = "http,net.tcp"    }catch [System.SystemException]    {        Write-Host "创建站点失败"        break    }    #todo: 待优化    CreateAppPool $siteName    Set-ItemProperty IIS:\Sites\$siteName -name applicationPool -value $siteName    return $site}function CreateApplication([string]$siteName,[string]$appName,[string]$appPhysPath){    #todo: 待优化    if(GetApplication $siteName $appName)    {        Write-Host "应用程序已经存在"        return    }    if(GetSite $siteName)    {        $app = New-Item IIS:\Sites\$siteName\$appName  -physicalPath $appPhysPath -type Application        $site = Get-Item "IIS:\Sites\$siteName"        Set-ItemProperty IIS:\Sites\$siteName\$appName -name applicationPool -value $site.applicationPool        return $app    }}function CheckBindingInfo([string]$ports){    $portList=$ports.split(',')    $bindA = @{}    $bindB = @{}    $portA = $portList[0]    $portB = $portList[1]    if($portList.Length -ne 2)    {            Write-Host "格式错误"        break    }    if(![string]::IsNullOrEmpty($portA.trim()))    {        $bindA=@{protocol="http";bindingInformation="*:"+$portA+":"}    }        if(![string]::IsNullOrEmpty($portB.trim()))    {        $bindB=@{protocol="net.tcp";bindingInformation=$portB+":"}    }    if(($bindA.Count -eq 0) -and !($bindB.Count -eq 0))    {        return $bindB    }    if(!($bindA.Count -eq 0) -and ($bindB.Count -eq 0))    {        return $bindA    }    if(!($bindA.Count -eq 0) -and !($bindB.Count -eq 0))    {        return $bindA,$bindB    }        return $null}function CreateAppPool([string]$appPool,[string]$runtimeVersion="v4.0",[int]$pipelineMode=1){    #待优化    $apool = New-Item IIS:\AppPools\$appPool    Set-ItemProperty IIS:\AppPools\$appPool managedRuntimeVersion $runtimeVersion    #1:Classic or 0:Integrated    Set-ItemProperty IIS:\AppPools\$appPool managedPipelineMode $pipelineMode    return $apool}function GetSite([string]$siteName){    try    {        $site = Get-Item "IIS:\Sites\$siteName" -ErrorAction Stop        return $site    }catch [System.SystemException]    {        #Write-Host -foregroundColor "Red" "获取站点 $siteName 信息失败"        return $null    }}function GetApplication([string]$siteName,[string]$appName){    if(GetSite $siteName)    {    try    {        $app = Get-Item "IIS:\Sites\$siteName\$appName" -ErrorAction Stop        return $app    }catch [System.SystemException]    {        #Write-Host -foregroundColor "Red" "获取应用程序 $appName 失败"        return $null    }    }}function Pause{    Write-Host "Press any key to continue ..."    [Console]::ReadKey($true)|Out-Null    Write-Host}try{    Import-Module WebAdministration -ErrorAction Stop}catch [System.SystemException]{    Write-Host -foregroundColor "Red" "请先安装IIS管理脚本和工具:"    Write-Host -foregroundColor "Red" "Win2008 *,角色-->添加角色--->功能工具下面的'IIS管理脚本和工具'"    Write-Host -foregroundColor "Red" "Win7 在卸载程序中,点击'打开或关闭Windows功能'"    break}function CreateWebSite([string]$siteName,[string]$physicalPath,[string]$ports){    if(GetSite $siteName)    {        #todo: 待优化        Write-Host "站点已经存在"        return    }    $bindings = CheckBindingInfo $ports    try    {        $site = New-Item IIS:\Sites\$siteName -bindings $bindings -physicalPath $physicalPath -ErrorAction Stop        #todo: 待优化                $site.enabledProtocols = "http,net.tcp"    }catch [System.SystemException]    {        Write-Host "创建站点失败"        break    }    #todo: 待优化    CreateAppPool $siteName    Set-ItemProperty IIS:\Sites\$siteName -name applicationPool -value $siteName    return $site}function CreateApplication([string]$siteName,[string]$appName,[string]$appPhysPath){    #todo: 待优化    if(GetApplication $siteName $appName)    {        Write-Host "应用程序已经存在"        return    }    if(GetSite $siteName)    {        $app = New-Item IIS:\Sites\$siteName\$appName  -physicalPath $appPhysPath -type Application        $site = Get-Item "IIS:\Sites\$siteName"        Set-ItemProperty IIS:\Sites\$siteName\$appName -name applicationPool -value $site.applicationPool        return $app    }}function CheckBindingInfo([string]$ports){    $portList=$ports.split(',')    $bindA = @{}    $bindB = @{}    $portA = $portList[0]    $portB = $portList[1]    if($portList.Length -ne 2)    {            Write-Host "格式错误"        break    }    if(![string]::IsNullOrEmpty($portA.trim()))    {        $bindA=@{protocol="http";bindingInformation="*:"+$portA+":"}    }        if(![string]::IsNullOrEmpty($portB.trim()))    {        $bindB=@{protocol="net.tcp";bindingInformation=$portB+":"}    }    if(($bindA.Count -eq 0) -and !($bindB.Count -eq 0))    {        return $bindB    }    if(!($bindA.Count -eq 0) -and ($bindB.Count -eq 0))    {        return $bindA    }    if(!($bindA.Count -eq 0) -and !($bindB.Count -eq 0))    {        return $bindA,$bindB    }        return $null}function CreateAppPool([string]$appPool,[string]$runtimeVersion="v4.0",[int]$pipelineMode=1){    #待优化    $apool = New-Item IIS:\AppPools\$appPool    Set-ItemProperty IIS:\AppPools\$appPool managedRuntimeVersion $runtimeVersion    #1:Classic or 0:Integrated    Set-ItemProperty IIS:\AppPools\$appPool managedPipelineMode $pipelineMode    return $apool}function GetSite([string]$siteName){    try    {        $site = Get-Item "IIS:\Sites\$siteName" -ErrorAction Stop        return $site    }catch [System.SystemException]    {        #Write-Host -foregroundColor "Red" "获取站点 $siteName 信息失败"        return $null    }}function GetApplication([string]$siteName,[string]$appName){    if(GetSite $siteName)    {    try    {        $app = Get-Item "IIS:\Sites\$siteName\$appName" -ErrorAction Stop        return $app    }catch [System.SystemException]    {        #Write-Host -foregroundColor "Red" "获取应用程序 $appName 失败"        return $null    }    }}function Pause{    Write-Host "Press any key to continue ..."    [Console]::ReadKey($true)|Out-Null    Write-Host}

用的时候
CreateWebSite "sitename" "C:sitepath" "8094,4506"
CreateApplication "sitename" "site_app_name" "app_path"

 

WinServer2008下通过powershell获取IIS等角色功能列表,保存至txt                                                                       
Set objShell = CreateObject("WScript.Shell")strCommondLine = "powershell.exe"app = objShell.Run(strCommondLine)objShell.AppActivate appWScript.Sleep 100strCommond = "Import-Module ServerManager {ENTER} Get-WindowsFeature|out-file IISServiceList.txt -Encoding UTF8 {ENTER} Exit {ENTER}"objShell.SendKeys strCommondWScript.quit


Windows编程开发的WMI相关参考资料(Win32)

WMI详细介绍和架构(英文版):http://msdn.microsoft.com/en-us/library/aa394582(v=vs.85).aspx

WMI脚本入门第一部分(中文版):http://msdn.microsoft.com/zh-cn/library/ms974579.aspx#EFAA

WMI脚本入门第二部分(中文版):http://msdn.microsoft.com/zh-cn/library/ms974592.aspx

WMI脚本入门第三部分(中文版):http://msdn.microsoft.com/zh-cn/library/ms974547.aspx



WMI Explorer : http://www.ks-soft.net/hostmon.eng/wmi/index.htm

WMI Administrator Tools : https://www.microsoft.com/en-us/download/details.aspx?id=24045


[Powershell] 检查IIS设置


$script:OutMessage = "ok"function WriteLog([string]  $content){    #Write-Host $content    $script:OutMessage += $content + "`r`n"}Import-Module WebAdministration#获取所有Application PoolsWriteLog "开始检查IIS应用程序池..."Get-ChildItem IIS:\apppools | ForEach-Object{    $appPoolName =  $_.Name    WriteLog("开始检查应用程序池: " + $_.name)    $appPool = $_    #检查回收设置    $RecyclingTime = $appPool.recycling.periodicRestart.time.TotalMinutes    WriteLog ("--自动回收周期(Minutes):" + $RecyclingTime)    #检查账号设置    $identityType = $appPool.processModel.identityType    WriteLog("--账号类型:" + $identityType)    $userName = $appPool.processModel.userName    WriteLog("--用户:" + $userName)    #$password = $appPool.processModel.password    #生成回收事件日志设置    $LogEventOnRecycle = $appPool.recycling.logEventOnRecycle    WriteLog("--LogEventOnRecycle:"+ $LogEventOnRecycle)    #把Idle Timeout设为0    $IdleTimeout = $appPool.processModel.idleTimeout    WriteLog("--IdleTimeout:"+ $IdleTimeout)    #最大工作进程数设置为0,支持NUMA    $maxProcesses = $appPool.processModel.maxProcesses    WriteLog("--maxProcesses:"+ $maxProcesses)    WriteLog (" ")}WriteLog "开始检查IIS网站..."Get-ChildItem IIS:\Sites | ForEach-Object{    $site = $_    WriteLog ("开始检查站点: " + $site.name)    #检查网站日志目录    WriteLog ("--是否开启IISLOG:" + $site.logFile.enabled)    WriteLog ("--日志字段:" + $site.logFile.logExtFileFlags)    WriteLog ("--日志存放路径:" + $site.logFile.directory)    WriteLog ("--日志文件大小:" + $site.logFile.truncateSize)    WriteLog (" ")}$OutMessage

执行策略限制

Powershell一般初始化情况下都会禁止脚本执行。脚本能否执行取决于Powershell的执行策略。

PS E:> .\MyScript.ps1无法加载文件 E:MyScript.ps1,因为在此系统中禁止执行脚本。有关详细信息,请参阅 "get-help about_signing"。所在位置 行:1 字符: 15+ .MyScript.ps1 < <<<    + CategoryInfo          : NotSpecified: (:) [], PSSecurityException    + FullyQualifiedErrorId : RuntimeException

只有管理员才有权限更改这个策略。非管理员会报错。

查看脚本执行策略,可以通过:

PS E:> Get-ExecutionPolicy

更改脚本执行策略,可以通过

PS E:> Get-ExecutionPolicyRestrictedPS E:> Set-ExecutionPolicy UnRestricted  #powershell的默认安全设置禁用了执行脚本,要启用这个功能需要拥有管理员的权限。
执行策略更改

Powershell调用入口的优先级

别名:控制台首先会寻找输入是否为一个别名,如果是,执行别名所指的命令。因此我们可以通过别名覆盖任意powershell命令,因为别名的优先级最高。

函数:如果没有找到别名,会继续寻找函数,函数类似别名,只不过它包含了更多的powershell命令。因此可以自定义函数扩充cmdlet 把常用的参数给固化进去。

命令:如果没有找到函数,控制台会继续寻找命令,即cmdlet,powershell的内部命令。

脚本:没有找到命令,继续寻找扩展名为“.ps1”的Powershell脚本。

文件:没有找到脚本,会继续寻找文件,如果没有可用的文件,控制台会抛出异常。


利用VBS批量导出/读取IIS域名、主机头、存放路径等

<%'修改了iis基本函数,可以导出任意你想的数据option explicitdim fsoSet FSO = Server.CreateObject("Scripting.FileSystemObject")dim tsSet ts = fso.OpenTextFile(server.MapPath("iis.xml"),1)  '修改此处的iis备份文件名即可,同目录下哦dim content,contentdircontent= ts.ReadAllcontentdir=contentcontent=split(content,"<IIsWebServer")'取主相关字段'splitStr可以为你想要截取的标识如:ServerComment、AppFriendlyName、Path'zswfunction getStr(str,splitStr)dim reg,readstr,matches,match1set reg=new Regexpreg.Multiline=Truereg.Global=falsereg.IgnoreCase=truereg.Pattern=splitStr&"(.*)\s"Set matches = reg.execute(str)  For Each match1 in matches   readstr=match1.Value  NextSet matches = NothingSet reg = NothinggetStr=replace(readstr,splitStr&"=","")getStr=replace(getStr,"""","")end function'取字段'www.sql8.net   'yxyfunction GetKey(HTML,Start,Last)dim filearray,filearray2filearray=split(HTML,Start)filearray2=split(filearray(1),Last)GetKey=filearray2(0)End functionfunction Clear(content)dim arr,iarr=split(content,":")for i=0 to ubound(arr)if instr(arr(i),".")>0 thenClear=Clear & arr(i)&"<Br/>"end ifnextend function'取文件存放的目录contentdir=split(contentdir,"<IIsWebVirtualDir") response.Clear()dim ifor i=0 to ubound(content)if instr(content(i),"ServerBindings")>0 thenresponse.Write (i)&" 描述:"&getStr(content(i),"ServerComment")&"<br>主机头:<br/>"&Clear(GetKey(content(i),"ServerBindings=""",""""))response.write("文件目录:"&getStr(contentdir(i),"Path")&"<BR/><Br/>")end ifnext%>

 

PowerShell管理IIS(新建站点、应用程序池、应用程序、虚拟目录等)

 

复制代码
 1 #导入IIS管理模块 2 Import-Module WebAdministration 3   4   5 #新建应用程序池 api.dd.com  6 New-Item iis:\AppPools\api.dd.com 7 Set-ItemProperty iis:\AppPools\api.dd.com managedRuntimeVersion v4.0 #更改应用程序池版本为4.0,默认为2.0(Windows Server 2008 R2) 8 #新建站点 api.dd.com,主机头为 api.dd.com,路经为 d:\apidd 9 New-Item iis:\Sites\api.dd.com -bindings @{protocol="http";bindingInformation=":80:api.dd.com"} -physicalPath d:\apidd10 11 #为站点 api.dd.com 添加主机头 imageapi.dd2.com12 New-WebBinding -Name "api.dd.com" -IPAddress "*" -Port 80 -HostHeader imageapi.dd2.com13 14 #为站点 api.dd.com 更改应用程序池为 api.dd.com15 Set-ItemProperty IIS:\Sites\api.dd.com -name applicationPool -value api.dd.com16 17 #在站点api.dd.com下新建应用程序cust_account_api ,目录为D:\cust_account_api_new18 new-item iis:\sites\api.dd.com\cust_account_api -type Application -physicalpath D:\cust_account_api_new19 Set-ItemProperty IIS:\Sites\api.dd.com\cust_account_api -name applicationPool -value api.dd.com20 21 #在站点ServerLog下新建虚拟目录cust_account_api ,目录为D:\cust_account_api_new\log22 new-item D:\cust_account_api_new\log -type directory -force 23 new-item iis:\sites\ServerLog\cust_account_api -type VirtualDirectory -physicalpath D:\cust_account_api_new\log
复制代码

 

New-Website

#新建IISLog站点New-Website -Name IISLog -Port 11001 -PhysicalPath "D:\IISLog"New-WebVirtualDirectory -Site IISLog -Name APPLog -PhysicalPath D:\APPLogNew-WebVirtualDirectory -Site IISLog -Name SystemLog -PhysicalPath  C:\Windows\System32\Winevt\Logs

 

更改IIS站点的物理路径:

Set-ItemProperty "iis:\sites\Default Web Site" -Name physicalpath -Value "c:\inetpub"

使用appcmd.exe:

New-Alias -name appcmd -value $env:windir\system32\inetsrv\appcmd.exe

这样就可以在当前PS环境下直接使用appcmd了

 

get-website

备份/还原单个站点:

1.appcmd add backup 2.remove-website|?{$_.name -ne "sitename"}

在IIS7上导出所有应用程序池的方法批量域名绑定

一点经验:导出配置文件后,建议打开看看,如果有需要调整的需要做修改。 

在IIS7+上导出所有应用程序池的方法:
%windir%/system32/inetsrv/appcmd list apppool /config /xml > c:/apppools.xml

这个命令会将服务器上全部的应用程序池都导出来,但有些我们是我们不需要的,要将他们删掉.比如:
DefaultAppPool
Classic .Net AppPool
如果在导入时发现同名的应用程序池已经存在,那么导入就会失败.

导入应用程序池的方法: 
%windir%/system32/inetsrv/appcmd add apppool /in < c:/apppools.xml

这样就可以将全部的应用程序池都导入到另一个服务器中了.

导出全部站点的方法:
%windir%/system32/inetsrv/appcmd list site /config /xml > c:/sites.xml

同样,我们需要编辑sites.xml文件删除不需要的站点.如:
Default Website

导入站点的方法:
%windir%/system32/inetsrv/appcmd add site /in < c:/sites.xml

至此,导入工作完成了,看看两台服务器的IIS配置一样了吧. 

另外,介绍下单独导出导入一个站点的方法
导出单独应用程序池:
%windir%/system32/inetsrv/appcmd list apppool “应用程序池名称” /config /xml > c:/myapppool.xml
黄色字体的就是要导出的应用程序池名称 

导入单独应用程序池:
%windir%/system32/inetsrv/appcmd add apppool /in < c:/myapppool.xml

导出单独站点:
%windir%/system32/inetsrv/appcmd list site “站点名称” /config /xml > c:/mywebsite.xml 
黄色字体的就是要导出的站点名称 

导入单独站点:
%windir%/system32/inetsrv/appcmd add site /in < c:/cnziben.com.xml

参考: https://www.microsoftpro.nl/2011/01/27/exporting-and-importing-sites-and-app-pools-from-iis-7-and-7-5/

程序附件[免费]CS4IIS.exe IIS服务器域名批量查找下载 http://download.csdn.net/download/summerll/2196079









阅读全文
0 0