I have the following script, but am getting an error -
Script -
$CNAMES = Get-Content "C:\Temp\alias.txt"
$Query = "Select * from MicrosoftDNS_CNAMEType"
$Record = Get-WmiObject -Namespace "root\microsoftdns" -Query $Query -ComputerName 10.10.10.1 | Where-Object{$_.Ownername -match $CNAME}
Foreach($CNAME in $CNAMES)
{
$Record.RecordData = "some.server.net"
$Record.put()
}
Error -
Property 'RecordData' cannot be found on this object; make sure it exists and is settable.
At C:\temp\DNSUpdateCNAMETarget_02.ps1:7 char:9
+ $Record. <<<< RecordData = "some.server.net"
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : PropertyAssignmentException
Method invocation failed because [System.Object[]] doesn't contain a method named 'put'.
At C:\temp\DNSUpdateCNAMETarget_02.ps1:8 char:12
+ $Record.put <<<< ()
+ CategoryInfo : InvalidOperation: (put:String) [], RuntimeException
+ FullyQualifiedErrorId : MethodNotFound
TIA
I didn't try (cause i don't have a MS-DNS at hand right now) but i'd suspect that you need
$Record.PSBase.Put()
to make it work.
EDIT:
As it looks $Record holds an array of System.Object so will have to cast it a suitable type to access .RecordData and .Put()
Your script queries for records of type MicrossoftDNS_CNAMEType which only support CreateInstanceFromPropertyData.
I would try sending you $Record to Get-Member
Get-WmiObject -Namespace "root\microsoftdns" -Query $Query -ComputerName 10.10.10.1 | Get-Member
to find out, what you are dealing with.
Related
I'm facing an issue of getting all vms configuration ( using Get-ScVirtualMachine command) into an array from an input file.
The code is this one below
$VmsList = Get-Content C:\VmsList.txt
foreach($vm in $VmsList){
$Result += Get-SCVirtualMachine -Name $vm
}
And I have this error
Method invocation failed because [Microsoft.SystemCenter.VirtualMachineManager.VM] does not contain a method named 'op_Addition'.
At line:3 char:1
$Result += Get-SCVirtualMachine -Name $vm
+ CategoryInfo : InvalidOperation: (op_Addition:String) [], RuntimeException
+ FullyQualifiedErrorId : MethodNotFound
Method invocation failed because [Microsoft.SystemCenter.VirtualMachineManager.VM] does not contain a method named 'op_Addition'.
At line:3 char:1
$Result += Get-SCVirtualMachine -Name $vm
+ CategoryInfo : InvalidOperation: (op_Addition:String) [], RuntimeException
+ FullyQualifiedErrorId : MethodNotFound
Get-SCVirtualMachine : Cannot validate argument on parameter 'Name'. The character length (0) of the argument is too short. Specify an argument with a length that
is greater than or equal to "1", and then try the command again.
At line:3 char:39
$Result += Get-SCVirtualMachine -Name $vm
~~~
CategoryInfo : InvalidData: (:) [Get-SCVirtualMachine], ParameterBindingValidationException
FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.SystemCenter.VirtualMachineManager.Cmdlets.GetVMCmdlet
I forgot to declare the array $result = #()
I resolved the issue.
I’m trying to convert some PowerShell code from using WMI to using CIM. I had a function which used Win32ShutdownTracker (https://msdn.microsoft.com/en-us/windows/desktop/aa394057) to reboot a system, with a timeout, comment, and reason for initiating the reboot. Using WMI I had to give the account running the reboot permissions using “psbase.Scope.Options.EnablePrivileges = $true” even though the account was already an administrator on the local system. I have not figured out how to give the same permissions using CIM and it seems without them, I’m unable to reboot the system. Also, the class binding does not seem to work. Any help would be greatly appreciated.
I've tried many combinations of CIM, including getting the object then invoking it and calling the class directly and none have worked.
WMI Code (Works without issue):
$OSObject = Get-WmiObject -Class Win32_OperatingSystem
$OSObject.psbase.Scope.Options.EnablePrivileges = $true
$OSObject.Win32ShutdownTracker(300,"This is a test",2147745794,6)
CIM Code I've tried (Does not work):
$OSObject = Get-CimInstance -Class Win32_OperatingSystem
$OSObject.psbase.Scope.Options.EnablePrivileges = $true
The property 'EnablePrivileges' cannot be found on this object. Verify that the property exists and can be set.
At line:1 char:1
+ $OSObject.psbase.Scope.Options.EnablePrivileges = $true
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : PropertyNotFound
Invoke-CimMethod -CimClass $OSObject -MethodName Win32ShutdownTracker –Arguments 300,"This is a test",21477
45794,6
Invoke-CimMethod : Cannot bind parameter 'CimClass'. Cannot convert the "Win32_OperatingSystem: Microsoft Windows
10 Enterprise" value of type "Microsoft.Management.Infrastructure.CimInstance#root/cimv2/Win32_OperatingSystem"
to type "Microsoft.Management.Infrastructure.CimClass".
At line:1 char:28
+ Invoke-CimMethod -CimClass $OSObject -MethodName Win32ShutdownTracker ...
+ ~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Invoke-CimMethod], ParameterBindingException
+ FullyQualifiedErrorId : CannotConvertArgumentNoMessage,Microsoft.Management.Infrastructure.CimCmdlets.Invok
eCimMethodCommand
Invoke-CimMethod -CimClass "Win32_OperatingSystem" -MethodName Win32ShutdownTracker –Arguments #{300,"This is a test",2147745794,6}
Invoke-CimMethod -CimClass "Win32_OperatingSystem" -MethodName Win32ShutdownTracker –Arguments #{300,"This
is a test",2147745794,6}
Invoke-CimMethod -CimClass "Win32_OperatingSystem" -MethodName "Win32ShutdownTracker" –Arguments 300,"This
is a test",2147745794,6
Invoke-CimMethod : Cannot bind parameter 'CimClass'. Cannot convert the "Win32_OperatingSystem" value of type
"System.String" to type "Microsoft.Management.Infrastructure.CimClass".
At line:1 char:28
+ Invoke-CimMethod -CimClass "Win32_OperatingSystem" -MethodName "Win32 ...
+ ~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Invoke-CimMethod], ParameterBindingException
+ FullyQualifiedErrorId : CannotConvertArgumentNoMessage,Microsoft.Management.Infrastructure.CimCmdlets.Invok
eCimMethodCommand
Invoke-CimMethod -CimClass "Win32_OperatingSystem" -MethodName Win32ShutdownTracker –Arguments 300,"This is
a test",2147745794,6
Invoke-CimMethod : Cannot bind parameter 'CimClass'. Cannot convert the "Win32_OperatingSystem" value of type
"System.String" to type "Microsoft.Management.Infrastructure.CimClass".
At line:1 char:28
+ Invoke-CimMethod -CimClass "Win32_OperatingSystem" -MethodName Win32S ...
+ ~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Invoke-CimMethod], ParameterBindingException
+ FullyQualifiedErrorId : CannotConvertArgumentNoMessage,Microsoft.Management.Infrastructure.CimCmdlets.Invok
eCimMethodCommand
(Invoke-CimMethod -CimClass 'Win32_OperatingSystem').Win32ShutdownTracker(300,"This is a test",2147745794,6
)
Invoke-CimMethod : Cannot bind parameter 'CimClass'. Cannot convert the "Win32_OperatingSystem" value of type
"System.String" to type "Microsoft.Management.Infrastructure.CimClass".
At line:1 char:29
+ (Invoke-CimMethod -CimClass 'Win32_OperatingSystem').Win32ShutdownTra ...
+ ~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Invoke-CimMethod], ParameterBindingException
+ FullyQualifiedErrorId : CannotConvertArgumentNoMessage,Microsoft.Management.Infrastructure.CimCmdlets.Invok
eCimMethodCommand
(Invoke-CimMethod -CimClass $OSObject).Win32ShutdownTracker(300,"This is a test",2147745794,6)
Invoke-CimMethod : Cannot bind parameter 'CimClass'. Cannot convert the "Win32_OperatingSystem: Microsoft Windows
10 Enterprise" value of type "Microsoft.Management.Infrastructure.CimInstance#root/cimv2/Win32_OperatingSystem"
to type "Microsoft.Management.Infrastructure.CimClass".
At line:1 char:29
+ (Invoke-CimMethod -CimClass $OSObject).Win32ShutdownTracker(300,"This ...
+ ~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Invoke-CimMethod], ParameterBindingException
+ FullyQualifiedErrorId : CannotConvertArgumentNoMessage,Microsoft.Management.Infrastructure.CimCmdlets.Invok
eCimMethodCommand
This works for me:
$arguments = #{
Timeout = [System.UInt32]300
Comment = 'This is a test'
ReasonCode = [System.UInt32]2147745794
Flags = 6
}
Invoke-CimMethod -Query 'SELECT * FROM Win32_OperatingSystem' -MethodName 'Win32ShutdownTracker' –Arguments $arguments
I've tried two ways to instantiate a class in Powershell v3:
$regex = New-Object -Type System.Text.RegularExpressions.Regex -ArgumentList '\/\/.*' | Get-Member
$regex::Replace("//hey", "")
And:
$netregex = [regex]::new('\/\/.*') | Get-Member
$nosingleline = $netregex::Replace("//hey", '')
The first way yields this:
Unable to cast object of type 'System.Object[]' to type 'System.Type'.
At line:2 char:1
$regex::Replace("//hey", "")
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
CategoryInfo : OperationStopped: (:) [], InvalidCastException
FullyQualifiedErrorId : System.InvalidCastException
The second way yields this:
Method invocation failed because
[System.Text.RegularExpressions.Regex] doesn't contain a method named
'new'. At line:4 char:1
$netregex = [regex]::new('//.*') | Get-Member
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
CategoryInfo : InvalidOperation: (:) [], RuntimeException
FullyQualifiedErrorId : MethodNotFound
Remove | Get-Member from both commands. It is changing the ultimate object type being output on those lines.
Also use . to access the method:
$netregex = [regex]::new('\/\/.*')
$nosingleline = $netregex.Replace("//hey", '')
$regex = New-Object -Type System.Text.RegularExpressions.Regex -ArgumentList '\/\/.*'
$regex.Replace("//hey", "")
It turned out that after migration to New Query Language in OMS also WebhookData structure for alert has changed.
I was trying to change my powershell script (which is called at OMS alert via Automation Account runbook) and it works locally for the Input I've copied for some previous (updated) alerts but I cannot get it to work in Automation Account.
Can anyone tell why this don't work in Runbook but works locally?
Here is my runbook input: https://jsonblob.com/adf5e1c2-c948-11e7-af9e-2d30dd548850
I took it from here:
Script:
$WebhookData = '{"WebhookName":"OMS Alert Remediation b64051e5-b9c5-44db-b74f-51d7cf5a9df2","RequestBody":"{\"WorkspaceId\":\"8547d992-7979-46d0-912b-8fffeabe1c8b\",\"AlertRuleName\":\"SRVR slow response - TEST\",\"SearchQuery\":\"ApplicationInsights | where TelemetryType == \\\"Request\\\" and Computer startswith_cs \\\"SRVR\\\" and Computer != \\\"SRVR-DEVEL\\\" | summarize AggregatedValue = avg(RequestDuration) by bin_at(TimeGenerated, 4m, datetime(2017-11-12T10:32:00.0000000)), Computer | sort by TimeGenerated desc\",\"SearchResult\":{\"tables\":[{\"name\":\"PrimaryResult\",\"columns\":[{\"name\":\"TimeGenerated\",\"type\":\"datetime\"},{\"name\":\"Computer\",\"type\":\"string\"},{\"name\":\"AggregatedValue\",\"type\":\"real\"}],\"rows\":[[\"2017-11-12T10:28:00Z\",\"SRVR-06\",1535.2852333333333],[\"2017-11-12T10:24:00Z\",\"SRVR-06\",718.91287857142856]]}]},\"SearchIntervalStartTimeUtc\":\"2017-11-12T10:27:00Z\",\"SearchIntervalEndtimeUtc\":\"2017-11-12T10:32:00Z\",\"AlertThresholdOperator\":\"Greater Than\",\"AlertThresholdValue\":700,\"ResultCount\":2,\"SearchIntervalInSeconds\":300,\"LinkToSearchResults\":\"https://8547d992-7979-46d0-912b-8fffeabe1c8b.portal.mms.microsoft.com/#Workspace/search/index?_timeInterval.intervalEnd=2017-11-12T10%3a32%3a00.0000000Z&_timeInterval.intervalDuration=300&q=ApplicationInsights%20%20%7C%20where%20TelemetryType%20%3D%3D%20%5C%22Request%5C%22%20and%20Computer%20startswith_cs%20%5C%22SRVR%5C%22%20and%20Computer%20!%3D%20%5C%22SRVR-DEVEL%5C%22%20%20%7C%20summarize%20AggregatedValue%20%3D%20avg(RequestDuration)%20by%20bin_at(TimeGenerated%2C%204m%2C%20datetime(2017-11-12T10%3A32%3A00.0000000))%2C%20Computer%20%20%7C%20sort%20by%20TimeGenerated%20desc\",\"Description\":\"W runbook-u testujemy powershell workflow, zamiast powershel script \",\"Severity\":\"Critical\"}","RequestHeader":{"Connection":"Keep-Alive","Accept":"application/json","Host":"s2events.azure-automation.net","User-Agent":"OMS-Remediation","x-ms-request-id":"9be297e0-c196-45c0-ad23-3b513e165648"}}'
$Input = ConvertFrom-Json $WebhookData
$RequestBody = ConvertFrom-Json -InputObject $Input.RequestBody
$Computers = New-Object -TypeName System.Collections.ArrayList
foreach($row in $RequestBody.SearchResult.tables[0].rows)
{
$Computers.Add($row[1]) > $null
}
foreach ($Computer in $Computers | Get-Unique)
{
'Computer: ' + $Computer
Invoke-Command -Credential $c -ComputerName $Computer -ScriptBlock {
$date = Get-Date | Out-File -Append 'C:\tmp\test_log.txt'
}
}
And those are errors in Azure Portal:
1.
ConvertFrom-Json : Invalid JSON primitive: .
At line:9 char:10
+ $Input = ConvertFrom-Json $WebhookData
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [ConvertFrom-Json], ArgumentException
+ FullyQualifiedErrorId : System.ArgumentException,Microsoft.PowerShell.Commands.ConvertFromJsonCommand
2.
ConvertFrom-Json : Cannot bind argument to parameter 'InputObject' because it is null.
At line:10 char:46
+ $RequestBody = ConvertFrom-Json -InputObject $Input.RequestBody
+ ~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidData: (:) [ConvertFrom-Json], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.ConvertFromJs
onCommand
3.
Cannot index into a null array.
At line:14 char:17
+ foreach($row in $RequestBody.SearchResult.tables[0].rows)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : NullArray
As you noticed the query language has changed. We have published a new sample here on how to parse results from the new language.
Look here:
https://learn.microsoft.com/en-us/azure/log-analytics/log-analytics-alerts-actions#webhook-actions
Have a look at the new sample and see if you can use that to parse the records.
Thanks,
Anirudh
I want to execute below code in the either local or remote machine whith current user.
$BackUpSqlAgentAndRemoveOldbackup = {
param([string]$AppServer,[string]$SqlInstance,[string]$BackupShare,[string]$alias)
[Environment]::UserName #I got same user name in all cases.
[System.Reflection.Assembly]::LoadWithPartialName('Microsoft.SqlServer.Smo') | Out-Null
$server = New-Object ('Microsoft.SqlServer.Management.Smo.Server') $SqlInstance
$backupName = 'SqlAgentJob_' + $SqlInstance + '_' + (Get-Date –format ‘yyyyMMdd_HHmm’) + '_' + $alias + '.sql'
$backupPath = join-path $BackupShare $backupName
$oldBackups = Get-ChildItem $backupShare | where { ( $_.name -like 'SqlAgentJob_*.sql' ) }
$server.JobServer.Jobs.Script() | Out-File -filepath $backupPath
foreach ( $item in $oldBackups ) { remove-item $item.fullName }
}
the #argList is
#('hafcapp-1', 'hafcsql-1', '\\Host5FileSrv\Backup\test','auto')
I notice that
this one, it works well (no -comupterName and -session)
Invoke-Command -ScriptBlock $BackUpSqlAgentAndRemoveOldbackup -argumentList $argList
this one, it throw execption (I also tried "-session", get same result)
Invoke-Command -computerName localhost -ScriptBlock $BackUpSqlAgentAndRemoveOldbackup -argumentList $argList
the exception is as below, it seems the it can not access the folder.
Cannot find path '\\Host5FileSrv\Backup\test' because it does not exist.
+ CategoryInfo : ObjectNotFound: (\\Host5FileSrv\Backup\test:String) [Get-ChildItem], ItemNotFoundException
+ FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.GetChildItemCommand
You cannot call a method on a null-valued expression.
+ CategoryInfo : InvalidOperation: (Script:String) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
Cannot bind argument to parameter 'Path' because it is null.
+ CategoryInfo : InvalidData: (:) [Remove-Item], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.RemoveItemCommand
does anyone know how can I do if I want to add computerName or session?
(notes:[Environment]::UserName return identical user)
You have run into the double hop problem. Your credentials can be transferred to the next machine (first hop), but no further (second hop). This means that you can't use the credentials of the machine where you are executing Invoke-Command on, the remote machine (localhost) to connect to a file share (\Host5FileSrv\Backup). Even if you use localhost as computername, it is still remoting. A solution could be CredSSP. See here and here for more information.
This looks like a "second hop" remoting problem, and you'll need to configure WinRM on the computers involved to use CredSSP
http://msdn.microsoft.com/en-us/library/windows/desktop/ee309365(v=vs.85).aspx