Powershell Script Required to Recreate Existing Printers - powershell

I have printer RDS 2012 issues and using Group policy to create network printers
because printing reliablity is woeful on RDS 2012 and been a terminal services box net spooler stops and start
Group Policy Preferences is alo a bit unreliable
I would like the ability to recreate the printers using Powershell
Get-Printer | remove-printer get rid of them o.k
but how do I recreate printers.

On PowerShell 3 or less, You can use WMI,
You need to Create a Printer IP Port(win32_tcpipPrinterPort Class), add Driver(Win32_PrinterDriver Class), then create a printer(Win32_Printer Class),
You can use this helper functions, for each of the tasks:
Function CreatePrinterPort {
Param ($PrinterIP, $PrinterPort, $PrinterPortName, $ComputerName)
$wmi = [wmiclass]"\\$ComputerName\root\cimv2:win32_tcpipPrinterPort"
$wmi.psbase.scope.options.enablePrivileges = $true
$Port = $wmi.createInstance()
$Port.name = $PrinterPortName
$Port.hostAddress = $PrinterIP
$Port.portNumber = $PrinterPort
$Port.SNMPEnabled = $false
$Port.Protocol = 1
$Port.put()
}
Function InstallPrinterDriver {
Param ($DriverName, $DriverPath, $DriverInf, $ComputerName)
$wmi = [wmiclass]"\\$ComputerName\Root\cimv2:Win32_PrinterDriver"
$wmi.psbase.scope.options.enablePrivileges = $true
$wmi.psbase.Scope.Options.Impersonation = [System.Management.ImpersonationLevel]::Impersonate
$Driver = $wmi.CreateInstance()
$Driver.Name = $DriverName
$Driver.DriverPath = $DriverPath
$Driver.InfName = $DriverInf
$wmi.AddPrinterDriver($Driver)
$wmi.Put()
}
Function CreatePrinter
{
param ($PrinterCaption, $PrinterPortName, $DriverName, $ComputerName)
$wmi = ([WMIClass]"\\$ComputerName\Root\cimv2:Win32_Printer")
$Printer = $wmi.CreateInstance()
$Printer.Caption = $PrinterCaption
$Printer.DriverName = $DriverName
$Printer.PortName = $PrinterPortName
$Printer.DeviceID = $PrinterCaption
$Printer.Put()
}
Example use:
Create Port:
CreatePrinterPort -PrinterIP 192.168.100.100 -PrinterPort 9100 -PrinterPortName 192.168.100.100 -ComputerName $Computer
Install Driver:
InstallPrinterDriver -ComputerName $Computer -DriverName "Xerox Phaser 3600 PCL 6" -DriverPath "C:\PrinterDrivers\Xerox\x64" -DriverInf "C:\PrinterDrivers\Xerox\x64\sxk2m.inf"
Add Printer:
CreatePrinter -PrinterCaption "Xerox Phaser 3600 PCL 6" -PrinterPortName "192.168.100.100" -DriverName "Xerox Phaser 3600 PCL 6" -ComputerName $Computer
Needless to say, You need Admin Permissions on the target computer...
Good luck

Before you remove the printers safe the information about them in a variable.
After the removing step you can add them with the cmdlet Add-printer.

Related

DCOM machine level access and launch permissions via PowerShell

Is it possible to set machine level "My Computer" access and launch permissions from PowerShell?
The equivalent of
DComPerm.exe -ma set name permit level:l,r
DComPerm.exe -ml set name permit level:l,r
I am looking for a solution using PowerShell v 3.0. The target servers are Windows Server 2008 R2 and 2012.
I have found a number of references for setting the DCOM application security settings. However I can't figure out how to set it at the machine or top level.
https://janbk.wordpress.com/2015/03/12/automating-dcom-acl-with-powershell/
Alternative to using DcomPerm.exe and SetAcl.exe in powershell
We have been using WMI to set Launch Permissions.
Refer: https://rkeithhill.wordpress.com/2013/07/25/using-powershell-to-modify-dcom-launch-activation-settings/
This stopped working after windows security patches rolled out (patch #: 4012212, 4012213, and 4012213)
We converted WIM powershell script to use CIM and that took care of setting launch permissions on DCOM objects & works with the security patches. Code is below for reference:
$ComponentName = "TestComponent" #--- change value as needed
$Username = "Username" #--- change value as needed
$Domain = "Domain" #--- change value as needed
# If you already have a CimSession that you used to get the security descriptor, you can leave this line out and use the existing one:
$CimSession = New-CimSession localhost
Grant-DComAccessToUser -ComponentName $ComponentName -Username $Username -Domain $Domain
# Cleanup
$CimSession | Remove-CimSession
function Grant-DComAccessToUser {
param(
[Parameter(Mandatory=$true)][string] $ComponentName,
[Parameter(Mandatory=$true)][string] $Username,
[string] $Domain
)
$DCom = Get-CimInstance -Query "SELECT * from Win32_DCOMApplicationSetting WHERE Description LIKE '$ComponentName%'"
$GetDescriptor = Invoke-CimMethod -InputObject $DCom -MethodName "GetLaunchSecurityDescriptor";
$ExistingDacl = $GetDescriptor.Descriptor.DACL | Where {$_.Trustee.Name -eq $Username}
if ($ExistingDacl)
{
$ExistingDacl.AccessMask = 11
}
else
{
$NewAce = New-DComAccessControlEntry -Domain $Domain -Username $Username
$GetDescriptor.Descriptor.DACL += $NewAce
}
Invoke-CimMethod -InputObject $DCom -MethodName "SetLaunchSecurityDescriptor" -Arguments #{Descriptor=$GetDescriptor.Descriptor};
}
function New-DComAccessControlEntry {
param(
[Parameter(Mandatory=$true)][string] $Username,
[string] $Domain
)
# Create the Win32_Trustee instance
$Trustee = New-Object ciminstance $CimSession.GetClass("root/cimv2", "Win32_Trustee")
$Trustee.Name = $Username
$Trustee.Domain = $Domain
# Create the Win32_ACE instance
$Ace = New-Object ciminstance $CimSession.GetClass("root/cimv2", "Win32_ACE")
$Ace.AceType = [uint32] [System.Security.AccessControl.AceType]::AccessAllowed
$Ace.AccessMask = 11
$Ace.AceFlags = [uint32] [System.Security.AccessControl.AceFlags]::None
$Ace.Trustee = $Trustee
$Ace
}
You can change this script: https://gallery.technet.microsoft.com/scriptcenter/Grant-Revoke-Get-DCOM-22da5b96. It works with application permissions using registry path "HKCR:\AppID\$ApplicationID" and registry keys "AccessPermission", "LaunchPermission".
You should use registry path "HKLM:SOFTWARE\Microsoft\Ole" and registry keys "DefaultAccessPermission", "DefaultLaunchPermission", "MachineAccessRestriction", "MachineLaunchRestriction".
More info in "Configuring Remote DCOM" chapter: https://books.google.ru/books?id=rbpNppFdipkC&pg=PT211&lpg=PT211&dq=dcom+grant+local+launch+permission+powershell&source=bl&ots=5ZfeVca5NA&sig=9lMN_VeymG8cf73KT062QTsWWkc&hl=ru&sa=X&ved=0ahUKEwikn73f6YLcAhVEDSwKHUftCwkQ6AEIfDAI#v=onepage&q&f=true

Unable to create printers on Windows 2008 using WMI Class

When using the below code to create printer on Windows 2008 servers to create the printers
`function CreatePrinterPort {
$server = $args[0]
$port = ([WMICLASS]“\\$server\ROOT\cimv2:Win32_TCPIPPrinterPort").createInstance()
$port.Name= $args[1]
$port.SNMPEnabled=$false
$port.Protocol=2
$port.HostAddress= $args[2]
$port.Put()
}
function CreatePrinter {
$server = $args[0]
$print = ([WMICLASS]“\\$server\ROOT\cimv2:Win32_Printer”).createInstance()
$print.Drivername = $args[1]
$print.PortName = $args[2]
$print.Shared = $true
$print.Published = $false
$print.Sharename = $args[3]
$print.Location = $args[4]
$print.Comment = $args[5]
$print.DeviceID=$args[2]
$print.Put()
}
$printers = Import-Csv “C:\printers.csv”
foreach ($printer in $printers) {
CreatePrinterPort $printer.Printserver $printer.Portname $printer.IPAddress
CreatePrinter $printer.Printserver $printer.Driver $printer.Portname $printer.Sharename $printer.Location $printer.Comment $printer.Printername
}'
I am getting the following error. The port creation function is working.
"IsSingleton : False
Exception calling "Put" with "0" argument(s): "Generic failure "
At line:23 char:1
+ $print.Put()
+ ~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : DotNetMethodException"
I have importing all the details from a CSV file and it contains all the information.
Any suggestions?
I'm pretty sure you're both doing this the hard way, and didn't read the MSDN page for the Win32_Printer class. It says in the remarks that you have to enable the SeDriverUpdate privilege before you can issue the Put method, so I have a feeling that's where you're getting your error from.
Next, use the Set-WMIInstance cmdlet, or the newer 'New-CIMInstance` if you can. Calling the classes directly is possible I'm sure, but if the server is local it won't enable the privileges that you need to create a printer.
Lastly, you could make your function better if you made it an advanced function, and allowed piped data. Check this out:
function CreatePrinter {
[cmdletbinding()]
Param(
[Parameter(ValueFromPipelineByPropertyName=$true)]
[Alias('Printserver')]
$Server,
[Parameter(ValueFromPipelineByPropertyName=$true)]
[Alias('Driver')]
$Drivername,
[Parameter(ValueFromPipelineByPropertyName=$true)]
$PortName,
[Parameter(ValueFromPipelineByPropertyName=$true)]
$Sharename,
[Parameter(ValueFromPipelineByPropertyName=$true)]
$Location,
[Parameter(ValueFromPipelineByPropertyName=$true)]
$Comment,
[Parameter(ValueFromPipelineByPropertyName=$true)]
[Alias('IPAddress')]
$HostAddress,
[Parameter(ValueFromPipelineByPropertyName=$true)]
[Alias('PrinterName')]
$Name
)
PROCESS{
$PortArgs = #{
Name = $PortName
SNMPEnabled = $false
Protocol = 2
HostAddress = $HostAddress
}
Set-WmiInstance -Class Win32_TCPIPPrinterPort -Arguments $PortArgs -ComputerName $Server -PutType UpdateOrCreate -EnableAllPrivileges
$PrinterArgs = #{
Drivername = $Drivername
PortName = $PortName
Shared = $true
Published = $false
Sharename = $Sharename
Location = $Location
Comment = $Comment
DeviceID = $PortName
Name = $Name
}
Set-WmiInstance -Class Win32_Printer -Arguments $CmdArgs -ComputerName $Server -PutType UpdateOrCreate -EnableAllPrivileges
}
}
That creates the port, and then the printer. I suppose you could split it into two functions, but do you really see needing one without the other? Plus you can pipe your CSV data directly into it like this:
Import-CSV "C:\printers.csv" | CreatePrinter
That's it, that will create ports and printers for all records in the CSV. Plus I used the UpdateOrCreate enum, so if something isn't right you could correct the CSV and just run it again to refresh the settings to the correct settings without having to worry about deleting old copies and making new copies of things.

Powershell : How to get Antivirus product details

We have over 1500 servers. Windows 2003, 2008 and 2012. I have to gather the details of antivirus(Product Name & Version) on these servers.
There could be multiple antivirus product.
I am not sure powershell script will work on 2003 server.
So, far i tried below scripts but not got useful information.
$av = get-wmiobject -class "Win32_Product" -namespace "root\cimv2" `
-computername "." -filter "Name like '%antivirus%'"
Below script is working fine on client operating system.
$wmiQuery = "SELECT * FROM AntiVirusProduct"
$AntivirusProduct = Get-WmiObject -Namespace "root\SecurityCenter2" -Query $wmiQuery #psboundparameters # -ErrorVariable myError -ErrorAction 'SilentlyContinue'
Write-host $AntivirusProduct.displayName
Can anybody advise me on this?
I am trying to get the details of antivirus(Product & Version)
What do i need to do for win server 2003?
You were on the right path, the following Powershell script works.
function Get-AntiVirusProduct {
[CmdletBinding()]
param (
[parameter(ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)]
[Alias('name')]
$computername=$env:computername
)
#$AntivirusProducts = Get-WmiObject -Namespace "root\SecurityCenter2" -Query $wmiQuery #psboundparameters # -ErrorVariable myError -ErrorAction 'SilentlyContinue' # did not work
$AntiVirusProducts = Get-WmiObject -Namespace "root\SecurityCenter2" -Class AntiVirusProduct -ComputerName $computername
$ret = #()
foreach($AntiVirusProduct in $AntiVirusProducts){
#Switch to determine the status of antivirus definitions and real-time protection.
#The values in this switch-statement are retrieved from the following website: http://community.kaseya.com/resources/m/knowexch/1020.aspx
switch ($AntiVirusProduct.productState) {
"262144" {$defstatus = "Up to date" ;$rtstatus = "Disabled"}
"262160" {$defstatus = "Out of date" ;$rtstatus = "Disabled"}
"266240" {$defstatus = "Up to date" ;$rtstatus = "Enabled"}
"266256" {$defstatus = "Out of date" ;$rtstatus = "Enabled"}
"393216" {$defstatus = "Up to date" ;$rtstatus = "Disabled"}
"393232" {$defstatus = "Out of date" ;$rtstatus = "Disabled"}
"393488" {$defstatus = "Out of date" ;$rtstatus = "Disabled"}
"397312" {$defstatus = "Up to date" ;$rtstatus = "Enabled"}
"397328" {$defstatus = "Out of date" ;$rtstatus = "Enabled"}
"397584" {$defstatus = "Out of date" ;$rtstatus = "Enabled"}
default {$defstatus = "Unknown" ;$rtstatus = "Unknown"}
}
#Create hash-table for each computer
$ht = #{}
$ht.Computername = $computername
$ht.Name = $AntiVirusProduct.displayName
$ht.'Product GUID' = $AntiVirusProduct.instanceGuid
$ht.'Product Executable' = $AntiVirusProduct.pathToSignedProductExe
$ht.'Reporting Exe' = $AntiVirusProduct.pathToSignedReportingExe
$ht.'Definition Status' = $defstatus
$ht.'Real-time Protection Status' = $rtstatus
#Create a new object for each computer
$ret += New-Object -TypeName PSObject -Property $ht
}
Return $ret
}
Get-AntiVirusProduct
Output:
Product GUID : {B0D0C4F4-7F0B-0434-B825-1213C45DAE01}
Name : CylancePROTECT
Real-time Protection Status : Enabled
Computername : HOSTNAME
Product Executable : C:\Program Files\Cylance\Desktop\CylanceSvc.exe
Reporting Exe : C:\Program Files\Cylance\Desktop\CylanceSvc.exe
Definition Status : Up to date
Product GUID : {D68DDC3A-831F-4fae-9E44-DA132C1ACF46}
Name : Windows Defender
Real-time Protection Status : Unknown
Computername : HOSTNAME
Product Executable : windowsdefender://
Reporting Exe : %ProgramFiles%\Windows Defender\MsMpeng.exe
Definition Status : Unknown
Instead of relying on running processes, you could query the registry :
$computerList = "localhost", "localhost"
$filter = "antivirus"
$results = #()
foreach($computerName in $computerList) {
$hive = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey([Microsoft.Win32.RegistryHive]::LocalMachine, $computerName)
$regPathList = "SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall",
"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall"
foreach($regPath in $regPathList) {
if($key = $hive.OpenSubKey($regPath)) {
if($subkeyNames = $key.GetSubKeyNames()) {
foreach($subkeyName in $subkeyNames) {
$productKey = $key.OpenSubKey($subkeyName)
$productName = $productKey.GetValue("DisplayName")
$productVersion = $productKey.GetValue("DisplayVersion")
$productComments = $productKey.GetValue("Comments")
if(($productName -match $filter) -or ($productComments -match $filter)) {
$resultObj = [PSCustomObject]#{
Host = $computerName
Product = $productName
Version = $productVersion
Comments = $productComments
}
$results += $resultObj
}
}
}
}
$key.Close()
}
}
$results | ft -au
Example output :
Host Product Version Comments
---- ------- ------- --------
localhost Avast Free Antivirus 10.4.2233
localhost Avast Free Antivirus 10.4.2233
Would this work for you? It's written in PowerShell v2, so if you have that installed on your 2003 servers, it will run on all the servers. This code will give you a CSV of this data from whichever machines run the script that have a service with the description including the word "virus" (which I thought better than "antivirus" because some services use "anti-virus" instead). If they all have access to a shared resource, you can prepend that shared resource directory to the $Filename variable and it will name each report starting with that computer's name and dump your reports there.
invoke-command -computername Server01, Server02 -filepath c:\Scripts\get_av_info.ps1
Assuming the script is saved as c:\Scripts\get_av_info.ps1, that should run it on whatever machines you specify, or if you have a CSV of all the machines you want to run the script, ForEach it. I didn't try this, so I can't verify the remote invoking.
$Date = (Get-Date).ToString('yyyy-MM-dd')
$localhost = $env:computername
$Filename = "C:\" + $localhost + "_" + $Date + "_AV_FileInfo.csv"
$AV = get-process | ?{$_.Description -like "*virus*"}
$Process = ForEach($a in $AV){
$ID = $($a.Id)
get-process -Id $ID -FileVersionInfo
}
$Process | select "CompanyName","FileBuildPart","FileDescription","FileName","FileVersion","ProductName","ProductPrivatePart","ProductVersion","SpecialBuild" | Export-Csv $Filename -NoTypeInformation
There are a LOT of options, I just picked ones I thought you'd want. You could probably also combine the reports to one by adding a shared resource to the Filename and having it -Append, but you would run the risk of multiple servers trying to write to the file at the same time and failing to report at all.
You'll need to refine your results, of course. If you don't change anything, any machine where you run this will just drop a CSV called "COMPUTERNAME_DATE_AV_FileInfo.csv" at the root of it's C:\ drive.

Issues automating printer driver update (printer settings) and printer preferences in Win7, using a PS,cmd,vbs,etc script?

WMI can do it, but I have an issue, PCs are on, but logged off. If I try to run:
wmic /node:%strIP% printer where DeviceID="lp1" set DriverName="Lexmark Universal v2"
It fails with a message about a "generic failure". I RDP in and then run the same command from my end, and it works. Powershell version I am using is older, so it does not have some of the printer cmdlets, and updating PS is currently out of the question. Is there a way to remotely log someone in, without actually having to RDP in? Via PS, cmd, PSEXEC, etc?
The other avenue I've taken is using regedit, but I'm hitting some hicups with that, namely that I cannot figure out what to copy. In regedit, I can change the drivername and the setting that enable duplex and tray2 (in printer settings), but I cannot figure how to change the settings in printer preferences for printing double sided and doing so along the long edge.
What I did to figure out what to change, I did a find on the printer name in regedit as a data value and exported the keys before changing the settings. Then I exported it again AFTER changing the settings. I then used fc /c /a /u before.reg after.reg to get the changes. I chopped up the .reg to include only the changed values. Running the .reg seems to change everything, but the print both sides, along the long edge settings. It is a lexmark printer, so I am wondering if maybe preferences for it are stored elsewhere.
This is my most up to date PS1 script. I've commented out some lines as I tried different ways of doing things:
$Cred = Get-Credential
$Str = Read-Host "Please select a site ID [###] "
$PC = Read-Host "Please select a PC number [##] "
Clear-Host
$PCNm = "$Str-CCPC-$PC"
function Test-PsRemoting
{
try
{
$errorActionPreference = "Stop"
$result = Invoke-Command -ComputerName $PCNm { 1 }
}
catch
{
Write-Verbose $_
return $false
}
if($result -ne 1)
{
Write-Verbose "Remoting to $PCNm returned an unexpected result."
return $false
}
$true
}
If(!(Test-PsRemoting)){
PSEXEC \\$PCNm powershell Enable-PSRemoting -force 2>&1 >nul
Clear-Host
Write-Host "Enabled PsRemoting"
}else{Write-Host "PsRemoting already enabled"}
Invoke-Command -ComputerName $PCNm -Credential $Cred -ScriptBlock {
#$lp1 = Get-WMIObject -Query "SELECT * from Win32_Printer Where DeviceID='lp1'"
$lp1 = Get-WmiObject Win32_Printer | ?{$_.name -eq "lp1"}
$lp1.Scope.Options.EnablePrivileges = $true
$lp1.DriverName = "Lexmark Universal v2"
$lp1R = $lp1.Put()
#$lp2 = Get-WMIObject -Query "SELECT * from Win32_Printer Where DeviceID='lp2'"
$lp2 = Get-WmiObject Win32_Printer | ?{$_.name -eq "lp2"}
$lp2.Scope.Options.EnablePrivileges = $true
$lp2.DriverName = "Lexmark Universal v2"
$lp2R = $lp2.Put()
}
#$lp1 = Get-WMIObject -Impersonation Delegate -Authentication Call -Credential $Cred -ComputerName $PCNm -Query "SELECT * from Win32_Printer Where DeviceID='lp1'"
#$lp1.DriverName = "Lexmark Universal v2"
#$lp1.Put()
No matter which way I try it, invoke-command, or get-wmiobject, I get:
Exception calling "Put" with "0" argument(s): "Generic failure "
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : DotNetMethodException
+ PSComputerName : 150-CCPC-02
This doesn't particularly answer your actual question but as a solution for how I do this very same thing I thought I would give you what I threw together to update printer properties. I have not cleaned this up at all as I was porting it from my create printer function.
Function Set-SSPrinter {
Param(
[Parameter(Mandatory=$true,
ValueFromPipeline=$True,
ValueFromPipelineByPropertyName=$True)]
[ValidateNotNullOrEmpty()]
[string]$ComputerName,
[Parameter(Mandatory=$true)]
[ValidateNotNullOrEmpty()]
[string]$Name,
[string]$PortName,
[string]$DriverName,
[string]$Comment,
[string]$Location,
[bool]$Shared,
[string]$ShareName = $Name,
[string]$PermissionSDDL,
[string]$PrintProcessor,
[string]$DataType,
[bool]$RawOnly
)
try {
$modprinter = Get-WmiObject Win32_Printer -ComputerName $ComputerName | ?{$_.name -eq $Name}
$modprinter.Scope.Options.EnablePrivileges = $true
if($DriverName) {
$modprinter.DriverName = $DriverName
}
if($PortName) {
$modprinter.PortName = $PortName
}
if($Shared) {
$modprinter.Shared = $Shared
}
if($ShareName) {
$modprinter.ShareName = $ShareName
}
if($Location) {
$modprinter.Location = $Location
}
if($Comment) {
$modprinter.Comment = $Comment
}
if($Name) {
$modprinter.DeviceID = $Name
}
if($PrintProcessor) {
$modprinter.PrintProcessor = $PrintProcessor
}
if($DataType) {
$modprinter.PrintJobDataType = $DataType
}
if($RawOnly) {
$modprinter.RawOnly = $RawOnly
}
$result = $modprinter.Put()
if($PermissionSDDL) {
$modprinter.SetSecurityDescriptor($objHelper.SDDLToWin32SD($PermissionSDDL).Descriptor) | Out-Null
}
$("Update Complete: " + $Name)
} catch {
$("Update Failed: " + $Name)
Write-Warning $_.Exception.Message
$error.Clear()
}
}
Unfortunately I use the printer name to figure out which device to modify on the remote machine. Your executing credentials from the powershell session you have open must have admin rights on the remote machine. if necessary do a runas different user on powershell.exe
Example usage:
Set-SSPrinter -ComputerName "10.210.20.100" -Name "TestPrinter" -DriverName "Lexmark Universal v2"
wmic /node:servername /user:username /password:password path win32_something call methodname
Is how to do it.
Things with users are best done with logon scripts because that is how windows is designed.

How to update existing IIS 6 Web Site using PowerShell

I am trying to create a PowerShell script that creates a new IIS 6 web site and sets things like App Pool, Wildcard application maps, ASP.NET version, etc.
After extensive search on the Internet I found a script that allows me to create a new Web Site but not to modify all the properties I need.
$newWebsiteName = "WebSiteName"
$newWebsiteIpAddress = "192.168.1.100"
$newWebSiteDirPath = "c:\inetpub\wwwroot\WebSiteName"
$iisWebService = Get-WmiObject -namespace "root\MicrosoftIISv2"
-class "IIsWebService"
$bindingClass = [wmiclass]'root\MicrosoftIISv2:ServerBinding'
$bindings = $bindingClass.CreateInstance()
$bindings.IP = $newWebsiteIpAddress
$bindings.Port = "80"
$bindings.Hostname = ""
$result = $iisWebService.CreateNewSite
($newWebsiteName, $bindings, $newWebSiteDirPath)
Any help on how to expand example above is greatly appreciated.
First of all, big thanks to jrista for pointing me in the right direction.
I also found this article very useful.
What follows here is a powershell script to create Application pool, Website and a SelfSsl certificate:
function CreateAppPool ([string]$name, [string]$user, [string]$password)
{
# check if pool exists and delete it - for testing purposes
$tempPool = gwmi -namespace "root\MicrosoftIISv2" -class "IISApplicationPoolSetting" -filter "Name like '%$name%'"
if (!($tempPool -eq $NULL)) {$tempPool.delete()}
# create Application Pool
$appPoolSettings = [wmiclass] "root\MicrosoftIISv2:IISApplicationPoolSetting"
$newPool = $appPoolSettings.CreateInstance()
$newPool.Name = "W3SVC/AppPools/" + $name
$newPool.WAMUsername = $user
$newPool.WAMUserPass = $password
$newPool.PeriodicRestartTime = 1740
$newPool.IdleTimeout = 20
$newPool.MaxProcesses = 1
$newPool.AppPoolIdentityType = 3
$newPool.Put()
}
function CreateWebSite ([string]$name, [string]$ipAddress, [string]$localPath, [string] $appPoolName, [string] $applicationName)
{
# check if web site exists and delete it - for testing purposes
$tempWebsite = gwmi -namespace "root\MicrosoftIISv2" -class "IISWebServerSetting" -filter "ServerComment like '%$name%'"
if (!($tempWebsite -eq $NULL)) {$tempWebsite.delete()}
# Switch the Website to .NET 2.0
C:\windows\Microsoft.NET\Framework\v2.0.50727\aspnet_regiis.exe -sn W3SVC/
$iisWebService = gwmi -namespace "root\MicrosoftIISv2" -class "IIsWebService"
$bindingClass = [wmiclass]'root\MicrosoftIISv2:ServerBinding'
$bindings = $bindingClass.CreateInstance()
$bindings.IP = $ipAddress
$bindings.Port = "80"
$bindings.Hostname = ""
$iisWebService.CreateNewSite($name, $bindings, $localPath)
# Assign App Pool
$webServerSettings = gwmi -namespace "root\MicrosoftIISv2" -class "IISWebServerSetting" -filter "ServerComment like '%$name%'"
$webServerSettings.AppPoolId = $appPoolName
$webServerSettings.put()
# Add wildcard map
$wildcardMap = "*, c:\somewildcardfile.dll, 0, All"
$iis = [ADSI]"IIS://localhost/W3SVC"
$webServer = $iis.psbase.children | where { $_.keyType -eq "IIsWebServer" -AND $_.ServerComment -eq $name }
$webVirtualDir = $webServer.children | where { $_.keyType -eq "IIsWebVirtualDir" }
$webVirtualDir.ScriptMaps.Add($wildcardMap)
# Set Application name
$webVirtualDir.AppFriendlyName = $applicationName
# Save changes
$webVirtualDir.CommitChanges()
# Start the newly create web site
if (!($webServer -eq $NULL)) {$webServer.start()}
}
function AddSslCertificate ([string] $websiteName, [string] $certificateCommonName)
{
# This method requires for you to have selfssl on your machine
$selfSslPath = "\program files\iis resources\selfssl"
$certificateCommonName = "/N:cn=" + $certificateCommonName
$certificateValidityDays = "/V:3650"
$websitePort = "/P:443"
$addToTrusted = "/T"
$quietMode = "/Q"
$webServerSetting = gwmi -namespace "root\MicrosoftIISv2" -class "IISWebServerSetting" -filter "ServerComment like '$websiteName'"
$websiteId ="/S:" + $webServerSetting.name.substring($webServerSetting.name.lastindexof('/')+1)
cd -path $selfSslPath
.\selfssl.exe $addToTrusted $certificateCommonName $certificateValidityDays $websitePort $websiteId $quietMode
}
$myNewWebsiteName = "TestWebsite"
$myNewWebsiteIp = "192.168.0.1"
$myNewWebsiteLocalPath = "c:\inetpub\wwwroot\"+$myNewWebsiteName
$appPoolName = $myNewWebsiteName + "AppPool"
$myNewWebsiteApplicationName = "/"
$myNewWebsiteCertificateCommonName = "mynewwebsite.dev"
CreateAppPool $appPoolName "Administrator" "password"
CreateWebSite $myNewWebsiteName $myNewWebsiteIp $myNewWebsiteLocalPath $appPoolName $myNewWebsiteApplicationName
AddSslCertificate $myNewWebsiteName $myNewWebsiteCertificateCommonName
The $result object contains the path to the newly created IIsWebServer object. You can get access to the virtual directory, where you can configure more properties, by doing the following:
$w3svcID = $result.ReturnValue -replace "IIsWebServer=", ""
$w3svcID = $w3svcID -replace "'", ""
$vdirName = $w3svcID + "/ROOT";
$vdir = gwmi -namespace "root\MicrosoftIISv2"
-class "IISWebVirtualDir"
-filter "Name = '$vdirName'";
# do stuff with $vdir
$vdir.Put();
This is a useful PowerShell snippet.
I tried running this and I get problems with the delete tests. Delete does not work against the app pool when the site still exists. Surely you should run website delete test first.
# check if web site exists and delete it - for testing purposes
$tempWebsite = gwmi -namespace "root\MicrosoftIISv2"
-class "IISWebServerSetting"
-filter "ServerComment like '%$name%'"
if (!($tempWebsite -eq $NULL)) {$tempWebsite.delete()}
Run this first, then run the app pool deletion test.
I realise you have marked these as tests but surely it is useful to exit or delete if webs site exists.