Powershell Script to Edit IIS File Extensions - sql-server

Curious if someone could point me in the direction to how I could automate IIS Request Filtering File Extensions? I have used the following per Microsoft manuals, but when the extension is already set to false I get an error. Even though the manual states that changing the value from false to true will enable. Am I missing something very simple?
https://learn.microsoft.com/en-us/iis/configuration/system.webserver/security/requestfiltering/fileextensions/
Start-IISCommitDelay
$fileExtensions = Get-IISConfigSection -CommitPath 'Default Web Site' -SectionPath 'system.webServer/security/requestFiltering' | Get-IISConfigCollection -CollectionName 'fileExtensions'
New-IISConfigCollectionElement -ConfigCollection $fileExtensions -ConfigAttribute #{ 'fileExtension' = '.asax'; 'allowed' = $true } -AddAt 0
Set-IISConfigAttributeValue -ConfigElement $fileExtensions -AttributeName 'applyToWebDAV' -AttributeValue $true
Stop-IISCommitDelay
New-IISConfigCollectionElement : Filename:
Error: Cannot add duplicate collection entry of type 'add' with unique key
attribute 'fileExtension' set to '.asax'
At line:5 char:1
+ New-IISConfigCollectionElement -ConfigCollection $fileExtensions -Con ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [New-IISConfigCollectionElemen
t], COMException
+ FullyQualifiedErrorId : System.Runtime.InteropServices.COMException,Micr
osoft.IIS.Powershell.Commands.NewIISConfigCollectionElementCommand
Set-IISConfigAttributeValue : Object reference not set to an instance of an
object.
At line:7 char:1
+ Set-IISConfigAttributeValue -ConfigElement $fileExtensions -Attribute ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [Set-IISConfigAttributeValue],
NullReferenceException
+ FullyQualifiedErrorId : System.NullReferenceException,Microsoft.IIS.Powe
rshell.Commands.SetIISConfigAttributeValueCommand
WARNING: No active transaction.

Never able to figure out why this process doesn't work as it should per the man docs from Microsoft, but found the configuration files for IIS and made an edited version and wrote a Powershell to move the original and place the edited version in the needed directories. Problem solved.

Related

PowerShell & SQL Server : Attempt to retrieve data for object failed for ManagedComputer

I'm currently writing a script to install a new SQL Server instance with PowerShell.
In this script, after the instance has been created, I disable the dynamic port and give it a new fixed port.
Import-Module SqlPs
[...] # Install a new instance SQL Server
$wmi = (Get-Item "SQLServer:\SQL\$Env:ComputerName").ManagedComputer
$urn = "ManagedComputer[#Name='$Env:ComputerName']/ ServerInstance[#Name='$Instance']/ ServerProtocol[#Name='Tcp']"
$tcp = $wmi.GetSmoObject($urn)
$tcp.IPAddresses['IPAll'].IPAddressProperties['TcpPort'].Value = "$Port"
$tcp.IPAddresses['IPAll'].IPAddressProperties['TcpDynamicPorts'].Value = ""
$tcp.Alter()
This script works correctly but when I try to run it a second times on the same PowerShell window, it return the following error :
Exception calling "GetSmoObject" with "1" argument(s): "Attempt to retrieve data for object failed for ManagedComputer 'MYSERVER'."
At .\New-Instance.ps1:316 char:5
+ $tcp = $wmi.GetSmoObject($urn)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : FailedOperationException
$Error[0] | Format-List -Force
Exception : System.Management.Automation.MethodInvocationException: Exception calling "GetSmoObject" with "1" argument(s): "Attempt to retrieve data for object failed for ManagedComputer 'MYSERVER'." --->
Microsoft.SqlServer.Management.Smo.FailedOperationException: Attempt to retrieve data for object failed for ManagedComputer 'MYSERVER'. ---> Microsoft.SqlServer.Management.Smo.MissingObjectException: The
ServerInstance 'MYINSTANCE' does not exist on the server.
at Microsoft.SqlServer.Management.Smo.Wmi.ManagedComputer.GetSmoObjectRec(Urn urn)
at Microsoft.SqlServer.Management.Smo.Wmi.ManagedComputer.GetSmoObjectRec(Urn urn)
at Microsoft.SqlServer.Management.Smo.Wmi.ManagedComputer.GetSmoObject(Urn urn)
--- End of inner exception stack trace ---
at Microsoft.SqlServer.Management.Smo.Wmi.ManagedComputer.GetSmoObject(Urn urn)
at CallSite.Target(Closure , CallSite , Object , Object )
--- End of inner exception stack trace ---
at System.Management.Automation.ExceptionHandlingOps.CheckActionPreference(FunctionContext funcContext, Exception exception)
at System.Management.Automation.Interpreter.ActionCallInstruction`2.Run(InterpretedFrame frame)
at System.Management.Automation.Interpreter.EnterTryCatchFinallyInstruction.Run(InterpretedFrame frame)
at System.Management.Automation.Interpreter.EnterTryCatchFinallyInstruction.Run(InterpretedFrame frame)
TargetObject :
CategoryInfo : NotSpecified: (:) [], MethodInvocationException
FullyQualifiedErrorId : FailedOperationException
ErrorDetails :
InvocationInfo : System.Management.Automation.InvocationInfo
ScriptStackTrace : at <ScriptBlock>, D:\SqlServer\Scripts\New-Instance.ps1: line 316
at <ScriptBlock>, <No file>: line 1
PipelineIterationInfo : {}
PSMessageDetails :
Yet, the instance 'MYINSTANCE' has been installed successfully. I think the recovered ManagedComputer hasn't been update and doesn't include the new instance 'MYINSTANCE'.
How can I force the refresh of the recovered ManagedComputer ?
My PowerShell Version :
$PSVersionTable.PSVersion
Major Minor Build Revision
----- ----- ----- --------
5 1 14393 3471

Active Directory. The following exception occurred while retrieving member distinguishedName: An operations error occurred

I try to get information from AD using LDAP. Before, I mounted ntds.dit through DSAMAIN at localhost:5000.
PS C:\Users\Administrator> ([ADSI]"LDAP://localhost:5000/")
format-default : The following exception occurred while retrieving member "distinguishedName": "Unknown error
(0x80005000)"
+ CategoryInfo : NotSpecified: (:) [format-default], ExtendedTypeSystemException
+ FullyQualifiedErrorId : CatchFromBaseGetMember,Microsoft.PowerShell.Commands.FormatDefaultCommand
PS C:\Users\Administrator> ([ADSI]"LDAP://localhost:5000/DC=srv,DC=local")
format-default : The following exception occurred while retrieving member "distinguishedName": "An operations error
occurred.
"
+ CategoryInfo : NotSpecified: (:) [format-default], ExtendedTypeSystemException
+ FullyQualifiedErrorId : CatchFromBaseGetMember,Microsoft.PowerShell.Commands.FormatDefaultCommand
PS C:\Users\Administrator> [ADSI]::Exists("LDAP://localhost:5000/DC=srv,DC=local")
Exception calling "Exists" with "1" argument(s): "An operations error occurred.
"
At line:1 char:1
+ [ADSI]::Exists("LDAP://localhost:5000/DC=srv,DC=local")
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : DirectoryServicesCOMException
PS C:\Users\Administrator> [adsi]"LDAP://localhost:5000/RootDSE"
distinguishedName : {}
Path : LDAP://localhost:5000/RootDSE
What do I do wrong?

Issues with EPiServer.TinyMCESpellChecker / NHunspell

During a reinstallation of the EPiServer.TinyMCESpellChecker package, I was having problems with the NHunspell dependency. Trying out the SpellChecker would show a browser alert message with the HTML of an error page on it, with the message that it was unable to find NHunspellx86.DLL. I checked my bin/ folder, and indeed the DLL was missing. What was stranger was that it was present in the nuget packages/ folder for the NHunspell install.
Here is the error message that showed when I reinstalled NHunspell in particular:
PM> update-package -reinstall nhunspell
Attempting to gather dependency information for multiple packages with respect to project 'Guthrie.Web', targeting '.NETFramework,Version=v4.6.2'
Gathering dependency information took 7.41 sec
Attempting to resolve dependencies for multiple packages.
Resolving dependency information took 0 ms
Resolving actions install multiple packages
Retrieving package 'NHunspell 1.2.5554.16953' from 'nuget.org'.
Removed package 'NHunspell 1.2.5554.16953' from 'packages.config'
Successfully uninstalled 'NHunspell 1.2.5554.16953' from Guthrie.Web
Package 'NHunspell.1.2.5554.16953' already exists in folder 'C:\TFS2013\ClientGITCollection\Guthrie\GuthrieEpi\packages'
'Hunspellx86.dll' already exists. Skipping...
'Hunspellx64.dll' already exists. Skipping...
Added package 'NHunspell.1.2.5554.16953' to 'packages.config'
Executing script file 'C:\TFS2013\ClientGITCollection\Guthrie\GuthrieEpi\packages\NHunspell.1.2.5554.16953\tools\install.ps1'
Value does not fall within the expected range.
At C:\TFS2013\ClientGITCollection\Guthrie\GuthrieEpi\packages\NHunspell.1.2.5554.16953\tools\install.ps1:4 char:1
+ $hunspellx86Dll = $project.ProjectItems.Item("Hunspellx86.dll")
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : OperationStopped: (:) [], ArgumentException
+ FullyQualifiedErrorId : System.ArgumentException
You cannot call a method on a null-valued expression.
At C:\TFS2013\ClientGITCollection\Guthrie\GuthrieEpi\packages\NHunspell.1.2.5554.16953\tools\install.ps1:5 char:1
+ $hunspellx86Dll.Properties.Item("BuildAction").Value = 0 # BuildActio ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
You cannot call a method on a null-valued expression.
At C:\TFS2013\ClientGITCollection\Guthrie\GuthrieEpi\packages\NHunspell.1.2.5554.16953\tools\install.ps1:6 char:1
+ $hunspellx86Dll.Properties.Item("CopyToOutputDirectory").Value = 2 # ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
Value does not fall within the expected range.
At C:\TFS2013\ClientGITCollection\Guthrie\GuthrieEpi\packages\NHunspell.1.2.5554.16953\tools\install.ps1:10 char:1
+ $hunspellx64Dll = $project.ProjectItems.Item("Hunspellx64.dll")
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : OperationStopped: (:) [], ArgumentException
+ FullyQualifiedErrorId : System.ArgumentException
You cannot call a method on a null-valued expression.
At C:\TFS2013\ClientGITCollection\Guthrie\GuthrieEpi\packages\NHunspell.1.2.5554.16953\tools\install.ps1:11 char:1
+ $hunspellx64Dll.Properties.Item("BuildAction").Value = 0 # BuildActio ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
You cannot call a method on a null-valued expression.
At C:\TFS2013\ClientGITCollection\Guthrie\GuthrieEpi\packages\NHunspell.1.2.5554.16953\tools\install.ps1:12 char:1
+ $hunspellx64Dll.Properties.Item("CopyToOutputDirectory").Value = 2 # ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
Successfully installed 'NHunspell 1.2.5554.16953' to Guthrie.Web
As it turns out, the error message was appearing because the NHunspellx86 and NHunspellx64 DLLs are in the content folder of the nuget package. What this means is that if the file is present in your solution, it does not get overwritten. In order to resolve the error, I had to force uninstall NHunspell (force because I wanted nuget to ignore that the EPiServer spellchecker depended on it):
uninstall-package nhunspell -Force
and then delete the NHunspellx86 and NHunspellx64 DLL's in the root of my website project. Turns out, the original installation of EPiServer.TinyMCESpellChecker had put them there, and the fact that they existed was preventing nuget from reinstalling the package correctly by copying over the DLL's from the content tab. After you've deleted both DLL's, run the following:
install-package nhunspell
Now the console should show NHunspell installing without errors, and when your run EPiServer again, the TinyMCESpellchecker should work without errors!

Errors using DacServices to unregister a data tier

Upgrading my code from DacStore to work in SQL Server 2016 and running into issues with DacServices. The goal here is to unregister the data tier of a preexisting database before updating the schema.
Code snippet:
$serverconnection = New-Object System.Data.SqlClient.SqlConnection
If (!$uid -And !$pwd){
$serverconnection.ConnectionString = "Server = $server; Database = $database; Integrated Security = True;"
}
Else{
$serverconnection.ConnectionString = "server = $server; Database = $database; Integrated Security = False; User ID = $uid; Password = $pwd;"
}
# Load the DAC assembly
$validate = Test-Path $dacfxPath
if (!$dacfxPath){
throw 'No usable version of Dac Fx found.'
}
Add-Type -Path $dacfxPath # Attempt to load DAC assembly
$DacService = New-Object Microsoft.SqlServer.Dac.DacServices($serverconnection)
$dacName = $database
## Only delete the DAC definition from msdb, the associated database remains active.
$DacService.Unregister($dacName)
Error received when creating DacServices object:
New-Object : Exception calling ".ctor" with "1" argument(s): "Format of the initialization string does not conform to
specification starting at index 0."
At C:\Users\Administrator\AppData\Local\Temp\2\_ir_sf_temp_0\UnregisterDataTier.ps1:34 char:15
+ ... acService = New-Object Microsoft.SqlServer.Dac.DacServices($servercon ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [New-Object], MethodInvocationException
+ FullyQualifiedErrorId : ConstructorInvokedThrowException,Microsoft.PowerShell.Commands.NewObjectCommand
My connection string appears correct, and worked in the past. What else could I be doing incorrectly?
Update: Specifying in the DacServices constructor arg that it was a connection string seemed to fix the issue.
$DacService = New-Object Microsoft.SqlServer.Dac.DacServices($serverconnection.Connec‌​tionString)
Having an issue with the Unregister() method now, but one step closer!

Azure Powershell SQL DataBase Export to Storage Container gets "An Error Occurred while Sending the Request"

I'd appreciate any help, even if it's just to suggest a way to diagnose the situation. The error message isn't really helping.
I've built a new VM from which I'm running PowerShell scripts to backup my databases. It had worked before on an old server for several months, and worked once on the new server, then I upgraded my Azure PowerShell cmdlets, and haven't been able to get it to work again. Mostly it says "An Error Occurred while sending the request", although twice it's said "Error Copying Content to a Stream" instead.
Below is my source code, with sensitive stuff replaced with ?'s. When I display the $stctx and $dbctx, they seem to have reasonable values. I added the IP address of the server as an exception to the db firewall, and I've installed SQL Server Management Studio and verified that I can connect to the database.
Here are the two error messages that I get:
Start-AzureSqlDatabaseExport : An error occurred while sending the request.
At C:\Users\Public\PublicCmds\test.ps1:29 char:1
+ Start-AzureSqlDatabaseExport -SqlConnectionContext $dbctx -StorageContext $stctx ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [Start-AzureSqlDatabaseExport],
HttpRequestException
+ FullyQualifiedErrorId :
Microsoft.WindowsAzure.Commands.SqlDatabase.Database.Cmdlet.StartAzureSqlDatabaseExport
Start-AzureSqlDatabaseExport : Error while copying content to a stream.
At C:\Users\Public\PublicCmds\test.ps1:29 char:1
+ Start-AzureSqlDatabaseExport -SqlConnectionContext $dbctx -StorageContext $stctx ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [Start-AzureSqlDatabaseExport], HttpRequestException
+ FullyQualifiedErrorId :
Microsoft.WindowsAzure.Commands.SqlDatabase.Database.Cmdlet.StartAzureSqlDatabaseExport
Here is a sanitized version of the source code:
param($dbname)
if ($dbname -eq $null) {
write-host "Database code must be specified"
return
}
$password = "????????" | ConvertTo-SecureString -asPlainText -Force
$servercredential = new-object System.Management.Automation.PSCredential("????", $password)
$dbsize = 1
$dbrestorewait = 10
$dbserver = "????"
$stacct = $dbcode
$stkey = "????????"
$stctx = New-AzureStorageContext -StorageAccountName $stacct -StorageAccountKey $stkey
$dbctx = New-AzureSqlDatabaseServerContext -ServerName $dbserver -Credential $servercredential
$dt = Get-Date
$timestamp = "_" + $dt.Year + "-" + ("{0:D2}" -f $dt.Month) + "-" + ("{0:D2}" -f $dt.Day) + "-" + ("{0:D2}" -f $dt.Hour) + ("{0:D2}" -f $dt.Minute)
$bkupname = $dbname + $timestamp + ".bacpac"
write-host "db context"
$dbctx
write-host "storage context"
$stctx
write-host "Backup $dbname to $bkupname"
Start-AzureSqlDatabaseExport -SqlConnectionContext $dbctx -StorageContext $stctx - StorageContainerName databasebackup -DatabaseName $dbname -BlobName $bkupname
I made two changes that together fixed the problem:
- There was an error in the filename (wish the error message said as much)
- I changed to using AD security (the free kind)

Resources