Quantcast
Channel: PowerShell
Viewing all 136 articles
Browse latest View live

How to Script SSL certificates for WMSVC and IIS 10.0

$
0
0

Hello All -

I just spent a very long time studying the various documentation for scripting SSL certs for WMSVC (Web Deploy). There were some gotcha's in Windows 10 that required some details. I thought I'd contribute my code here so that others working with certs and IIS 10 will lose less hair than I did. :)

The reason I have this script is to update the SSL cert used when building out VM's from a template.  Obviously once the host is newly named, you will have to create a new Self signed cert for it so you can deploy using MS Deploy.  

First, I have a simple command file wrapper around the powershell which sets up the fully qualified hostname and makes it easier to call from the RunOnce registry. You will probably need to munge this to fit your own environment. 

set FQHN=%COMPUTERNAME%.<yourdomain>
cd C:\WMSVCCONFIG
powershell -ExecutionPolicy bypass -NonInteractive -NoProfile -command .\createNew.ps1 > createNew_log.txt 2>&1

And now the powershell:

$FQHN = "$env:FQHN";

Import-Module WebAdministration
"Attempting to stop WMSVC..."
net stop WMSVC"Removing unassigned addresses SSl bindings... (ignore errors)"
Remove-Item -Path IIS:\SslBindings\0.0.0.0!8172"Creating new cert..."$webServerCert = New-SelfSignedCertificate -Type Custom -DnsName $FQHN  -Subject "CN=$FQHN" -KeySpec "Signature" -KeyUsage @("KeyEncipherment","DataEncipherment") -TextExtension @("2.5.29.37={text}1.3.6.1.5.5.7.3.1") -TestRoot -FriendlyName "$FQHN Self-Signed For MSDEPLOY Agent"  -NotAfter $([datetime]::now.AddYears(5)) -CertStoreLocation Cert:\LocalMachine\My$thumbprint = $webServerCert.Thumbprint"Creating new bindings with new cert with hash: " + $thumbprint;

# Note: the exact appid is required for WMSVC to actually start in IIS 10.0.
# Also note you have to supply certstorename=My explicitly because there is a defect
# in some version of Server 2016 which doesn't set the binding store name by default.
# Without it, WMSVC just won't start.

netsh http add sslcert ipport="0.0.0.0:8172" appid='{d7d72267-fcf9-4424-9eec-7e1d8dcec9a9}' certhash=$thumbprint certstorename=My"Attempting start of WMSVC..."

net start WMSVC


Creating IIS Site in powershell without SNI ( Multiple Certificates)

$
0
0

Hi All,

I am trying to create one IIS site in powershell .I want the site to be created without SNI.
I am using iis 10, ( Windows 2016 server )

Our Netscaler is not compatible with SNI and hence I have to create without SNI.

I am able to create site with SNI using sslflags=1. But When I try to create without sni, I am running into issues.

Below is my snippet

$SecurePassword = ConvertTo-SecureString "Somepassword" -AsPlainText -Force;
Import-PfxCertificate -FilePath 'C:\certs\nt111trnch01.pfx' -CertStoreLocation Cert:\LocalMachine\My -Password $SecurePassword;
Import-PfxCertificate -FilePath 'C:\certs\nt111trnch02.pfx' -CertStoreLocation Cert:\LocalMachine\My -Password $SecurePassword;
Import-PfxCertificate -FilePath 'C:\certs\nt111trnch03.pfx' -CertStoreLocation Cert:\LocalMachine\My -Password $SecurePassword;
Import-Module "WebAdministration";
New-Item IIS:\Sites\myProj -bindings @{protocol='https';bindingInformation='*:8080:nt111trnch01.sit.abcit';SslFlags=1} -PhysicalPath C:\site;
New-WebBinding -Name "myProj" -Protocol https -HostHeader nt111trnch02.sit.abcit -Port 8080 -SslFlags 1; \
New-WebBinding -Name "myProj" -Protocol https -HostHeader nt111trnch03.sit.abcit -Port 8080 -SslFlags 1; \
New-Item -Path "IIS:\SslBindings\*!8080!nt111trnch01.sit.abcit" -Thumbprint 145300EC69B3448EE15A54DBCD54647AF8294611 -SslFlags 1;
New-Item -Path "IIS:\SslBindings\*!8080!nt111trnch02.sit.abcit" -Thumbprint 86C1CD3660F9810DB30CB2E312E197C898I26253 -SslFlags 1;
New-Item -Path "IIS:\SslBindings\*!8080!nt111trnch03.sit.abcit" -Thumbprint 0C7888C0615615997DB6F9DA9E9A03E4671E3BAD -SslFlags 1;
New-Item C:\site\myProj -type directory

Note: I am able to create site with single certificate and without SNI. But binding multiple certificates causing the issues.

When I changed all SslFlags vlaue to 0, I am getting this error.

New-Item : Cannot create a file when that file already exists
At line:12 char:2
+     New-Item -Path "IIS:\SslBindings\*!8080!nt111trnch02.sit.abci...
+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [New-Item], Win32Exception
    + FullyQualifiedErrorId : System.ComponentModel.Win32Exception,Microsoft.PowerShell.Commands.NewItemCommand

WARNING: Binding host name 'nt111trnch03.sit.abcit' is not equals to certificate subject name 'CN=nt111trnch03.sit.swcsit, OU=IT Services, O=Mycity 
Company, L=Mycity, S=State, C=Country'. Client may not be able to connect to the site using HTTPS protocol.
New-Item : Cannot create a file when that file already exists
At line:13 char:2
+     New-Item -Path "IIS:\SslBindings\*!8080!nt111trnch03.sit.abci ...
+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [New-Item], Win32Exception
    + FullyQualifiedErrorId : System.ComponentModel.Win32Exception,Microsoft.PowerShell.Commands.NewItemCommand

Site with multiple certificates

Thanks in advance

VVP

Powershell script to modify authentication referring to a file

$
0
0

Hi,

How can I disable anonymous authentication and enable window auth for a file in a Powershell script. I tried to use the -PSPath and -Location properties, but I didn't found out how can I set web.config location.

examples:

Set-WebConfigurationProperty -Filter "/system.webServer/security/authentication/anonymousAuthentication" -Name Enabled -Value False -PSPath "IIS:\Sites\Default Web Site\Test\test.txt" -Location "e:\Test"

OR

Set-WebConfigurationProperty -Filter "/system.webServer/security/authentication/anonymousAuthentication" -Name Enabled -Value False -PSPath "IIS:\Sites\Default Web Site\Test\" -Location "e:\Test\test.txt"

in either case same error:

Set-WebConfigurationProperty : Filename: \\?\E:\Test\test.txt\web.config 

Error: Cannot write configuration file

Thank you for your help!

how to host Powershell scripts in IIS

$
0
0

Hi,

can i anyone tell me how to host the powershell script in IIS

Upload files to http server using powershell

$
0
0

I want to transfer a XML file to http server (http://abcdef.com/somefolder/abcdef.xml) . I wrote scripts for this and it's running but actually it's not uplaoding the files to http server .

My code $sourceFilePath = "C:\Temp\NEWFOLDER\ABCDEF.XML" $siteAddress = "http://abcdef.net/inetpub/temp/XML/" $urlDest = "{0}/{1}" -f ($siteAddress, "ABCDEF.XML"); $UserName = "XXXXX" $Password = "XXXXX" function uploadFile() { Param ([string] $sourceFilePath, [string] $siteAddress , [string] $urlDest, [string] $UserName, [string] $Password) $webClient = New-Object System.Net.WebClient; $webClient.Credentials = New-Object System.Net.NetworkCredential($UserName,$Password); ("*** Uploading {0} file to {1} ***" -f ($sourceFilePath, $siteAddress) ) | write-host -ForegroundColor Green $webClient.UploadFile($urlDest, "PUT", $sourceFilePath); } uploadFile $sourceFilePath $siteAddress $urlDest $UserName $Password

Error

Exception calling "UploadFile" with "3" argument(s): "The remote server returned an error: (503) Server Unavailable."At 
C:\ABCDEF-documents\upload-file.ps1:40 char:13
+             $webClient.UploadFile($urlDest, "PUT", $sourceFilePath);
+             ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : WebException

Can anyone help me on this . Any clue will be helpful.

Powershell API- Upload PDF to Endpoint from Local Machine

$
0
0

I'm having an issue trying to get this to work. What I'm trying to do is upload a "PDF" to our system using API commands in Powershell. I've been able to upload "documents" from my disk drive, but when I try to view them they are either "Document not found" or "Cannot open this PDF" or ""The input is not a valid Base-64 string as it contains a non-base 64 character". I've tried different methods: encoding/decoding in a variety of ways, I've tried opening it in several different programs- doesn't seem like nothing is working and I'm losing sleep.

Below is my code for just straight upload:

$fileName ="C:\files\Test1.pdf"$data =ConvertTo-Json@{

encrypted="false";
allowSaveBinaryData="True";
binaryData=$fileName;
divider="Expense Report";
isMultipageImage="true";
extension="pdf";
name="Test1.pdf";
relProjectId="31";}$addproject="https://ENDPOINT URL.com/v4/documents/597?guid=$temp&fbsite=https://MYURL.com/"Invoke-RestMethod-ContentType'application/json'-Method PUT -Body$data -Uri$addproject

Below is my code I tried using encoding/decoding:

$fileName ="C:\files\Test1.pdf"$fileContent = get-content $fileName$fileContentBytes =[System.Text.Encoding]::Unicode.GetBytes($fileContent)$fileContentEncoded =[System.Convert]::ToBase64String($fileContentBytes)$data =ConvertTo-Json@{

encrypted="false";
allowSaveBinaryData="True";
binaryData=$fileContentEncoded;
divider="Expense Report";
isMultipageImage="true";
extension="pdf";
name="Test1.pdf";
relProjectId="31";}$addproject="https://ENDPOINT URL.com/v4/documents/597?guid=$temp&fbsite=https://MYURL.com/"Invoke-RestMethod-ContentType'application/json'-Method PUT -Body$data -Uri$addproject

obtaining a ConnectionString

$
0
0

 Hello,

 

Anyone know how to obtain a particular connection string defined in the "connectionString" section of a Web.Config with the IIS PowerShell provider?

 

Thanks,

Carlos

Restore-WDApp missing a -ParameterValuesFile Powershell Parameter.

$
0
0

Hi all.

Sorry if this is not right but this is my first post!

We use Powershell Web Deploy to roll out our websites, recently we built some new web servers and we cannot deploy to these.

After investigating I have found that there is a line in our deployment that uses the "-ParameterValuesFile" param this is available on our DEV servers. From looking at the version installed this looks like version 3.0, however, if I download this version from MS I find that there "Version" column does not match under apps and features when I compare new and old servers.

There is basically no documentation on this parameter apart from in here:  https://docs.microsoft.com/en-us/iis/publish/using-web-deploy/web-deploy-powershell-cmdlets#iii-restore "To find out the Web Deploy parameters defined in any Web Deploy package you can simply open the zip file in Windows Explorer and examine the parameters.XML file present in the root of the package. Any Web Deploy parameter that does not have a default value or a value needs a value to be specified. Add all of these parameters in an XML file and pass it in as the value for ParameterValuesFile parameter. You can generate this file as given in here or manually. The format is"

I understand from the same article that there is a "Get-WDParameters -FilePath" command that could be a variable ($MyParams = Get-WDParameters -FilePath c:\Myfile.xml), this can be used on the newer "-Parameters" value.

Our ideal approach would be to install the matching WD package on the new servers, does anyone know where to get this? Otherwise, how would you approach this using the newer approaches without having to reinstall web deploy across all of our servers?

Thanks for any help!


Stop-NlbClusterNode perform stop all nodes

$
0
0

I have a issue with my script (powershell) that is monitored my nlb cluster that have only 2 nodes.

my script is checks the state of the iis (for each a node), and check the state of the node, if the iis is down, so i perform stop-NlbClusterNode on the certain node, but it perform stop all nodes..

i try few options:

Stop-NlbClusterNode-InputObject(Get-NlbClusterNode-NodeName"node1")Stop-NlbClusterNode-HostName"node1"-Drain-Timout10

but always all nodes are stopped.

any idea?

Powershell DSC configuration

$
0
0

Hi , 

I want to set the application pool "idletimeoutaction"  to "suspend" mode on application pool defaults  using powershell DSC script. since idletimeoutaction parameter is not available on xWebAppPoolDefaults so I am adding the powershell command to change the application pool in DSC script like below. Please help providing suggestion to create a better script.

Node $NodeName
    {
         xWebSiteDefaults SiteDefaults
         {
            ApplyTo ='Machine'
            LogFormat ='IIS'
            AllowSubDirConfig ='true'
         }


         xWebAppPoolDefaults PoolDefaults
         {
            ApplyTo ='Machine'
            ManagedRuntimeVersion ='v4.0'
            IdentityType ='ApplicationPoolIdentity'
         }
Set-WebConfigurationProperty /system.applicationHost/applicationPools/applicationPoolDefaults/processmodel -Name idleTimeoutAction -Value Suspend

}

New-psdrive is not working from Powershell Web Access

$
0
0

I am trying to map the network drive while executing the script from Powershell Web Access but getting the below error.

$servername is valid name and the script is working fine on poweshell ISE.  Please help

<form id="mainForm" action="./console.aspx" method="post"> <div id="console"> <div class="output" id="output" style="height: 526px; width: 860px;">
New-PSDrive -Name "r" -PSProvider FileSystem -Root "\\$servername\c$\ ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo          : InvalidOperation: (r:PSDriveInfo) [New-PSDrive], Win32Exception
+ FullyQualifiedErrorId : CouldNotMapNetworkDrive,Microsoft.PowerShell.Commands.NewPSDriveCommand
</div> </div> </form>

Setting Recycling | how to set 2xSpecific Times for application pools

$
0
0

Hi

I am trying to set up 2xSpecific Times to of application pool properties using a PS script. However, only can add 1 value at a time.

exemple

7:00AM

21:00PM

Set-ItemProperty-Path IIS:\AppPools\DefaultAppPool -Name recycling.periodicRestart.schedule -Value@{value ='07:00:00'}

Does anyone have a hint to what I am doing wrong? Thanks!

HTTPS Binding went missing after the server reboot

$
0
0

IIS was installed using PowerShell DSC script below , We have added only http binding since https required cert thumbprint and that will be dynamic on every year. 

Now , https binding is getting removed everytime server rebooted , Someone please help how to fix this issue. 

Configuration Wserver
{
Import-DscResource -ModuleName xwebadministration
Node $env:COMPUTERNAME
{
xWebsite Testwebsite
{
Ensure = "Present"
Name = "DefaultWebSite"
State = "Started"
ApplicationPool="DefaultAppPool"


BindingInfo = MSFT_xWebBindingInformation
{
Protocol = "http"
Port = "80"
}

How to add URL Rewrite using command line

$
0
0

I searched many places but nowhere is there a way to create a rewrite url using cmd.
Someone please help me.

How to create new file config using cmd

$
0
0

I want to create a rewrite url in cmd but I don't have the web.config file yet.

Someone please help me.


Manage IIS remotely powershell for non admin user

$
0
0

IIS version: 10

Hello,

I would like to give some priviledge for one user to manage IIS remotely via a script powershell using the following command : get-webapppool, start-webapppool and stop-webapppool. I have already configure this non admin user to execute the script remotely via winrm and that is work perfectly, but i cannot use some command included in webadministration module (access denied). Also, I configure delegation in IIS for this non admin user and he can manage IIS remotely via IIS admin web.

Now, I would like know how is it possible to authorize him to execute cmdlet IIS powershell.

could you please confirm me if is it possible to use this powershell module localy without any admin priviledge? Also, could you please confirm me if I can use WMI provider instead and how i can configure it?

Thanks and best regards,

G.

 

Deny by Request Rate via DSC

$
0
0

Hello

any examples of how  to enable "deny by request rate" for all sites?

thanks

IIS 10.0 Powershell script to create a IIS site on default web site, app pool, appname, set-property on Windows 2016 1803 server

$
0
0

Hi,

IIS 10.0 Powershell script to create a IIS site on default web site, app pool, app name, set-property, virtual directory and physicalpath on Windows 2016 1803 server

Thanks,

Configure the PS provider to use .NET 4.0 machine.config and root web.config

$
0
0

Greetings,

I'm having problems manipulating the configuration of .NET 4.0 applications under IIS 7.5.

It seems that despite the application being placed in an application pool configured to run under .NET 4.0, the configuration system reads machine.config and root web.config of .NET 2.0. This causes numerous errors ("section not declared") when we try to configure settings that were introduced in 4.0 (or later installed as an extension to 4.0, e.g. AppFabric).

A simple example: let's assume the application "testapp" is installed under "Default Web Site" and configured to run in a 4.0 AppPool. The following valid web.config

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
  <system.serviceModel>
    <protocolMapping>
      <add scheme="http" binding="myCustomHttpBinding" />
    </protocolMapping>
  </system.serviceModel>
</configuration>

 causes the following command to fail:

Get-WebConfiguration -filter '/system.serviceModel/protocolMapping' -pspath 'iis:\sites\Default Web Site\testapp'

 The error message is:

The configuration section 'protocolMapping' cannot be read because it is missing a section declaration

The message is correct in a way, since this section is not declared in .NET 2.0. Now in the IIS MMC console it is possible to "Change .NET Framework version" which makes it possible to edit the root web.config. Is it possible to make a similar "switch" in the Powershell provider?

I have found this blog post: http://www.ksingla.net/2009/03/new_features_in_configuration_system_and_appcmd_in_iis-75/ which specifically states that IIS 7.5 configuration system can work against .NET 4.0 machine.config and root web.config and a new switch was added to appcmd to allow that.

Does the powershell provider support such a scenario?

Safe way to update SSL bindings

$
0
0

I have to update the certificates on a number of servers and I'm looking for a way to script the process.

I found this guide but I'm not too keen on the whole delete/re-create approach to solving this problem.

My main concern is updating both IIS and non-IIS bindings. 

Get-ChildItem IIS:\SslBindings seems to list all bindings, even the service related ones.

This seems to work to update the certificate on the binding objects (for IIS bindings at least):

Get-ChildItem IIS:\SslBindings | Where-Object -Property Thumbprint -eq $oldCert | ForEach-Object -Process { Set-ItemProperty -Path $_.PSPath -Name Thumbprint -Value $newCert }

The servers have bindings for both IIS sites, and non-IIS sites (ie, services that listen on non-standard ports and have our certificate bound to them) and I need to update both types. Historically, we've updated the non-IIS bindings through netsh, with a similar delete/recreate model, and I'm really hoping to do away with that in favour of updating existing bindings instead.

I'm worried that there is a downside to this approach that I have not considered, any thoughts or advice on best practice is very welcome.

Viewing all 136 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>