using powershell to set an event logs "Maximum Size" action - c#

When viewing an Event Logs properties (in Server 2008) you can set three actions for what to happen when the maximum event log size has been reached:
Overwrite events as needed
Archive the log when full
Do not overwrite events
Using Powershell I can use limit-eventlog to set the event log retention to set the OverflowAction to DoNotOverwrite or OverwriteAsNeeded, but I cannot seem to be able to get the Archive the log when full action selected.
Any ideas how I could select this option via powershell?

The only way (IMO) is to modifying the registry. Here an example to set 'Archive the log when full' action for the Application log:
new-ItemProperty -path HKLM:\SYSTEM\CurrentControlSet\services\eventlog\Application `
-name AutoBackupLogFiles -Value 1 -PropertyType 'dword'
if the options have been selected previously, the key is already present so just need set to 1 the key value:
set-ItemProperty -path HKLM:\SYSTEM\CurrentControlSet\services\eventlog\Application `
-name AutoBackupLogFiles -Value 1

Related

Updating PATH environment variable via registry setting using C# causes path to no longer be valid

I have a folder that I want to add to the PATH variable under Environment Variables (for the machine). I am appending the folder to the path via the registry setting. SYSTEM\CurrentControlSet\Control\Session Manager\Environment.
Here is a snippet of the code where I read the registry setting. And I perform a registry update on the setting, so nothing revolutionary.
String keyName = #"SYSTEM\CurrentControlSet\Control\Session Manager\Environment\";
string existingPathFolderVariable = (string)Registry.LocalMachine.OpenSubKey(keyName).GetValue("PATH", "", RegistryValueOptions.DoNotExpandEnvironmentNames);
string keyValue = #"c:\MyPath\";
if ( !existingPathFolderVariable.Contains(keyValue) )
{
if (!existingPathFolderVariable.EndsWith(";", StringComparison.InvariantCulture))
{
existingPathFolderVariable += ';';
}
Followed by code to update registry value, standard registry functions.
}
I tried various options of updating the registry including using powershell.
$oldpath = (Get-ItemProperty -Path 'Registry::HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Session Manager\Environment' -Name PATH).path
$newpath = "$oldpath;c:\install\sysinternals"
Set-ItemProperty -Path 'Registry::HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Session Manager\Environment' -Name PATH -Value $newPath
(Get-ItemProperty -Path 'Registry::HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Session Manager\Environment' -Name PATH).Path
Though the path is updated and the values look correct, the path is no longer valid. The commands under the System32 folder are no longer valid. If I perform a ping, I get the unknown command message. Same for ipconfig and other commands.
I read that I could use the SetEnvironmentVariable function. But I do not want the values expanded.
If I copy the line, delete the line, and add the line via the registry setting or UI, the problem is resolved.
Any suggestions on how to resolve the problem?

how to seed data in table storage?

How do we seed table storage tables in order to automate the deployment process?
We've got the following resources all in the same resource group in our dev subscription:
storage account
events in the storage account for blob created
config data in table storage
function app
logic app
In order to automate the deployment of these resources, I've downloaded the ARM template from the resource group:
We can then simply redeploy to any destination resource group:
However, this will not deploy resources like the storage tables, events, seeding data into the tables.
How do we automatically seed table storage tables in order to automate the deployment?
Do something like this.
In your project check in your CSV file
In your build definition add a step to copy files - https://learn.microsoft.com/en-us/azure/devops/pipelines/tasks/utility/copy-files?view=azure-devops&tabs=yaml
In your release pipeline run your PS script like I mentioned in my comment above - https://learn.microsoft.com/en-us/azure/devops/pipelines/tasks/utility/powershell?view=azure-devops
You can use something like this for your PS script to load the csv file
# Load the CSV
$csv = Import-CSV $PSScriptRoot'\yourSeedData.csv'
# And push it to storage
ForEach ($line in $csv)
{
$entity = New-Object -TypeName Microsoft.WindowsAzure.Storage.Table.DynamicTableEntity -ArgumentList $line.PartitionKey, $line.RowKey
if($line.Description -ne $null) {
$entity.Properties.Add("Property1", $line.Property1)
}
$entity.Properties.Add("Property2", $line.Property2)
$result = $table.CloudTable.Execute([Microsoft.WindowsAzure.Storage.Table.TableOperation]::InsertOrReplace($entity))
}
I went with this option to seed data automatically using powershell:
$partitionKey1 = "partition1"
$partitionKey2 = "partition2"
# add four rows
Add-AzTableRow `
-table $cloudTable `
-partitionKey $partitionKey1 `
-rowKey ("CA") -property #{"username"="Chris";"userid"=1}
Add-AzTableRow `
-table $cloudTable `
-partitionKey $partitionKey2 `
-rowKey ("NM") -property #{"username"="Jessie";"userid"=2}
Add-AzTableRow `
-table $cloudTable `
-partitionKey $partitionKey1 `
-rowKey ("WA") -property #{"username"="Christine";"userid"=3}
Add-AzTableRow `
-table $cloudTable `
-partitionKey $partitionKey2 `
-rowKey ("TX") -property #{"username"="Steven";"userid"=4}

Write to a file without read permission

I'm trying to Implement The Bell-La Padula Model on local windows accounts in C# , and in this model the user in lower security level can write to files that belong to higher security level without read it !!
I've Added permissions to files like this
file.txt : read [deny] - write [Allow]
Now I'm working on allow user to append text to file.txt without read it .
I used this :
using (FileStream aFile = new FileStream(filename, FileMode.Append, FileAccess.Write))
using (StreamWriter sw = new StreamWriter(aFile))
{
sw.WriteLine(DateTime.Now.ToString() + " Modified BY :" + username + Environment.NewLine);
sw.WriteLine(textBox1.Text);
sw.WriteLine("---------- END User Edition --------------");
}
It worked when I run The program from the Admin account ,but when I tried to run it from Guset account it raise exception : you can't access this file !
I've tried to add read permissions before Start Editing and remove it after finish , but the the file permissions never changed .
Is there any programmatic way that I can implement that , or allow my application to make effect on file when run it within Guest account ?
Took a little time but got it figured out. Had to use procmon to figure it out. Your code is fine. However, you need to setup permissions properly.
For your text file, you need to grant the limited account rights to Write only. Do not check anything under the deny column. Because if you do, the deny access will trump anything else. You also need to grant that account access to Read Attributes and Read Extended Attributes permissions as well.
You can probably accomplish the same thing using icacls or cacls. Here are the manual instructions on how to do it manually. This is based on Windows 10 (Win7 should be similar):
Right click on the file
click on properties.
switch to Security tab.
Click on "Edit" button
Click on "Add..." button
Find the limited user account.
Back in the permissions tab, select the account.
uncheck everything except "Write" checkbox.
Click "OK" to close this dialog box.
Click on "Advanced" button.
Select the account and click "Edit" button.
On the next dialog box, click "Show advanced permissions"
Make sure that the following check boxes are checked.
Read Attributes
Read extended attributes
Create files / write data
Create folders / append data
Write attributes
Write extended attributes
Click OK on all the dialog boxes.
To do this programmatically, you need to allow these:
System.Security.AccessControl.FileSystemRights.AppendData
System.Security.AccessControl.FileSystemRights.CreateFiles
System.Security.AccessControl.FileSystemRights.ReadAttributes
System.Security.AccessControl.FileSystemRights.ReadExtendedAttributes
System.Security.AccessControl.FileSystemRights.WriteAttributes
System.Security.AccessControl.FileSystemRights.WriteExtendedAttributes
Extra info here
Read/Write(Extended)Attributes are necessary for write operations, above will let users to create log files and append text to them without being able to read anything, If you add Delete permission, that will make rolling of the log files possible as well (i'd say most of people will need it as having unlimited size logs without rolling is quite dangerous)
This can be done via any .NET language, PowerShell example (create and write logs files and roll them permissions):
$acl = Get-Acl "C:\logs"
$acl.SetAccessRuleProtection($true, $false) # Remove inherited
$acl.Access | % { $acl.RemoveAccessRule($_) } | Out-Null # Remove existing
$acl.AddAccessRule((New-Object System.Security.AccessControl.FileSystemAccessRule("SYSTEM", "FullControl", "ContainerInherit, ObjectInherit", "None", "Allow")))
$acl.AddAccessRule((New-Object System.Security.AccessControl.FileSystemAccessRule("Administrators", "FullControl", "ContainerInherit, ObjectInherit", "None", "Allow")))
$logsRights = [System.Security.AccessControl.FileSystemRights]::AppendData -bor `
[System.Security.AccessControl.FileSystemRights]::CreateFiles -bor `
[System.Security.AccessControl.FileSystemRights]::Delete -bor `
[System.Security.AccessControl.FileSystemRights]::ReadAttributes -bor `
[System.Security.AccessControl.FileSystemRights]::ReadExtendedAttributes -bor `
[System.Security.AccessControl.FileSystemRights]::WriteAttributes -bor `
[System.Security.AccessControl.FileSystemRights]::WriteExtendedAttributes
$acl.AddAccessRule((New-Object System.Security.AccessControl.FileSystemAccessRule("Users", $logsRights, "ContainerInherit, ObjectInherit", "None", "Allow")))
Set-Acl "C:\logs" $acl
Write-Host "logs ACL"
$acl.Access
Depending on your use case you may or may not need to clear existing rules and add SYSTEM/Administrators, but you get the idea

Checking who edited my file

There is file named status.html which is used as a loadbalancer between WFE's on SharePoint servers. My query is I want to come up with a script or a mechanism that will trigger a mail as soon as this file is edited by someone.
Is it possible?
In my research I have found this script:
$ACL = new-object System.Security.AccessControl.DirectorySecurity
$AccessRule = new-object System.Security.AccessControl.FileSystemAuditRule("domain\seitconsult","Modify","success")
$ACL.SetAuditRule($AccessRule)
$ACL | Set-Acl "C:\windows\system32\cmd.exe"
But I'm not sure if that will work. Also, how can trigger an email using this script?
I see two ways to achieve your goal:
Attach a "send an e-mail" task to the event in question:
Open the Event Viewer (eventvwr.msc) and select an event you want to be notified about.
Click Action → Attach Task To This Event…
Step through the wizard and select Send an e-mail in the Action section.
Fill in the details and finish the wizard.
See here for more information.
Set up a FileSystemWatcher:
$folder = 'C:\your\html\folder'
$file = 'status.html'
$from = 'monitor#example.com'
$to = 'you#example.com'
$subject = "$file was modified"
$monitor = New-Object IO.FileSystemWatcher $folder, $file -Property #{
IncludeSubdirectories = $false
NotifyFilter = [IO.NotifyFilters]'FileName, LastWrite'
}
Register-ObjectEvent $monitor Changed -SourceIdentifier FileChanged -Action {
$name = $Event.SourceEventArgs.FullPath
$reader = New-Object System.IO.StreamReader($name)
$msg = $reader.ReadToEnd()
Send-MailMessage -From $from -To $to -Subject $subject -Body $msg
$reader.Close()
}
However, since the NotifyFilters don't include the username you need to extract that from the respective audit event in the eventlog as described here.
The watcher can be removed via its source identifier:
Unregister-Event -SourceIdentifier FileChanged

Azure, Increase Worker Count Programatically, Management API / Cmdlets? (without reboot) [duplicate]

Is it possible to update the value of a setting in an Azure Cloud Service with Azure Powershell?
So far there is no way to update just a single setting (the Service Management API does not allow it - it only accepts the whole service configuration). So, in order to update a single setting, you will have to update the entire configuration. And you can do this with PowerShell:
# Add the Azure Account first - this will create a login promppt
Add-AzureAccount
# when you have more then one subscription - you have explicitly select the one
# which holds your cloud service you want to update
Select-AzureSubscription "<Subscription name with spaces goes here>"
# then Update the configuration for the cloud service
Set-AzureDeployment -Config -ServiceName "<cloud_service_name_goes_here>" `
-Configuration "D:/tmp/cloud/ServiceConfiguration.Cloud.cscfg" `
-Slot "Production"
For the the `-Configuration' parameter I have provided full local path to the new config file I want to use with my cloud service.
This is verified and working solution.
As astaykov says, you can't update a single cloud config value using Powershell.
But you can read all of the settings, update the one you wish to change, save it to a temp file, and then set all the settings again, like so:
UpdateCloudConfig.ps1:
param
(
[string] $cloudService,
[string] $publishSettings,
[string] $subscription,
[string] $role,
[string] $setting,
[string] $value
)
# param checking code removed for brevity
Import-AzurePublishSettingsFile $publishSettings -ErrorAction Stop | Out-Null
function SaveNewSettingInXmlFile($cloudService, [xml]$configuration, $setting, [string]$value)
{
# get the <Role name="Customer.Api"> or <Role name="Customer.NewsletterSubscription.Api"> or <Role name="Identity.Web"> element
$roleElement = $configuration.ServiceConfiguration.Role | ? { $_.name -eq $role }
if (-not($roleElement))
{
Throw "Could not find role $role in existing cloud config"
}
# get the existing AzureServiceBusQueueConfig.ConnectionString element
$settingElement = $roleElement.ConfigurationSettings.Setting | ? { $_.name -eq $setting }
if (-not($settingElement))
{
Throw "Could not find existing element in cloud config with name $setting"
}
if ($settingElement.value -eq $value)
{
Write-Host "No change detected, so will not update cloud config"
return $null
}
# update the value
$settingElement.value = $value
# write configuration out to a file
$filename = $cloudService + ".cscfg"
$configuration.Save("$pwd\$filename")
return $filename
}
Write-Host "Updating setting for $cloudService" -ForegroundColor Green
Select-AzureSubscription -SubscriptionName $subscription -ErrorAction Stop
# get the current settings from Azure
$deployment = Get-AzureDeployment $cloudService -ErrorAction Stop
# save settings with new value to a .cscfg file
$filename = SaveNewSettingInXmlFile $cloudService $deployment.Configuration $setting $value
if (-not($filename)) # there was no change to the cloud config so we can exit nicely
{
return
}
# change the settings in Azure
Set-AzureDeployment -Config -ServiceName $cloudService -Configuration "$pwd\$filename" -Slot Production
# clean up - delete .cscfg file
Remove-Item ("$pwd\$filename")
Write-Host "done"

Categories

Resources