I am trying to write Powershell script for Azure Service Bus Topic Creation. I have similar code in C# which works but now I want to transform it to Powershell script. But right now I am stuck on how to convert following line to Powershell:
AuthorizationRule Ar = new SharedAccessAuthorizationRule("PublisherOwner", "SASKEY++++++++++++++++++++++", new[] { AccessRights.Listen, AccessRights.Send });
I am trying it like this, but it isn't working:
$PublisherRule = New-Object -TypeName Microsoft.ServiceBus.Messaging.SharedAccessAuthorizationRule -ArgumentList "PublisherOwner", $PublisherKey
Here is the Error
New-Object : Cannot find type [Microsoft.ServiceBus.Messaging.SharedAccessAuthorizationRule]: make sure the
assembly containing this type is loaded.
At line:1 char:28
+ $PublisherRule = New-Object <<<< -TypeName Microsoft.ServiceBus.Messaging.SharedAccessAuthorizationRule -
ArgumentList "PublisherOwner", $PublisherKey
+ CategoryInfo : InvalidType: (:) [New-Object], PSArgumentException
+ FullyQualifiedErrorId : TypeNotFound,Microsoft.PowerShell.Commands.NewObjectCommand
You can use the array sub-expression operator #() to pass an array as an argument to -ArgumentList:
$PublisherRule = New-Object -TypeName Microsoft.ServiceBus.Messaging.SharedAccessAuthorizationRule -ArgumentList "PublisherOwner", $PublisherKey,#([Microsoft.ServiceBus.Messaging.AccessRights]::Listen,[Microsoft.ServiceBus.Messaging.AccessRights]::Send)
Third parameter the array needs to be a strongly typed array. The converted script is as below and it worked:
[Microsoft.ServiceBus.Messaging.AccessRights[]]$PublisherRights =
New-Object -TypeName "System.Collections.Generic.List[Microsoft.ServiceBus.Messaging.AccessRights]" ;
$PublisherRights += [Microsoft.ServiceBus.Messaging.AccessRights]::Listen;
$PublisherRights += [Microsoft.ServiceBus.Messaging.AccessRights]::Send;
$Rule = New-Object -TypeName Microsoft.ServiceBus.Messaging.SharedAccessAuthorizationRule -ArgumentList "PublisherRule", "SASKEY", $PublisherRights;
Related
I can't seem to get the New-Object function in Powershell 2.0 to use the correct constructor for the type XmlMessageFormatter.
The MS documentation for XmlMessageFormatter is here: https://learn.microsoft.com/en-us/dotnet/api/system.messaging.xmlmessageformatter.-ctor?view=netframework-4.8#System_Messaging_XmlMessageFormatter__ctor_System_Type___
I want to use the constructor that takes an array of types:
XmlMessageFormatter(Type[] targetTypes);
My powershell script looks like this:
[System.Reflection.Assembly]::LoadWithPartialName("System.Messaging")
$queue = New-Object System.Messaging.MessageQueue $queuePath
[Type[]]$types = [MyNamespace.MyClass1], [MyNamespace.MyClass2], [MyNamespace.MyClass3]
$queue.Formatter = New-Object System.Messaging.XmlMessageFormatter($types);
To re-create the issue you can probably use this code:
[System.Reflection.Assembly]::LoadWithPartialName("System.Messaging")
[Type[]]$types = [System.String], [System.Int], [System.Messaging.MessageQueue]
$formatter = New-Object System.Messaging.XmlMessageFormatter($types);
I was reading about arrays in PowerShell here: https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_arrays?view=powershell-7
The error message seems to think I am sending multiple arguments rather than a single argument of an array:
New-Object : Cannot find an overload for "XmlMessageFormatter" and the argument count: "3".
At C:\temp\test.ps1:20 char:20
+ $queue.Formatter = New-Object System.Messaging.XmlMessageFormatter($types);
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [New-Object], MethodException
+ FullyQualifiedErrorId : ConstructorInvokedThrowException,Microsoft.PowerShell.Commands.NewObjectCommand
PowerShell assumes that you're passing it an array of 3 individual parameter arguments for the XmlMessageFormatter constructor, hence the ... with the argument count: "3". part of the error message.
Use the , unary array operator to wrap the $types array in yet another array, so that PowerShell will treat $types as a single parameter argument when invoking the constructor:
New-Object System.Messaging.XmlMessageFormatter (,$types)
How to create a char array of length $Count in powershell?
PS C:\Users\Administrator> $Count
415
PS C:\Users\Administrator> $chars = New-Object System.Char ($Count)
New-Object : Constructor not found. Cannot find an appropriate constructor for type System.Char.
At line:1 char:10
+ $chars = New-Object System.Char ($Count)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (:) [New-Object], PSArgumentException
+ FullyQualifiedErrorId : CannotFindAppropriateCtor,Microsoft.PowerShell.Commands.NewObjectCommand
I tried
[Char[]] $chars = #(415)
I had a class which needed a char array, but I basically I found a solution to my problem by using Strings. But I just wanted to ask if any one knows how to create an empty char array of variable length.
Eg: How do I do this in powershell? C# -> var chars = new Char[Count];
In PowerShell 5.0, you can use the new() constructor method:
PS C:\> $Count = 415
PS C:\> $chars = [char[]]::new($Count)
PS C:\> $chars.Count
415
In earlier versions, use the New-Object cmdlet, and indicate that you want an array with []:
$chars = New-Object -TypeName 'char[]' -ArgumentList $Count
Error I'm getting from PowerShell:
Cannot convert argument "srv", with value: "[DBADEV\SQL2008r2]", for "SqlBackup" to type "Microsoft.SqlServer.Management.Smo.Server": "Cannot convert the "[DBADEV\SQL2008r2]" value of type
"Microsoft.SqlServer.Management.Smo.Server" to type "Microsoft.SqlServer.Management.Smo.Server"."
At line:23 char:1
+ $backup.SqlBackup($srv)
+ ~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], ParentContainsErrorRecordException
+ FullyQualifiedErrorId : MethodArgumentConversionInvalidCastArgument
I'm attempting to write a PowerShell script to restore a database from our Production box and into our DBADEV box. Below is the code I'm using which is then producing the error.
#Clear Screen
cls
#load assemblies
[System.Reflection.Assembly]::LoadWithPartialName('Microsoft.SqlServer.SMO') | out-null
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.SmoExtended") | Out-Null
$ErrorActionPreference = "Inquire"
# Restore [SQLSRV2k8-0102\SQL2008] instance
$BackupFile = Get-ChildItem "\\NetworkShare\r`$\MSSQL10.SQL2008\MSSQL\Backup\AdventureWorks2008r2" | select -Last 1
$BackupFile
$srv = New-Object Microsoft.SqlServer.Management.Smo.Server("DBADEV\SQL2008r2")
$res = New-Object Microsoft.SqlServer.Management.Smo.Restore
$backup = New-Object Microsoft.SqlServer.Management.Smo.Backup
$Backup.Devices.AddDevice($BackupFile, [Microsoft.SqlServer.Management.Smo.DeviceType]::File)
$Backup.Database = "AdventureWorks2008r2"
$Backup.Action = [Microsoft.SqlServer.Management.Smo.BackupActionType]::Database
$backup.Initialize = $true
$backup.SqlBackup($srv)
$srv.Databases["AdventureWorks2008r2"].Drop()
$res.Devices.AddDevice($BackupFile, [Microsoft.SqlServer.Management.Smo.DeviceType]::File)
$res.Database = "AdventureWorks2008r2"
$res.NoRecovery = $true
$res.SqlRestore($srv)
The error seems a bit cryptic to me (as do most PowerShell errors). Any thoughts on why this is occurring? I'm also getting the error when I use Mike Fal's powershell script here: http://www.mikefal.net/2014/07/22/restoreautomation-powershell-module/
The one thing that seems to get me past this error is by passing "DBADEV\SQL2008r2" directly into SQLRestore,
i.e. $res.SqlRestore("DBADEV\SQL2008r2") instead of $res.SqlRestore($srv)
This now generate an error stating "Restore failed for Server 'DBADEV\SQL2008r2'
Well from my experiences this kind of errors appear because of wrong name/data type in variable.
I would try to escape \ in "DBADEV\SQL2008r2"
or try what I found on MSDN
$srv = new-Object Microsoft.SqlServer.Management.Smo.Server("(local)")
Write-Host $srv.Information.Version
so it could look like
New-Object Microsoft.SqlServer.Management.Smo.Server("(DBADEV\SQL2008r2)")
I'm attempting to author a PowerShell script that simply executes a stored proc from my administration database but am running into this:
New-Object : A positional parameter cannot be found that accepts argument 'System.Data.SqlClient.SqlDataReader'.
At C:\Scripts\Deployment\SPROCTest.ps1:19 char:15
+ $reader = New-Object -TypeName System.Data.SqlClient.SqlDataReader = $GetEn ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [New-Object], ParameterBindingException
+ FullyQualifiedErrorId : PositionalParameterNotFound,Microsoft.PowerShell.Commands.NewObjectCommand
Code would seem to be pretty straight forward like this:
$connection = New-Object -TypeName System.Data.SqlClient.SqlConnection
$connection.ConnectionString = "Server=bhbrf95xva.database.windows.net;Database=MY.DATABASE;Integrated Security=False;User=theuser;Password=xxx^xxx"
$connection.Open()
$GetEnvironment = New-Object System.Data.SqlClient.SqlCommand
$GetEnvironment.CommandText = "Select_Environment_ByEnvironmentName"
$GetEnvironment.CommandType = [System.Data.CommandType]::StoredProcedure
$GetEnvironment.Connection = $connection
$ParamGetEnvironment = New-Object -TypeName System.Data.SqlClient.SqlParameter
$ParamGetEnvironment.ParameterName = "#EnvironmentName"
$ParamGetEnvironment.SqlDbType = [System.Data.SqlDbType]::VarChar
$ParamGetEnvironment.Direction = [System.Data.ParameterDirection]::Input
$ParamGetEnvironment.Value = 'TheValue'
$GetEnvironment.Parameters.Add($ParamGetEnvironment)
$reader = New-Object -TypeName System.Data.SqlClient.SqlDataReader = $GetEnvironment.ExecuteReader()
$connection.Close()
I'm not too concerned (yet) with the actual format of this script, I'm just trying to get it to work first, but I'm wondering why and how I get this to recognize System.Data.SqlClient.SqlDataReader?
Do I need to add a plugin?
An SqlDataReader cannot be intialized by you. Infact, if you look at the documentation of SqlDataReader you will find that there is no public constructor for it.
You get an SqlDataReader only as return value from a call to an SqlCommand.ExecuteReader.
You just need to write
$reader = $GetEnvironment.ExecuteReader()
Also, keep in mind that, closing the connection used by the SqlDataReader effectively cripples the ability of the reader to read data from the database. So, if you plan to make something useful with the reader, don't close the connection until you have finished to read data.
I'm trying to create a new server audit on a WinServer 2008 R2 with the following PowerShell Script.
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.SMO") | out-null
$server = "SM1111" #change to desired instance
$instance = "S111"
$auditName = "$instance"+"TestAudit"
$auditDir = 'F:\Microsoft SQL Server\'+$instance+'AuditTestLogsNew\'
$srv = new-Object ('Microsoft.SqlServer.Management.Smo.Server') -argumentlist $instance
$newAudit = New-Object Microsoft.SqlServer.Management.Smo.Audit($srv, "$auditName")
$newAudit.DestinationType = [Microsoft.SqlServer.Management.Smo.AuditDestinationType]::File
$newAudit.FilePath = $auditDir
$newAudit.MaximumRolloverFiles = 10
$newAudit.MaximumFileSize = 100
$newAudit.QueueDelay = 1000
$newAudit.Create()
$newAudit.Enable()
However the following line always fails:
$newAudit = New-Object Microsoft.SqlServer.Management.Smo.Audit($srv, "$auditName")
I get the following error message:
New-Object : Exception calling ".ctor" with "2" argument(s): "SetParent failed for Audit 'S111TestAudit'. "
At MYFOLDER\Documents\Auditing_Test\CreateAudit.ps1:9 char:13
+ $newAudit = New-Object Microsoft.SqlServer.Management.Smo.Audit($srv, "$auditNam ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [New-Object], MethodInvocationException
+ FullyQualifiedErrorId : ConstructorInvokedThrowException,Microsoft.PowerShell.Commands.NewObjectCommand
I've been googling a lot, but still haven't found anything that might solve the problem, since I don't quite understand what raises the error to begin with.
I have full administrator privileges.
Any help would be appreciated!
You are missing the server name for your instance. Your variable $srv is not pointing to an actual server instance.
$server = "SM1111" #change to desired instance <- This isn't doing anything
$instance = "S111"
$srv = New-Object Microsoft.SqlServer.Management.Smo.Server -argumentlist "$server\$instance"