Using CreateDecryotor() in PowerShell - powershell

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)

Related

Cannot convert the "X" value of type "X" to type "X"

I can't work out why:
Exception calling "GetSites" with "1" argument(s): "Cannot convert the
"WS.WSErrorObject" value of type "WS.WSErrorObject" to type "WS.WSErrorObject"."
At ...
+ WS.WSSiteEntity[] $sites = $webServiceProxy.GetSites([ref] $wsError)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : PSInvalidCastException
The code is quite simple:
$webServiceProxy = New-WebServiceProxy -Uri $elevateUri -Credential $credential -Namespace WS
$wsError = New-Object -TypeName WS.WSErrorObject
WS.WSSiteEntity[] $sites = $webServiceProxy.GetSites([ref] $wsError)
It's similar to PowerShell 5 and classes - Cannot convert the "X" value of type "X" to type "X", so I think it has to do with there being multiple copies of the same type but I still can't work it out.
I have tried with full autogenerated typenames (i.e. not using a namespace for the Web Service proxy) and the result is the same.
I've tried to use weak typing but don't know how to declare wsError for the reference without constructing a new object and giving it a type.

Open Serial Port with variable

I want to open a COM port in my powershell script:
function openComPort($number, $baud) {
$port = New-Object System.IO.Ports.SerialPort("COM$number", $baud, "None", 8, "One")
$port.Open()
return $port
}
$myOpenedPort = openComPort(1, 9600)
This fails with
New-Object : Exception calling ".ctor" with "5" argument(s): "Positive number required.
Parameter name: BaudRate"
At line:9 char:20
+ $port = New-Object <<<< System.IO.Ports.SerialPort("COM$number", $baud, "None", 8, "One")
+ CategoryInfo : InvalidOperation: (:) [New-Object], MethodInvocationException
+ FullyQualifiedErrorId : ConstructorInvokedThrowException,Microsoft.PowerShell.Commands.NewObjectCommand
You cannot call a method on a null-valued expression.
At line:11 char:12
+ $port.Open <<<< ()
+ CategoryInfo : InvalidOperation: (Open:String) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
What am I doing wrong?
You're calling your function wrong, Powershell (unlike other languages) doesn't require brackets when calling a function, see about_functions for further info.
Using them like that groups everything inside the brackets into a single item, this is being sent to the first parameter $number, leaving $baud empty - which is causing your errors.
The correct syntax is:
openComPort 1 9600
EDIT: It's also good practice to have your params into a param() block (this is a step towards using advanced functions.
And to also set a param type to ensure you receive the correct input type. They are both int in this case - as you only want a positive whole number.
This would update your function to:
function openComPort {
Param(
[int]$number,
[int]$baud
)
$port = New-Object System.IO.Ports.SerialPort("COM$number", $baud, 'None', 8, 'One')
$port.Open()
return $port
}
$myOpenedPort = openComPort -number 1 -baud 9600

Saving Video Data To File From POST request InputStream in PowerShell

I am having trouble quite figuring out how to save video data sent to me via a HttpListener in PowerShell. I have the following which I believe is just sending it back to the requester but I'm having trouble just saving it into an MP4 file.
$req = $request
$body = $req.InputStream
$reader = New-Object System.IO.StreamReader ($body, $req.ContentEncoding)
$msg = $reader.ReadToEnd()
$reader.Close()
[byte[]] $buffer = [System.Text.Encoding]::UTF8.GetBytes($msg)
$res.ContentLength64 = $buffer.Length
$res.StatusCode = 200
$res.OutputStream.Write($buffer, 0, $buffer.Length)
$res.Close()
Thank you for your time eveyrone!
Update:
I have been able to make files with this, though for some reason in examples they're using 8192 sized byte but PowerShell says it's too big. With this I get zero length files, no errors that I can tell.
$path = "c:\matthew3.mp4"
$file = New-Object System.IO.FileStream $path,CreateNew
[byte]$bytes = 255
[int]$bytes_read = 0
while ( $bytes_read = $request.InputStream.Read($bytes, 0, $bytes.length) > 0 )
{
$file.Write($bytes, 0, $bytes_read)
}
Actually I did get an error:
Exception calling "GetBytes" with "1" argument(s): "Array cannot be null.
Parameter name: chars"
At line:45 char:1
+ $buffer = [System.Text.Encoding]::UTF8.GetBytes($content)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : ArgumentNullException
Exception calling "Write" with "3" argument(s): "Value cannot be null.
Parameter name: buffer"
At line:47 char:1
+ $response.OutputStream.Write($buffer, 0, $buffer.Length)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : ArgumentNullException
So the main developer for our company Nick pointed me in the right direction here.
The main thing is that for the FileStream object I needed to add the Write flag, and use the CopyTo method on the InputStream and then close both of them:
$file = New-Object System.IO.FileStream $path,CreateNew,Write
$context.Request.InputStream.CopyTo($file)
$file.Close()
$context.Request.InputStream.Close()

Powershell compare size of local file to file on sharepoint

I am using the current code to download a file from a sharepoint...
$webClient = New-Object System.Net.WebClient
$webClient.UseDefaultCredentials = $true
$webClient.DownloadFile($sharepointPathFile, $localPathFile) | Out-Null
But what if I wanted to check if the file is already at the local location and the size matches or is different? How would I do this using powershell?
Update
This was the closest I could get...
$url = $sharepointPathFile
$clnt = [System.Net.WebRequest]::Create($url)
$resp = $clnt.GetResponse()
$fileSize = $resp.ContentLength
Write-Host $fileSize
But I am getting the following error:
Exception calling "GetResponse" with "0" argument(s): "The remote server returned an error: (401) Unauthorized."
At C:\Scripts\Tests\testCheckUpdatedSearchFiles.ps1:345 char:2
+ $resp = $clnt.GetResponse()
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : WebException
I have full read and download rights, so is there something else not going right here?
I'm not sure if the "GetResponse" method will return exactly what you're looking for. And depending on the ContentLength, you may want to explicitly define your types. I would try something like this:
$webClient = New-Object System.Net.WebClient
$webClient.OpenRead("path/to/file")
[Int64]$fileSize = $webClient.ResponseHeaders["Content-Length"]
Write-Host $fileSize

I need help find the error in powershell script

Trying to get my script to work and need some help here is my code.
#excel
#open ap
$XL = new-object -com "Excel.Application"
$XLbooks = $XL.workbooks
$netci = [system.Globalization.CompareInfo]"en-us"
$wkbk = $XLbooks.PSBase.GetType().Invokemember("Add",[Reflection.BindingFlags]::InvokeMethod,$null,$XLbooks,$null,$newci)
$sheet = $XLbooks.worksheets.item(1)
$sheet.name = "name"
$sheet.cells.item($row,1).formulalocal = "Fred Nurk"
$file = "c\windows\scripts\test.xlsx"
[void]$wkbk.PSBase.GetType().InvokeMember("SaveAs",[Reflection.BindingFlags]::InvokeMethod,$null,$wkbk,$file,$newci)
("Close",[Reflection.BindingFlags]::Invokemedthod,$null,$wkbk,0,$newci)
$XL.quit()
Errors:
Cannot convert the "en-us" value of type "System.String" to type "System.Globalization.CompareInfo".
At C:\scripts\test.ps1:5 char:44
+ $netci = [system.Globalization.CompareInfo] <<<< "en-us"
+ CategoryInfo : NotSpecified: (:) [], RuntimeException
+ FullyQualifiedErrorId : RuntimeException
You cannot call a method on a null-valued expression.
At C:\scripts\test.ps1:7 char:34
+ $sheet = $XLbooks.worksheets.item <<<< (1)
+ CategoryInfo : InvalidOperation: (item:String) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
Property 'name' cannot be found on this object; make sure it exists and is settable.
At C:\scripts\test.ps1:8 char:8
+ $sheet. <<<< name = "name"
+ CategoryInfo : InvalidOperation: (name:String) [], RuntimeException
+ FullyQualifiedErrorId : PropertyNotFound
You cannot call a method on a null-valued expression.
At C:\scripts\test.ps1:9 char:18
+ $sheet.cells.item <<<< ($row,1).formulalocal = "Fred Nurk"
+ CategoryInfo : InvalidOperation: (item:String) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
Exception calling "InvokeMember" with "6" argument(s): "Microsoft Excel cannot access the file 'C:\Users\Jared\Document
s\c\windows\scripts\5ADD7000'. There are several possible reasons:
The file name or path does not exist.
The file is being used by another program.
The workbook you are trying to save has the same name as a currently open workbook."
At C:\scripts\test.ps1:11 char:42
+ [void]$wkbk.PSBase.GetType().InvokeMember <<<< ("SaveAs",[Reflection.BindingFlags]::InvokeMethod,$null,$wkbk,$file,$n
ewci)
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : DotNetMethodTargetInvocation
The main issue you need to address is creating the CompareInfo. The first error tells you this line isn't working:
$netci = [system.Globalization.CompareInfo]"en-us"
So what you'll need to do is create the CompareInfo object this way:
$netci = ([system.Globalization.CultureInfo]"en-us").CompareInfo
Though instead of using this crazy way to create a workbook:
$wkbk = $XLbooks.PSBase.GetType().Invokemember("Add",[Reflection.BindingFlags]::InvokeMethod,$null,$XLbooks,$null,$newci)
...try this more sane way instead :D
$wkbk = $XL.workbooks.Add()
If you do it this way, you won't have to worry about creating the CompareInfo object.
The problem that jumps out at me is that $netci = [system.Globalization.CompareInfo]"en-us" is invalid syntax. You're not calling any method on the System.Globalization.CompareInfo class, you're just placing a string after it. PowerShell is interpreting [System.Globalization.CompareInfo] as a typecast operator, and complains that the string "en-us" can't be converted to the data type System.Globalization.CompareInfo - because that data type doesn't exist.
You need to invoke a method that operates on "en-us". You can get a list of methods from MSDN:
http://msdn.microsoft.com/en-us/library/system.globalization.compareinfo.aspx
Assuming that the method you want is GetCompareInfo (seems most likely to me - it returns a CompareInfo object), you'd write that line this way:
$netci = [System.Globalization.CompareInfo]::GetCompareInfo('en-us')
Note, BTW, that you have this variable as $netci when you create it, but as $newci in the rest of the script.
I haven't looked too deeply at the other errors, but they're probably a cascade effect from the failure to create $newci properly, so I suspect that if you fix this, the other errors will go away.