Powershell: Setting anonymous user in IIS6 - iis-6

I'm using the PowerShell script below to set anonymous user identity and authentication methods on an IIS6 server. The script seems to work at first, but if I issue an iisreset after running it the values revert to the old ones! How do I persist them?
$server = "localhost"
$siteName = "www.mysite.com"
$iis = [ADSI]"IIS://$server/W3SVC"
$site = $iis.children | where { $_.keyType -eq "IIsWebServer" -and $_.ServerComment -eq $siteName }
$path = [ADSI]($site.path+"/ROOT")
$path.AnonymousUserName = "user"
$path.AnonymousUserPass = "pass"
$path.AuthFlags = 3
$path.CommitChanges()

Turns out the metabase is not persisted at once. iisreset forces shutdown of the IIS services and the information is lost.
There are two ways of fixing this:
Run C:\WINDOWS\system32\IIsCnfg.vbs /save
net stop and then net start

Related

Printing Name and value of configuration webapps of azure in powershell script

I written some code in PowerShell script to print the configuration of one web app using azure portal. But I struck in between that exactly I want to print names and values in config of particular web app like development environment...
Set-ExecutionPolicy -Scope Process -ExecutionPolicy Bypass Connect-AzAccount $subscriptions = Get-AzSubscription Write-Host "Subscription:" MDD-NU-01 -Separator "" Set-AzContext -Subscription MDD-NU-01 $srcResourceGroup = "d1-sap-rg52" $srcAppName = "d1-sap-web-l521" $srcAppServer = Get-AzWebApp -ResourceGroupName $srcResourceGroup -Name $srcAppName $srcAppSettings = $srcAppServer.SiteConfig.AppSettings
1.uptohere its connecting in config appsettings
2.In appsetting there are names and value will there
3.After this i struck here the logic should give the output like print all the name and value in configuration of web app("d1-sap-web-l521")
Please anybody help me out.
Thank you
You can directly get the required information of WebApps using Get-AzureRmWebApp. Below is the script that worked for me.
$WebAppInfo = Get-AzureRmWebApp -ResourceGroupName <YourResourceGroupName> -Name <YourWebAppName>
$Configurations = $WebAppInfo.SiteConfig.AppSettings
$Configurations
In portal:

Create AD application with VSTS task

I am trying to create a VSTS task, which should create an AD application.
Taken the DeployAzureResouceGroup as a sample, I have created to following script:
[CmdletBinding()]
param()
Trace-VstsEnteringInvocation $MyInvocation
Import-VstsLocStrings "$PSScriptRoot\Task.json"
$connectedServiceNameSelector = Get-VstsInput -Name "connectedServiceNameSelector" -Require
$connectedServiceName = Get-VstsInput -Name "connectedServiceName"
$connectedServiceNameClassic = Get-VstsInput -Name "connectedServiceNameClassic"
$domains = (Get-VstsInput -Name "domains").Split(";")
$appName = Get-VstsInput -Name "appName"
if($connectedServiceNameSelector -eq "ConnectedServiceNameClassic")
{
$connectedServiceName = $connectedServiceNameClassic
$action = $actionClassic
$resourceGroupName = $cloudService
}
Import-Module $PSScriptRoot\ps_modules\VstsAzureHelpers_
Initialize-Azure
# Import the loc strings.
Import-VstsLocStrings -LiteralPath $PSScriptRoot/Task.json
# Import all the dlls and modules which have cmdlets we need
Import-Module "$PSScriptRoot\DeploymentUtilities\Microsoft.TeamFoundation.DistributedTask.Task.Deployment.Internal.psm1"
Import-Module "$PSScriptRoot\DeploymentUtilities\Microsoft.TeamFoundation.DistributedTask.Task.Deployment.dll"
# Load all dependent files for execution
. "$PSScriptRoot\Utility.ps1"
try
{
Validate-AzurePowerShellVersion
$azureUtility = Get-AzureUtility "$connectedServiceName"
Write-Verbose "Loading $azureUtility"
. "$PSScriptRoot\$azureUtility"
Write-Output "test"
Write-Output "Creating a new Application in AAD (App URI -)" -Verbose
$azureAdApplication = New-AzureRmADApplication -DisplayName "test" -IdentifierUris "https://app.com" -HomePage "https://app.com"
$appId = $azureAdApplication.ApplicationId
Write-Output "Azure AAD Application creation completed successfully (Application Id: $appId)" -Verbose
Write-Verbose "Completing Azure Resource Group Deployment Task" -Verbose
}
catch
{
Write-TaskSpecificTelemetry "UNKNOWNDEP_Error"
throw
}
When I use a Service principal as Service Endpoint user, I got the error Resource me not found.
When I use my custom AD account, I got the error:Run Login-AzureRmAccount to login.
What am I doing wrong? How can I get this script working?
If you don't need Powershell scripting, go install Azure AD Application Management extension from https://marketplace.visualstudio.com/items?itemName=RalphJansen.Azure-AD-Application-Management
You can add new tasks from pipeline GUI for managing AD applications.
If you do need Powershell scripting, then things get tricky.
Get Powershell code from https://stackoverflow.com/a/51848069/1548275 as a base. The difference is, that if you're not running your code from an extension, you don't have Get-VstsInput nor Get-VstsEndpoint available to execute.
Also, you don't have AzureAD module cmdlets to run. You need to get the Nuget-package, unzip it to your own repo and have it as part of your scripts to be later Import-Module in a pipeline task.
Finally, you need an auth token for Graph API. As the extension code shows, you will need 3 variables:
$tenantId = (Get-AzureRmSubscription).TenantId
$clientId = (Get-AzureRmADServicePrincipal -DisplayName "Your Project Service Connection name from Azure AD App Registrations").ApplicationId.Guid
$clientSecret = 'hard-coded, reset SPN password'
As you can see, an extension would have access to all three, but regular script (to my knowledge) doesn't.
SPN password reset is covered in The Net. Briefly, it is something like this:
$clientId = (Get-AzureRmADServicePrincipal -DisplayName "Your Project Service Connection name from Azure AD App Registrations").Id.Guid
$password = ConvertTo-SecureString –asplaintext –force "oh, this is very secret!"
New-AzureRmADSpCredential -ObjectId $clientId -Password $password
Also: Update the plaintext password into Azure DevOps project settings, Service Connections for Pipeline to know about the update.

Stop-Service -ComputerName parameter ignored through SQL Agent

I have the following code which sucessfully stops a service on remote computer when run from the powershell console.
$Computer = "192.168.24.23"
$service = "Credential Checking LIVE"
Get-Service -ComputerName $Computer -name $service | Stop-Service
When i run this through a SQL Agent job the -ComputerName parameter is ignored.
Any ideas on why this would be and what i can do to rectify the problem?
I'd check the following
1) Does the SQL agent have rights to execute? (like briantist said)
2) Have you tried putting the logic in a script and executing the script from SQL?
3) Did you forget that you had to enter Set-Execution policy while testing?

Failed to connect to database server. How do I connect to a database that is not on my localhost using powershell and integrated security?

Background to my question
At any moment I am expecting the security people in black suits and black sun glasses to come and take me away because of all my sql server login attempts...
I used and adapted iris classon's example to connect to a database via Powershell. The adapted code uses Integrated Security=True"
$dataSource = my_enterprise_db_server
$database = my_db
$connectionString = "Server=$dataSource;Database=$database;Integrated Security=True;"
$connection = New-Object System.Data.SqlClient.SqlConnection
$connection.ConnectionString = $connectionString
$table = new-object “System.Data.DataTable”
$query = "..."
$connection.Open()
$command = $connection.CreateCommand()
$command.CommandText = $query
...
Hot diggity dog that worked. Thank's Iris.
I read the snapin verses the Import-Module sqlps way of executing a sql command. I also read all the links that Michael Sorens provided in his answer. I can mount a sqlserver connect with mount mydb SQLSERVER SQLSERVER:\SQL, use ls or dir, walk the path down the objects, etc. I also revised the main part of what Iris provided to
$table = Invoke-Sqlcmd –Server $dataSource –Database $database -Query $query
This version of Invoke-Sqlcmd allows me to connect to an "enterprise" database. The problem with all the references provided are that they expect you to work with a localhost sqlexpress database. The moment I try to use
Set-Location SQLSERVER:\SQL\my_enterprise_db_server\my_db
or similar constructs, I receive a message that ends with
...WARNING: Could not obtain SQL Server Service information. An attempt to connect to WMI on 'my_enterprise_db_server' failed with the following error: Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))
I also saw mention of the SQLCMDSERVER and SQLCMDDBNAME environment variables. I set these to
$env:SQLCMDDBNAME = "my_db"
$env:SQLCMDSERVER = "my_enterprise_db_server"
set-location sqlserver:\sql
ls
produces
MachineName
-----------
localhost
Question
How do I correctly use set-location or New-PSDrive-Name for a database that does not reside on my local computer?
I found the answer by a serendipitous route. I right clicked on a database object in sql server management studio. There was an option to start powershell. Even though this looks like the order sqlps option, SSMS gave me the right way to set the location.
Option 1. If the server does not have instances, then add DEFAULT after the server_name in the slashy path.
Set-Location SQLSERVER:\SQL\server_name\DEFAULT\Databases\database_name\Tables\dbo.table_name
Option 2. If you have a server with an instance, then set the instance name after the server_name in the slashy path.
Set-Location SQLSERVER:\SQL\server_name\instance_name\Databases\database_name\Tables\dbo.table_name
I am a mere mortal as far as database security goes. Many of the features of SSMS are turned off to me because of my security settings verses how the dba security settings are configured. I receive errors in in SSMS all the time. Well that is no different with Powershell using the Set-Location. I did not realize that the two error messages where related because of the security policy configuration verses pilot error. If I set a location to a table, then I only have two warnings of access denied. If I set the location to the database level, then Powershell blows chunks for a bit but I have my slashy path setting. I do not see the errors if I used the Invoke-SqlCmd. I see now that the way the security errors were presented in Powershell are why I thought there was a problem with how I was attempting to connect to the database. Now I can do this:
mount rb SELSERVER SQLSERVER:\SQL\server_name\DEFAULT\Databases\database_name\Tables
# Look at a list of tables.
ls
# Go to a traditional file system
cd F:\
# Go to the Linux Style mounted file system
cd rb:\
# Go to a table like a directory
cd dbo.my_table_name
# Look at the column names
ls
# Use relative navigation
cd ..\dbo.my_other_table_name
ls
# Compare column names with another table using relative navigation after I have just
# listed the current directory/table that I am in.
ls ..\dbo.my_table_name
That just rocks! Now all I need to do is come up with an array of server names and databases to create mount points for all the databases that I can connect to. An array like that is just begging for an iteration to create all the mount points.

PCSP hanging when user not logged in

I am having problem with PCSP hanging.
PCSP is called from within a WCF service running in IIS on Windows 2008 r2.
The service is running under an app pool that is running as a domain user
the host key has been cached for that user
A client will call the service across the local network
The service will get this message and transfer the file accross to the
external site
However, this will only work if the user that the app pool/service is running as is logged into Remote Desktop
As soon as the Remote Desktop session is ended and another call is made from the client the call to PCSP will just hang.
The command and arguments that are made to PSCP are below. Followed by the code that is used to call the command
pscp.exe -pw APassword -P 22 -sftp -q -batch "\\AServer\AFolder\AFile.csv" auser#service:/adirectory
System.Diagnostics.Process proc = new System.Diagnostics.Process();
proc.StartInfo.FileName = executablePath;
proc.StartInfo.RedirectStandardError = true;
proc.StartInfo.RedirectStandardOutput = true;
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.LoadUserProfile = true;
proc.StartInfo.Arguments = arguments;
proc.Start();
proc.WaitForExit(60 * 60 * 5);
I suspect it has something to do with the getting of the host key from the registry but for the life of me cant work out what that may be. Any help with this would be greatly appreciated
After 2 days banging my head on a brick wall I found the answer.
Under the app pool settings go to Advanced Settings and there under ProcessModel is a setting to "Load User Profile" Set this to true!