How to change LogFile.Directory property via WMI on a remote computer? - iis-7

I was able to retrieve, using WMI, the value of LogFile.Directory for a specific IIS site located on a remote computer.
Now I need to change the LogFile.Directory property - this is a step in an automation process - but I am hitting a wall. This is what I have so far, although it doesn't work.
Write-Output "Making IIS connection to $($XmlCloudNodeFullyQualifiedDomainName)"
$site = Get-WmiObject -ComputerName $XmlCloudNodeFullyQualifiedDomainName -Namespace "root/webadministration" -Class Site -Authentication 6 -Filter "Name = '$IISSiteName'"
If ($site.Name -eq $IISSiteName) {
Write-Output "Found site $IISSiteName"
Write-Output ("Existing log folder: " + $site.LogFile.Directory)
$newLogFolder = "E:\" + $IISSiteName + "\logs"
Write-Output ("Set IIS log folder to " + $newLogFolder)
$site.LogFile.Directory = $newLogFolder
$site.Put()
}
I don't get any errors. Simply the LogFile.Directory value does not change on the remote machine when I check in IIS Manager.
I've read that I should be using Set-WMIInstance instead, so I tried:
Write-Verbose "Making IIS connection to $($XmlCloudNodeFullyQualifiedDomainName)"
$site = Get-WmiObject -ComputerName $XmlCloudNodeFullyQualifiedDomainName -Namespace "root/webadministration" -Class Site -Authentication 6 -Filter "Name = '$IISSiteName'"
$sitePath = (Get-WmiObject -ComputerName $XmlCloudNodeFullyQualifiedDomainName -Namespace "root/webadministration" -Class Site -Authentication 6 -Filter "Name = '$IISSiteName'").__path
If ($site.Name -eq $IISSiteName) {
Write-Output "Found site $IISSiteName"
$newLogFolder = "E:\" + $IISSiteName + "\logs"
Write-Output ("Existing log folder: " + $site.LogFile.Directory)
Set-WmiInstance -Path $sitePath -argument #{LogFile.Directory = $newLogFolder}
Write-Output ("Set IIS log folder to " + $newLogFolder)
}
But this throws errors:
At E:\\Test.ps1:71 char:54
+ Set-WmiInstance -Path $sitePath #{LogFile.Directory = $newLogFolder}
+ ~
Missing '=' operator after key in hash literal.
At E:\\Test.ps1:72 char:18
+ Write-Output ("Set IIS log folder to " + $newLogFolder)
+ ~
Missing '=' operator after key in hash literal.
At E:\\Test.ps1:41 char:54
+ foreach ($FSMappingNode in $FSMappingNodesArray) {
+ ~
Is there a way to change this particular value remotely or is it a read-only property?
Any help would be greatly appreciated.
Thanks,
// Francesco

After much tinkering, I finally found the way to change the LogFile.Directory of an IIS site remotely:
Write-Output "Making IIS connection to $($XmlCloudNodeFullyQualifiedDomainName)"
$site = Get-WmiObject -ComputerName $XmlCloudNodeFullyQualifiedDomainName -Namespace "root/webadministration" -Class Site -Authentication 6 -Filter "Name = '$IISSiteName'"
$sitePath = $site.__path
Write-Verbose $sitePath
If ($site.Name -eq $IISSiteName) {
Write-Output "Found site $IISSiteName"
Write-Verbose ("Existing log folder: " + $site.LogFile.Directory)
$newLogFolder = "E:\" + $IISSiteName + "\logs"
$siteLogFile = $site.LogFile
$siteLogFile.Directory = $newLogFolder
Set-WmiInstance -Path $sitePath -Arguments #{LogFile = $siteLogFile}
Write-Output ("Set IIS log folder to " + $siteLogFile.Directory)
}

Related

Execute .jar file in .net core on Openshift container platform

net core application which internally calls a java (.jar) file using .net Process class. I have used cmd.exe to run .jar file along with parameters. I have deployed this application on Openshift Container Platform. But as openshift is running on Linux, so cmd.exe is not available.
Below is code in .net core to execute jar file.
Process cmd = new Process();
cmd.StartInfo.UseShellExecute = false;
cmd.StartInfo.WorkingDirectory = Common.JarWorkingDir;
cmd.StartInfo.FileName = "cmd.exe";
cmd.StartInfo.Arguments = "/K java -jar " + string.Format("{0} {1}", '"' + Common.JarFilePath + '"', '"' + sourceCodePath + '"');
cmd.StartInfo.CreateNoWindow = true;
cmd.StartInfo.RedirectStandardInput = true;
cmd.Start();
cmd.StandardInput.WriteLine("exit");
cmd.StandardInput.Flush();
cmd.WaitForExit();
So Jar file is unable to execute. Any alternative to execute this jar with .net on OpenShift. Please help.
OpenShift is essentially Kubernetes running Linux containers. In other words, your code should act as if it is running on Linux.
Instead of cmd.exe, use bash (or, sh, or really, whatever shell is pre-installed in your container):
Process cmd = new Process();
cmd.StartInfo.UseShellExecute = false;
cmd.StartInfo.WorkingDirectory = Common.JarWorkingDir;
cmd.StartInfo.FileName = "bash";
cmd.StartInfo.Arguments = "-c 'java -jar " + string.Format("{0} {1}", '"' + Common.JarFilePath + '"', '"' + sourceCodePath + '"'');
cmd.StartInfo.CreateNoWindow = true;
cmd.StartInfo.RedirectStandardInput = true;
cmd.Start();
cmd.StandardInput.WriteLine("exit");
cmd.StandardInput.Flush();
cmd.WaitForExit();
You can maybe even remove some of the lines. CreateNoWindow, for example, is not required because .NET Core does not create windows on Linux at all.
If you have no shell expressions, perhaps you can even get things to be simpler and simplify from this:
cmd.StartInfo.UseShellExecute = false;
cmd.StartInfo.FileName = "bash";
cmd.StartInfo.Arguments = "-c 'java -jar " + string.Format("{0} {1}", '"' + Common.JarFilePath + '"', '"' + sourceCodePath + '"'');
to something like this:
cmd.StartInfo.UseShellExecute = false;
cmd.StartInfo.FileName = "java";
cmd.StartInfo.Arguments = $"-jar \"{Common.JarFilePath}\" \"{sourceCodePath}\"";
Oh, and watch out for the quoting in your Arguments variable. If you wrap the entire command after -c with single quotes, you should be fine, but if you are doing something trickier - if Common.JarFilePath isn't a simple file name - it may not work so well. Definitely test and tweak that. Maybe consider EscapeAndConcatenate.

Invoke-Webrequest ASP.Net Error

I have a script which I use to load a webpage, retrieve information from said webpage, then output said information to a file. It had been working perfectly until today, when I have been getting an error which reads:
invoke-webrequest : Response object error 'ASP 0251 : 80004005'
Response Buffer Limit Exceeded
/foo/Reports/SearchLocation.asp, line 0
Execution of the ASP page caused the Response Buffer to exceed its configured limit.
At C:\path.ps1:7 char:12
+ $url = invoke-webrequest "http://url/ ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-WebRequest], WebException
+ FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeWebRequestCommand
I do not believe there have been any changes to the site which it is pulling its data from, and the file it is getting the input information from has no formatting errors.
Some googling around leads me to believe that the issue is that the page has more than 4 mb worth of data to load, and the default buffer size is 4 mb, but I can't find any instructions for how to change the buffer size in PowerShell.
I came across the clear-webconfiguration cmdlet, but I'm not certain whether or not that is what I need, or how exactly to implement it within my script. Here is the main portion of my code:
foreach($c in $csv){
[array]$tags = $null
$url = invoke-webrequest "http://url.com" -UseDefaultCredentials
$table = $url.ParsedHTML.getElementsByTagName('table')[7]
$rows = $table.getElementsByTagName('tr')
if($c.'Was this user on the old file?' -eq 'Yes'){
if($table.innerText -like "*N/A*" ){
$man = $c.'Manager Name' -replace ',',';'
$badusers += $c.'User ID' + "," + $c.Name + "," + $man + "," + $c.'CC'
}
else{
foreach($row in $rows){
$bcol = $row.getElementsByTagName('td') | Where-Object{$_.cellIndex -eq 1} | select -First 1
$ccol = $row.getElementsByTagName('td') | Where-Object{$_.cellIndex -eq 7} | select -First 1
$bcol = $bcol.innerText
$ccol = $ccol.innerText
if($ccol -ne $c.'CC'){
$tags += $bcol + ",," + $c.'CC' + "," + $c.'User ID'
}
}
if($tags -ne $null){
$results += $tags
}
}
}
}
Any help on solving this issue is much appreciated.

PowerShell script not working on server

I have a simple PowerShell script in which I try to write some log data.
The script that's not working:
Add-Content -Path C:\temp\logg.txt -Value $file.FullName
This line I placed in the middle of the script and I never get any text in the logg.txt. The Script executes fine except this, it compiles some files to a zip file.
This is on a Windows server.
If I, however, run the same script on my local machine, Win7, it does work!?
So I think it must be something with the server but I can't figure it out. Am using -ExecutionPolicy Bypass when I run the script.
EDIT: more info.
The script is called from an ASP.NET webpage:
Process.Start("Powershell.exe", "-ExecutionPolicy Bypass -Command ""& {" & destinationFolderRoot.Replace("\\", "\") & "\scriptParameters.ps1}""")
BaseZipScript:
function New-Zip
{
param([string]$zipfilename)
Set-Content $zipfilename ("PK" + [char]5 + [char]6 + ("$([char]0)" * 18))
(dir $zipfilename).IsReadOnly = $false
}
function Add-Zip
{
param([string]$zipfilename)
if(-not (Test-Path($zipfilename)))
{
Set-Content $zipfilename ("PK" + [char]5 + [char]6 + ("$([char]0)" * 18))
(dir $zipfilename).IsReadOnly = $false
}
$shellApplication = New-Object -COM Shell.Application
$zipPackage = $shellApplication.NameSpace($zipfilename)
foreach($file in $input)
{
$zipPackage.CopyHere($file.FullName)
Add-Content -Path "C:\temp\logg.txt" -Value $file.FullName
Start-Sleep -Milliseconds 750
}
}
scriptParameters1:
. "C:\temp\multiDownload\baseZipScript.ps1"
New-Zip c:\temp\multiDownload\user379\2016-09-15_14.39\files_2016-09-15_14.39.zip
dir c:\temp\multiDownload\user379\2016-09-15_14.39\tempCopy\*.* -Recurse |
Add-Zip c:\temp\multiDownload\user379\2016-09-15_14.39\files_2016-09-15_14.39.zip
Start-sleep -milliseconds 250
exit
As I said earlier the script works on local machine and also on the server, e.g. the files are being zipped, except that on the server nothing is logged in logg.txt.
Though the logg.txt works and exists on the server because the webpage also log some info there and that is being written.
Update:
As the comments guessed it was as simple as write access to the file. Though, it is kind of wierd because all files are created from the webservice if they doesn't exists? Any how, it works now. Thx! : )

MSB4018 Error Visual Studio 2015 ASP.Net and Error Publish Web App to Azure

I am working with Visual Studio 2015 Community with Azure 2.9 For the first time. I tried creating a brand new ASP.Net Web Application. The default template build and viewed in the Browser with no issues.
I tried publishing the site using Azure. When doing so I get this error
The "InvokePowerShell" task failed unexpectedly.
System.Management.Automation.CommandNotFoundException: The term '[cmdletbinding(SupportsShouldProcess=$true)]
param($publishProperties, $packOutput, $nugetUrl)
# to learn more about this file visit http://go.microsoft.com/fwlink/?LinkId=524327
$publishModuleVersion = '1.0.1'
function Get-VisualStudio2015InstallPath{
[cmdletbinding()]
param()
process{
$keysToCheck = #('hklm:\SOFTWARE\Wow6432Node\Microsoft\VisualStudio\14.0',
'hklm:\SOFTWARE\Microsoft\VisualStudio\14.0',
'hklm:\SOFTWARE\Wow6432Node\Microsoft\VWDExpress\14.0',
'hklm:\SOFTWARE\Microsoft\VWDExpress\14.0'
)
[string]$vsInstallPath=$null
foreach($keyToCheck in $keysToCheck){
if(Test-Path $keyToCheck){
$vsInstallPath = (Get-itemproperty $keyToCheck -Name InstallDir -ErrorAction SilentlyContinue | select -ExpandProperty InstallDir -ErrorAction SilentlyContinue)
}
if($vsInstallPath){
break;
}
}
$vsInstallPath
}
}
$vsInstallPath = Get-VisualStudio2015InstallPath
$publishModulePath = "{0}Extensions\Microsoft\Web Tools\Publish\Scripts\{1}\" -f $vsInstallPath, $publishModuleVersion
if(!(Test-Path $publishModulePath)){
$publishModulePath = "{0}VWDExpressExtensions\Microsoft\Web Tools\Publish\Scripts\{1}\" -f $vsInstallPath, $publishModuleVersion
}
$defaultPublishSettings = New-Object psobject -Property #{
LocalInstallDir = $publishModulePath
}
function Enable-PackageDownloader{
[cmdletbinding()]
param(
$toolsDir = "$env:LOCALAPPDATA\Microsoft\Web Tools\Publish\package-downloader-$publishModuleVersion\",
$pkgDownloaderDownloadUrl = 'http://go.microsoft.com/fwlink/?LinkId=524325') # package-downloader.psm1
process{
if(get-module package-downloader){
remove-module package-downloader | Out-Null
}
if(!(get-module package-downloader)){
if(!(Test-Path $toolsDir)){ New-Item -Path $toolsDir -ItemType Directory -WhatIf:$false }
$expectedPath = (Join-Path ($toolsDir) 'package-downloader.psm1')
if(!(Test-Path $expectedPath)){
'Downloading [{0}] to [{1}]' -f $pkgDownloaderDownloadUrl,$expectedPath | Write-Verbose
(New-Object System.Net.WebClient).DownloadFile($pkgDownloaderDownloadUrl, $expectedPath)
}
if(!$expectedPath){throw ('Unable to download package-downloader.psm1')}
'importing module [{0}]' -f $expectedPath | Write-Output
Import-Module $expectedPath -DisableNameChecking -Force
}
}
}
function Enable-PublishModule{
[cmdletbinding()]
param()
process{
if(get-module publish-module){
remove-module publish-module | Out-Null
}
if(!(get-module publish-module)){
$localpublishmodulepath = Join-Path $defaultPublishSettings.LocalInstallDir 'publish-module.psm1'
if(Test-Path $localpublishmodulepath){
'importing module [publish-module="{0}"] from local install dir' -f $localpublishmodulepath | Write-Verbose
Import-Module $localpublishmodulepath -DisableNameChecking -Force
$true
}
}
}
}
try{
if (!(Enable-PublishModule)){
Enable-PackageDownloader
Enable-NuGetModule -name 'publish-module' -version $publishModuleVersion -nugetUrl $nugetUrl
}
'Calling Publish-AspNet' | Write-Verbose
# call Publish-AspNet to perform the publish operation
Publish-AspNet -publishProperties $publishProperties -packOutput $packOutput
}
catch{
"An error occurred during publish.`n{0}" -f $_.Exception.Message | Write-Error
}' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
at System.Management.Automation.Runspaces.AsyncResult.EndInvoke()
at System.Management.Automation.PowerShell.EndInvoke(IAsyncResult asyncResult)
at Microsoft.Web.Publishing.Tasks.InvokePowerShell.Execute()
at Microsoft.Build.BackEnd.TaskExecutionHost.Microsoft.Build.BackEnd.ITaskExecutionHost.Execute()
at Microsoft.Build.BackEnd.TaskBuilder.<ExecuteInstantiatedTask>d__26.MoveNext() WebApplication1 0
I am assuming I missed something in my install? Anyone know what this error is or how to get passed it?
I upvoted this in the past, then apparently found the answer somewhere else, then forgot the answer again and ended up here again.
Adding <AutoParameterizationWebConfigConnectionStrings>False</AutoParameterizationWebConfigConnectionStrings>
in the csproj on the right PropertyGroup fixed the problem for me.

How can I have a Windows Service, installed using OctopusDeploy, use an app.config?

So far, I've been able to create a Windows Service, which I can then get TeamCity to build and pack up and make available for Octopus Deploy.
What I can't seem to do, is have an app.config which has a connection string in it and use that connection string.
The following is my Deploy.ps1:
# These variables should be set via the Octopus web portal:
#
# ServiceName - Name of the Windows service
#
# sc.exe is the Service Control utility in Windows
# Default the service name
if (! $ServiceName)
{
$ServiceName = "OctoService"
}
Write-Host "Service Name:" $ServiceName
# Get the exe name based ont the directory
$contentPath = (Join-Path $OctopusPackageDirectoryPath "content")
$configName = (Get-ChildItem $contentPath\*.config -Name | Select-Object -First 1)
$binPath = (Join-Path $OctopusPackageDirectoryPath "lib\net40")
$exeName = (Get-ChildItem $binPath\*.exe -Name | Select-Object -First 1)
$fullPath = (Join-Path $binPath $exeName)
Write-Host "Service Path:" $fullPath
Write-Host "Config Path:" (Join-Path $contentPath $configName)
Copy-Item (Join-Path $contentPath $configName) $binPath
$service = Get-Service $ServiceName -ErrorAction SilentlyContinue
if (! $service)
{
Write-Host "The service will be installed"
New-Service -Name $ServiceName -BinaryPathName $fullPath -StartupType Automatic
}
else
{
Stop-Service $ServiceName -Force
$fullPath = Resolve-Path $fullPath
& "sc.exe" config "$ServiceName" binPath= $fullPath start= auto | Write-Host
Start-Service $ServiceName
}
Here's my .nuspec file:
<?xml version="1.0"?>
<package xmlns="http://schemas.microsoft.com/packaging/2010/07/nuspec.xsd">
<metadata>
<id>$id$</id>
<version>$version$</version>
<title>$title$</title>
<authors>$author$</authors>
<owners>$author$</owners>
<requireLicenseAcceptance>false</requireLicenseAcceptance>
<description>$description$</description>
<copyright>Copyright 2012</copyright>
</metadata>
<files>
<file src="app.config" target="content" />
<file src="Deploy.ps1" />
</files>
</package>
If I try to access ConfigurationManager.ConnectionStrings["MyConnectionString"], I'll get a null reference.
Any suggestions?
my money is on you needing to name your app.config to exename.exe.config so it is picked up by your service.
App.config is the 'temporary' name used in the ide, it gets renamed as part of the build to whatever the exe name is

Resources