Creating IIS7 web application using PowerShell with Require SSL set to "Require" - ssl

I'm creating an IIS web site using PowerShell's New-WebSite cmdlet, and within that a web application using New-WebApplication.
The SSL settings for the web application need to be set to Require SSL; Require as shown below.
For consistency, I would like to do this using only PowerShell cmdlets.
The Require SSL setting is easy; you just add the -Ssl parameter to New-Website.
However, the only way we've found to set the Require option is using Appcmd.exe:
& $env:SystemRoot\System32\inetsrv\Appcmd.exe `
set config "$WebSiteName/$VirtualDirName" `
/section:access `
/sslFlags:"SslRequireCert" `
/commit:APPHOST
Is there a PowerShell alternative to this?

I had to add ssl to the value:
Set-WebConfiguration -Location "$WebSiteName/$WebApplicationName"
-Filter 'system.webserver/security/access'
-Value "Ssl, SslRequireCert"

Solution found, using Set-WebConfiguration:
Set-WebConfiguration -Location "$WebSiteName/$WebApplicationName" `
-Filter 'system.webserver/security/access' `
-Value "SslRequireCert"

I used this method:
Set-WebConfigurationProperty -PSPath "machine/webroot/apphost" `
-location "$mySiteName" -filter "system.webserver/security/access" `
-name "sslflags" -value "Ssl,SslNegotiateCert,SslRequireCert"

If you get the error "There is no configuration defined for object at path IIS:\SslBindings" you need to set the PsPath parameter
-PSPath IIS:\Sites

Related

Automate Powershell Script to connect to MSOnline while MFA is applied

Thanks in advance.
Quick brief, I work in a team managing multiple Microsoft CSPs (Partner Centers), every now and then somebody asks us to run a script that does specific activities or grab specific info from all 30 CSPs we manage and all customers under them.
Previously we used to keep all usernames, passwords, TenantIDs, WebApp IDs in a CSV file and we create a script that runs on every raw to get the required info for each CSP Automatically without prompting credentials using below command:
$credential = (New-Object –TypeName System.Management.Automation.PSCredential –argumentlist $AdminName ,(ConvertTo-SecureString $AdminPassword –AsPlainText –Force))
And then call it in all modules like the below:
#MSonline
Connect-Msolservice –Credential $Credential
#ExchangeOnline
$session = New-PSSession –ConfigurationName Microsoft.Exchange –ConnectionUri https://outlook.office365.com/powershell-liveid?DelegatedOrg=$Customerdomain –Credential $credential –Authentication Basic –AllowRedirection
Import-PSSession $Session
#Partner Center
Add-PCAuthentication -cspappID $NAtive_clientid -cspDomain $domain -credential $credentials
Connect-MsolService -Credential $credentials
Then MFA was applied on all CSPs, though secure, it presented a problem with automating our scripts. Every time we're asked to run a script we would have to login manually at least 1 time to enter our MFA credentials to be able to run the script on each CSP individually.
The Modules we usually connect to are:
PartnerCenter
MSOnline
CsOnline
AzureRM
AzureAD
Microsoft provided steps to work around this by using secure API Modules: https://learn.microsoft.com/en-us/powershell/partnercenter/secure-app-model?view=partnercenterps-1.5
I've created New APPs with new secrets and call backs , managed to get refresh token and integrated it in PartnerCenter module successfully as follows:
Connect-PartnerCenter -ApplicationId $NAtive_clientid -RefreshToken $refresh_token
Now I'm tying to do the same for the other Modules I'm addressing, as per the above document I could do the same for MS Online and for Azure AD simply by getting 3 other tokens (Graph Token , Azure AD token and Azure token)
$credential = Get-Credential
$refreshToken = 'Your-Refresh-Token-Value'
$azureToken = New-PartnerAccessToken -RefreshToken $refreshToken -Resource https://management.azure.com/ -Credential $credential -TenantId '<Your Tenant Id>'
$graphToken = New-PartnerAccessToken -RefreshToken $refreshToken -Resource https://graph.microsoft.com -Credential $credential -TenantId '<Your Tenant Id>'
$aadGraphToken = New-PartnerAccessToken -RefreshToken $refreshToken -Resource https://graph.windows.net -Credential $credential -TenantId '<Your Tenant Id>'
#MS Module
Connect-MsolService -AdGraphAccessToken $aadGraphToken.AccessToken -MsGraphAccessToken $graphToken.AccessToken
# Az Module
Connect-AzAccount -AccessToken $azureToken.AccessToken -GraphAccessToken $graphToken.AccessToken -TenantId '<TenantId>'
# AzureRM Module
Connect-AzureRmAccount -AccessToken $azureToken.AccessToken -GraphAccessToken $graphToken.AccessToken -TenantId '<TenantId>'
When Applying this and running the below command I get an error:
New-PartnerAccessToken -RefreshToken $refreshToken -Resource https://management.azure.com/ -Credential $credential -TenantId '<Your Tenant Id>'
New-PartnerAccessToken : Cannot validate argument on parameter 'RefreshToken'. The argument is null or empty. Provide an argument
that is not null or empty, and then try the command again.
At line:1 char:38
+ New-PartnerAccessToken -RefreshToken $refreshToken -Resource https:// ...
+ ~~~~~~~~~~~~~
+ CategoryInfo : InvalidData: (:) [New-PartnerAccessToken], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.Store.PartnerCenter.PowerShell.Commands.NewPartnerAccessT
oken
After some investigation I found that the parameter "-resource" no longer exists as per the documentation: https://learn.microsoft.com/en-us/powershell/module/partnercenter/new-partneraccesstoken?view=partnercenterps-3.0
Yet as per the documentation related to MSOnline, it shows I should be able to use it : https://learn.microsoft.com/en-us/powershell/module/msonline/connect-msolservice?view=azureadps-1.0
Now I'm stuck without the resource parameter I can't get the tokens required to use the 3 modules.
My question, is there another way to use App ID, refresh token, secret, Tenant ID to authenticate using powershell without human interference , if not how can I make the above method work for other modules the same way I did with the partner center.
According to my research. if the version of your PartnerCenter module is larger than 2.0.1909.1, it has rplaced the Resource parameter with the Scopes parameter for the Connect-PartnerCenter and New-PartnerAccessToken cmdlets. So please use the following script to get access token
New-PartnerAccessToken -ApplicationId 'xxxx-xxxx-xxxx-xxxx' -Credential $credential -RefreshToken $refreshToken -Scopes 'https://graph.windows.net/.default' -ServicePrincipal -Tenant 'xxxx-xxxx-xxxx-xxxx'

PHP: How to fix curl_exec() error 60: unable to get local issuer certificate?

(This question was originally titled, "Why is curl_exec() failing in this script?" But by adding calls to curl_errno() and curl_error() in the script, I found out that the problem was the certificate, and I've edited the question accordingly.)
The following script:
<?php
$sDataFile = '<path>\journal-issue-ToC.htm';
$sURL = 'https://onlinelibrary.wiley.com/toc/14678624/2014/85/1';
$bHeader = false;
$cURLhandle = curl_init();
$FilePointer = fopen($sDataFile, 'wb');
curl_setopt($cURLhandle, CURLOPT_URL, $sURL);
curl_setopt($cURLhandle, CURLOPT_FILE, $FilePointer);
curl_setopt($cURLhandle, CURLOPT_HEADER, $bHeader);
$bResult = curl_exec($cURLhandle);
echo('<br>' . ($bResult === false ? 'Failed to execute' : 'Executed') . ' cURL.');
if(! $bResult) echo('<br>Error #' . curl_errno($cURLhandle) . ': ' . curl_error($cURLhandle));
curl_close($cURLhandle);
fclose($FilePointer);
saves the empty file "journal-issue-ToC.htm" and generates the following browser output:
Failed to execute cURL.
Error #60: SSL certificate problem: unable to get local issuer certificate
So it appears that cURL encounters a certificate problem that doesn't happen when I access the requested URL in the browser. What do I need to know about certificates in order to get this script to work?
I'm running PHP 7.2.2 on IIS 7.5 under Windows 7 64 bit.
What I needed to know about certificates in order to get cURL to work is in an article on GitHub, which explains the need for certificates in cURL and how to get and apply them:
What we're talking about are SSL certificates, needed for the https protocol. "CA" stands for "certificate authorities".
Download the certificates from https://curl.haxx.se/ca/cacert.pem (documentation).
In the file "php.ini", in the section on cURL, uncomment the command for the CURLOPT_CAINFO option and specify the location of the downloaded file "cacert.pem”. After saving the ini file, restart the webserver to effect the change.
I did this with a couple of variations:
I chose to set the value of CURLOPT_CAINFO in the function curl_setopt() instead of in the file "php.ini".
I at first got error 77, "error setting certificate verify locations". This was fixed by moving the file "cacert.pem" to a folder under the folder "Program Files\PHP".
After doing that, the script ran without error and the output file was not empty. But what it contained was still not what I need, which is the subject of a new question.

Network error on powershell SQL job step

This is partially my code and partially from others help here on stack overflow.
$excelFile = "C:\ExcelTest\Test.csv"
$functionDirectory = "C:\foldername"
$csv = Import-csv $excelFile -Header FileName
Import-Module sqlps
foreach ($line in $csv)
{
if(test-path -path ($functionDirectory + "\" + $line.FileName))
{
invoke-sqlcmd -inputfile "C:\foldername\filename.sql" -serverinstance "servername\instancename" -database "databasename"
}
}
I had to remove the specific serverinstance / servername for privacy but I've checked both of those several times and I don't think that is where the issue is. I keep getting the error
A network related or instance specific error occurred while
establishing a connection to SQL Server. The server was not found or
was not accessible. Verify that the instance name is correct and that
SQL Server is configured to allow remote connections.
I have double checked server / instance name which I got from the server by running
select ##servername + '\' + ##SERVICENAME
nd the database name obviously was easy to get. I have double checked that the server is set up for remote connection (even though this is a database that is local on my laptop and not a remote server currently).
I'm kinda at a loss for what else to check for.
I had read you should look at firewall settings but I don't think those should make a difference when its a local server on my machine.
I'm still somewhat new with SQL and powershell so I apologize for any blatant syntax or formatting errors (please point out so I can correct them). Any help would be appreciated.
Turns out I needed to remove the instance name and just use the server name.

Call WCF Service from bat file

is it possible to call a Methode of a WCF Service in a bat file. We want to test if the WCF Service works correct after the Server was restartet.
There are no commands within the BAT file universe that will allow you to contact a WCF service directly, however you could use a BAT file to run an existing console program that can connect and interact with a WCF service. So the answer is both yes and no; not directly, but through a separate program yes.
If you need some simple, clickable way of accessing a WCF service, I'd go with a Powershell or VB script (assuming you're in a windows environment).
Maybe you will be able to use PowerShell? It would be easier then. Create script with content:
$url = 'http://yoursite.url/example.svc'
$action = "`"http://some.namespace/method`""
$SOAPRequest = [xml]#'heregoesxmlmessage'#
write-host "Sending SOAP Request To Server: $url"
$soapWebRequest = [System.Net.WebRequest]::Create($url)
$soapWebRequest.Headers.Add("SOAPAction", $action)
$soapWebRequest.ContentType = "text/xml;charset=`"utf-8`""
$soapWebRequest.Accept = "text/xml"
$soapWebRequest.Method = "POST"
write-host "Initiating Send."
$requestStream = $soapWebRequest.GetRequestStream()
$SOAPRequest.Save($requestStream)
$requestStream.Close()
write-host "Send Complete, Waiting For Response."
$resp = $soapWebRequest.GetResponse()
$responseStream = $resp.GetResponseStream()
$soapReader = [System.IO.StreamReader]($responseStream)
$ReturnXml = [Xml] $soapReader.ReadToEnd()
$responseStream.Close()
write-host "Response Received."
$ReturnXml.OuterXml | out-file ".\test.xml"
write-host $ReturnXml.OuterXml
As mentioned in the other answers Powershell is probably the best way to go using the New-WebServiceProxy cmdlet.
http://technet.microsoft.com/library/hh849841.aspx
Example from the link above:
PS C:\> $URI = "http://www.webservicex.net/uszip.asmx?WSDL"
PS C:\>$zip = New-WebServiceProxy -Uri $URI -Namespace WebServiceProxy -Class USZip
PS C:\> $zip.getinfobyzip(20500).table
CITY : Washington
STATE : DC
ZIP : 20500
AREA_CODE : 202
TIME_ZONE : E

Access SQL - WMI Namespaces from Remote Machine

i am playing with Powershell and SQL WMI events and i am wondering if i can do this stuff remotely from the admin notebook:
I'd like to query the "root\Microsoft\SqlServer\ServerEvents\MSSQLSERVER" namespace:
On SQLServer directly:
get-wmiobject -list -namespace "root\Microsoft\SqlServer" >> Works!
get-wmiobject -list -namespace "root\Microsoft\SqlServer\ServerEvents\MSSQLSERVER" >> Works !
On my Adminmachine:
get-wmiobject -list -namespace "root\Microsoft\SqlServer" >> Works!
get-wmiobject -list -namespace "root\Microsoft\SqlServer\ServerEvents\MSSQLSERVER" >> Error: Invalid Namespace.
Is there a trick to get this running? Do i have to additional install sth?
I am still on SQL 2005.
Thanks!
Use the computername name parameter.
get-wmiobject -computername Z002 -list -namespace "root\Microsoft\SqlServer\ServerEvents\MSSQLSERVER"
Also keep in mind MSSQLSERVER is only available if the server has a default instance. If the server uses a named instance you'll need to specify the instance name instead of MSSQLSERVER.
Posted - 05/05/2012 : 08:25:20
Hi All,
We've developed a free WMI CLR assembly to execute WMI queries in SQL.
e.g. This will return mount point and drive space
DECLARE #XmlData Xml
--Obtain Windows Services
select #XmlData=dbo.GetWMI('\\SQL2008WIN2008\root\cimv2', --Machine and WMI class
NULL, --UserName, leave NULL to use current
NULL, --Password, leave NULL to use current
'select * from win32_volume' --WMI Class
)
SELECT
tbl.A.value('(DeviceID)[1]','VARCHAR(100)') as DeviceID,
tbl.A.value('(Name)[1]','VARCHAR(200)') as Name,
tbl.A.value('(DriveType)[1]','int') as DriveType,
ISNULL(tbl.A.value('(DriveLetter)[1]','VARCHAR(10)'),'MountPoint') as DriveLetter,
tbl.A.value('(FreeSpace)[1]','bigint')/1024/1024 as FreeSpaceMbytes
FROM #XmlData.nodes('/WMI/Data') tbl(A)
Have a look at http://micatio.com/sqlwmi.aspx