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
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)
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;
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 was wondering if anyone could help me out with an error I am getting in PowerShell. I am having no issue with creating the encryptor shown below:
$Crypto = New-Object System.Security.Cryptography.RNGCryptoServiceProvider
$IV = New-Object System.Byte[] 16
$Crypto.GetNonZeroBytes($iv)
$RIJSym = new-Object System.Security.Cryptography.RijndaelManaged
[byte[]] $Key = ('mysecret$%#').ToCharArray()
$Encryptor = $RIJSym.CreateEncryptor($Key,$IV)
But for what ever reason I am having an issue when I want to decrypt my key, here is what I am using and the error I get when the Program runs:
$Decrypted = $RIJSym.CreateDecryptor($Encryptor)
Error Message
Cannot find an overload for "CreateDecryptor" and the argument count: "1".
At line:15 char:1
+ $DeCryp = $rijSym.CreateDecryptor($encryptor)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodException
+ FullyQualifiedErrorId : MethodCountCouldNotFindBest
The error says it all... CreateDecryptor() doesn't have an overload the uses onl a single argument. The valid overloads are:
PS > $RIJSym.CreateDecryptor
OverloadDefinitions
-------------------
System.Security.Cryptography.ICryptoTransform CreateDecryptor(byte[] rgbKey, byte[] rgbIV)
System.Security.Cryptography.ICryptoTransform CreateDecryptor()
You need to create the decryptor the same way you created the encrypter: by specifying the key and IV. Ex.
$Decrypted = $RIJSym.CreateDecryptor($Key, $IV)
I am creating a new object for export values to CSV:
New-Object -TypeName PSObject -Property #{
host_name = ($server.name).ToLower()
address = $IPAddress
host_is_collector = "no"
host-preset = "windows-server"
} | Select-Object host_name,address,host-preset | Export-Csv -Path $nConf_import_host_file
The problem is that one of the lines contains a dash (host-preset). I would ofcourse simply change it to an underscore, but my CSV needs this value to be a dash. I could also do a -replace on the entire csv after it has been created but that seems dirty.
Is there a way I can use dash here?
My error msg is:
Missing '=' operator after key in hash literal.
At Z:\Scripts\Testscripts\ScanServers_and_check_nagiosV7.ps1:336 char:16
+ host-preset <<<< = "windows-server"
+ CategoryInfo : ParserError: (:) [], ParseException
+ FullyQualifiedErrorId : MissingEqualsInHashLiteral
You simply need to treat the host-preset property name as a string by enclosing it in quotes:
New-Object -TypeName PSObject -Property #{ "host-preset" = "windows-server" }