my current tasks is to set up an automatic configuration for Microsoft Azure Backup.
What i did so far:
wrote scripts and tasks that copy the Installer to a remote server, execute it, make sure it's installed, register the server with Azure, set up the schedule, the file specs and everything around it.
And it all works.
The problem though: I have now recieved the task to also include "System State" within the backup.
I'm aware, that this is about a 60 second task, if you do it using the Azure Console to schedule the backup. I do however have the requirement to build the script in a way, that not a single finger has to be moved to complete the whole thing.
Question: Has anyone figured out, if it's possible to activate and include the System State Backups ( which ends up under %MARSDIR%\Scratch\SSBS ) within the OBPolicy using only powershell?
If i activate it with the console and then execute the command "Get-OBPolicy" i find the System State listed along the other filespecs.
However i can't figure out how i would set it, using New-OBFileSpec or anything alike.
Thanks in advance :)
Edit: To clarify
Assume i'm in the config window seeing this:
I can "check" C: by doing
"New-OBFileSpec -FileSpec #("C:\")"
What command should i use in PS to "check" System State ?
Edit 2:
Below is the part of the code for this.
How do i add System State to the $inclusions?
## Register Server with Azure
$credsfile = ## Path to Vault credential file
Start-OBRegistration -VaultCredentials $credsfile -Confirm:$false
# Create Policy
$newpolicy = New-OBPolicy
$sched = New-OBSchedule -DaysofWeek Monday,Tuesday,Wednesday,Thursday,Friday,Saturday,Sunday -TimesofDay 22:00
Set-OBSchedule -Policy $newpolicy -Schedule $sched
# File Spec
$inclusions = New-OBFileSpec -FileSpec #("E:\")
Add-OBFileSpec -Policy $newpolicy -FileSpec $inclusions
# Retention
$retentionpolicy = New-OBRetentionPolicy -RetentionDays 30
Set-OBRetentionPolicy -Policy $newpolicy -RetentionPolicy $retentionpolicy
## Set the Policy
Set-OBPolicy -Policy $newpolicy -Confirm:$false
# Set Machine Encryption Key
$PassPhrase = ConvertTo-SecureString -String "...." -AsPlainText -Force
Set-OBMachineSetting -EncryptionPassPhrase $PassPhrase
Related
az .\-u
I accidentally run this command and the cli started some work then I pressed ctrl-c to terminate it but I'm afraid something has been already done. How to check if something changed?
I've checked the cli reference, but couldn't find a similar command.
As there is no such command in Az, even though I entered the same as you, I received an error as shown:
If you want to check your activities for any changes, there are couple of ways:
Check the Log Activity: To check your log activity, use below PowerShell command: (default activity status exists for 90 days)
Get-AzActivityLog -StartTime 2022-11-01T10:30 -EndTime 2022- 11-14T11:30
Note: According to your requirements, you can obtain logs across resource group by applying start time, and end time parameters.
To check for any specific changes held in resources, use below query with "Azcli" command
Search-AzGraph -Query 'resourcechanges | extend changeTime=todatetime(properties.changeAttributes.timestamp) | project changeTime, properties.changeType, properties.targetResourceId, properties.targetResourceType, properties.changes | order by changeTime desc'
Received Output also includes a changetime attribute:
Through Azure portal, Activity logs can also be checked using path: Monitor -> Activity Log
Reference: MSDoc
I'm brand new to automation, and pretty new to Powershell as well, so I'm hoping this is a simple fix. :)
I'm trying to get some code to run. And for all I know, it does run, but the test pane doesn't show anything. Based on this thread: Azure powershell runbook don't show any output, I did try republishing the code and clearing my browser cache, but that didn't help in my case, so I'm thinking there's an issue with the code?
Here's my (genericized) code):
workflow DB_DailyTasks
{
Write-Output "Code starting"
inlinescript
{
[string] $SqlServerName = "myDb.database.windows.net"
$Credential = Get-AutomationPSCredential -Name "myDatabase-automation"
# Setup credentials
$ServerName = $Using:SqlServerName
$UserId = $Using:Credential.UserName
$Password = ($Using:Credential).GetNetworkCredential().Password
# Execute the udp_myProc procedure
# Create connection for each individual database
$DatabaseConnection = New-Object System.Data.SqlClient.SqlConnection
$DatabaseCommand = New-Object System.Data.SqlClient.SqlCommand
Write-Output "ConnectionState is: $(DatabaseConnection.State)"
$DbName = "myDb"
# Setup connection string for $DbName
$DatabaseConnection.ConnectionString = "Server=$ServerName; Database=$DbName; User ID=$UserId; Password=$Password;"
$DatabaseConnection.Open();
Write-Output "ConnectionState is: $(DatabaseConnection.State)"
# Create command for a specific database $DBName
$DatabaseCommand.Connection = $DatabaseConnection
Write-Output "Running udp_myProc procedure"
$DatabaseCommand.CommandText = "EXECUTE [dbo].[udp_myProc]"
$NonQueryResult = $DatabaseCommand.ExecuteNonQuery()
# Close connection to $DbName
$DatabaseConnection.Close()
}
}
...and here's what I see in the test pane when I try to test:
...which isn't terribly helpful in knowing whether it actually ran.
Thanks in advance for any help you can provide! :)
[Edit] The code is definitely not running. The stored procedure inserts an entry into a history table, and there's no record of it running either for the tests or for when I ran the published output.
Interesting note, though - when I ran the published output, there were no errors and no warnings, but it did say, "This job does not have any output" in the Output tab.
[Edit #2]: It doesn't write anything on my local computer either??
[Edit #3]: Replaced Write-Output with Write-Host inside the inlinescript block. No change, either on Azure admin console or on my local computer.
My guess is that you created a PowerShell runbook, not a PowerShell Workflow runbook. If this is correct, then your runbook code declares a workflow called DB_DailyTasks, but never invokes it. For example, you could declare a function, but would not expect it to be automatically invoked because of that.
Unless you are certain that you need a workflow, not a regular PowersShell runbook, I would recommend removing workflow and InlineScript from your code, and deal with regular PowerShell.
However, if you really need it to be a workflow (not recommended unless you have to use checkpoints and things like parallel and foreach -parallel), then create a runbook of the "PowerShell Workflow" type: it treats the workflow keyword differently, so your code would be correct.
11/13/2013 11:35:37 TRCW1 using local computer 11/13/2013 11:35:37
TRCE1 System.Management.ManagementException: Access denied at
System.Management.ManagementException.ThrowWithExtendedInfo(ManagementStatus
errorCode) at
System.Management.ManagementObjectCollection.ManagementObjectEnumerator.MoveNext()
at Microsoft.PowerShell.Commands.GetWmiObjectCommand.BeginProcessing()
Code (inside a loop of server names):
$error.clear() #clear any prior errors, otherwise same error may repeat over-and-over in trace
if ($LocalServerName -eq $line.ServerName)
{
# see if not using -ComputerName on local computer avoids the "service not found" error
Add-Content $TraceFilename "$myDate TRCW1 using local computer "
$Service = (get-wmiobject win32_service -filter "name = '$($line.ServiceName)'")
}
else
{
Add-Content $TraceFilename "$myDate TRCW2 using remote computer $($line.ServerName) not eq $LocalServerName"
$Service = (get-wmiobject win32_service -ComputerName $line.ServerName -filter "name = '$($line.ServiceName)'")
}
if ($error -ne $null)
{
Write-Host "----> $($error[0].Exception) "
Add-Content $TraceFilename "$myDate TRCE1 $($error[0].Exception)"
}
I'm reading a CSV of server names. I finally added the exception logic, to find I'm getting an "Access Denied". This was only happening on the local server. Seems almost backwards, the local server fails, whereas the remote servers work fine. I even changed logic to test to see if it was the local server, then tried leaving off the -ComputerName parms on the WMI (as shown in code above), and still getting error.
So far, my research shows the answer may lie with
set-item trustedhosts
But my main question is whether trustedhosts is applicable to local servers, or only remote servers. Wouldn't a computer always trust itself? Does it still use remoting to talk to itself?
This server apparently was part of a cluster a long time before I got here, and now it's not. I'm also suspicious of that.
When I run interactively the script works fine, it's only when I schedule it and run it under a service account that it fails with the access denied. The Service Account is local Admin on that box.
I'm using get-wmiobject win32_service instead of get-service because it returns extra info I need to lookup the process, and date/time the service was started using another WMI call.
Running on Win 2008/R2.
Below Update 11/13/2013 5:27Pm
I have just verified that the problem happens on more than one server. [I took the scripts and ran them on another server.] My CSV input includes a list of servers to monitor. The ones outside of my own server always return results. The ones to my own server, that omit the -ComputerName fail. (I have tried with and without the -ComputerName parm for the local server).
Are you running the script "as administrator" (UAC)? When your credentials are calculated for your local instance if you have UAC enabled and you didn't run it "as administrator" it removes the local administrator security token. Connecting to a different machine over the network, A) it completely bypasses UAC, and B) when the target evaluates your token, the group memberships you're in are fully evaluated and thus you get "administrator" access.
Probably unrelated, but I've just run across two 2008 R2 servers out of 10 on my system that reject THE FIRST performance criteria that I'm collecting, but only when it's running as a scheduled task. If I run it interactively it works at least 95% of the time. I'm collecting Disk Seconds/Read and Seconds/Write, so it's the reads that don't show, for these two servers only. I flipped the order and what do you know, the Writes don't report. I just added one drive Seconds/Transfer as a sacrificial lamb to the start of my criteria list, and VOILA now I don't get ACCESS DENIED to the reads and writes.
$counterlist = #("\$server\PhysicalDisk(0*)\Avg. Disk sec/Transfer",
"\$server\PhysicalDisk()\Avg. Disk sec/Read",
"\$server\PhysicalDisk()\Avg. Disk sec/Write")
$counters = $counterlist | Get-Counter
(not sure how to edit this, but there are asterisks in between the parenthesis after physicaldisk...)
Like many people, we have Azure VMs that we want to destroy when not in use so that we don't have to pay for their core usage. All of the VMs in question are on the same domain and the DC/DNS server is never destroyed/recreated and has a static IP. After successfully using a combination of Export/Remove/Import-AzureVM, however, all of the IP settings for the network adapter (DNS is my primary concern) are gone because a new network adapter is created each time I reconstruct the VM using Import-AzureVM.
I initially tried using NETSH to set my DNS entry at startup, but it depends on knowing the name of the adapter and the adapter name changes daily (since we're taking the machines down for the evening and recreating them in the morning). My next not-so-brilliant idea was to include a VBScript that renamed the adapter to the same name on startup so that NETSH would always have the same adapter name to deal with. However, it was at that point that I discovered that all of the old adapters still exist, but are simply hidden and not in use, rendering my plan moot.
Here are the test NETSH command and VBScript I was attempting to use, just for the sake of reference:
'this script was modified from one i got from the Scripting Guys
Const NETWORK_CONNECTIONS = &H31&
Set objShell = CreateObject("Shell.Application")
Set objFolder = objShell.Namespace(NETWORK_CONNECTIONS)
Set colItems = objFolder.Items
For Each objItem in colItems
'only one adapter is ever returned by this query, but it didn't seem like a bad idea to leave the loop alone just in case
objItem.Name = "testlan"
wscript.echo objItem.Name
Next
NETSH
netsh interface ip add dns name="testlan" 10.0.0.4
I know I can't be the only person trying to solve this issue, but I've been unable to find the solution through a significant amount of Googling and trial and error on my part. Many thanks!
Ben
#Nathan's comment is incorrect. When a VM is "Stopped" it is still being billed. If it is "Stopped(Deallocated)" however then the billing stops. From Azure's Pricing Details FAQ:
To ensure that you are not billed, stop the VM from the management
portal. You can also stop the VM through Powershell by calling
ShutdowRoleOperation with 'PostShutdownAction' equal to
"StoppedDeallocated". However, you will continue to be billed if you
shut down a VM from inside (e.g. using power options in Windows) or
through PowerShell by calling ShutdownRoleOperation with
'PostShutdownAction' equal to "Stopped".
Instead of destroying the VM, you can get to the deallocated state using the azure control panel, or use Azure Cmdlets to force stop the VM. This will deallocate and you wont have the networking problems. Unfortunately this cant be done currently with the REST Api.
I use the following in an app to stop the service:
RunPowerShellScript(#"Stop-AzureVM -ServiceName " + cloudServiceName + " -Name " + vmName + " -Force");
Use that line in on a button, or use the REST api to query your cloud services, then the following function to run your powershell. Be sure to run the getting started initially.
private string RunPowerShellScript(string scriptText)
{
// create Powershell runspace
Runspace runspace = RunspaceFactory.CreateRunspace();
// open it
runspace.Open();
// create a pipeline and feed it the script text
Pipeline pipeline = runspace.CreatePipeline();
pipeline.Commands.AddScript(scriptText);
// add an extra command to transform the script
// output objects into nicely formatted strings
// remove this line to get the actual objects
// that the script returns. For example, the script
// "Get-Process" returns a collection
// of System.Diagnostics.Process instances.
pipeline.Commands.Add("Out-String");
// execute the script
Collection<PSObject> results = pipeline.Invoke();
// close the runspace
runspace.Close();
// convert the script result into a single string
StringBuilder stringBuilder = new StringBuilder();
foreach (PSObject obj in results)
{
stringBuilder.AppendLine(obj.ToString());
}
return stringBuilder.ToString();
}
Try this...
Set-ExecutionPolicy Unrestricted
$wmi = Get-WmiObject win32_networkadapterconfiguration -filter "ipenabled = 'true'"
$wmi.SetDNSServerSearchOrder("10.0.2.6")
I'm building a script to read the Security Log from several computers. I can read the Security log from my local machine with no problem when using the Get-EventLog command, but the problem with it is that I can't run it against a remote machine (the script is for powershell v1). The command below never returns any results, although that with any other LogFile, it works perfectly:
gwmi -Class Win32_NTLogEvent | where {$_.LogFile -eq "Security"}
I've done some research, and I seems to be a impersonation issue, but the -Impersonation option for the Get-WmiObject does not seem to be implemented. Is there anyway around this problem? The solution could be running the Get-EventLog on a remote machine somehow, or dealing with the impersonation issue so that the security log can be accessed.
Thanks
You could use .NET directly instead of going through WMI. The scriptblock below will give you the first entry in the security log
$logs = [System.Diagnostics.EventLog]::GetEventLogs('computername')
$security = $logs | ? {$_.log -like 'Security'}
$security.entries[0]
Have you tried to use the -Credential parameter? Also, use the filter parameter instead of where-object, it gets just the security events (where-object gets ALL events from all logs and only then performs the filtering)
gwmi Win32_NTLogEvent -filter "LogFile='Security'" -computer comp1,comp2 -credential domain\user