Convert a string variable into an integer - powershell

I'm trying to convert my $file_data variable into an integer, the bit of code below grabs the number of a computer on my system held in a directory. However when run in PowerShell I get he below error even though the variable is a number.
The '++' operator works only on numbers. The operand is a 'System.String'.
At D:\pscript\Intune.ps1:7 char:26
+ For ($file_data -le 130; $file_data++ ){
+ ~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : OperatorRequiresNumber
I'm not sure where I'm going wrong on this any help would be amazing. :)
Get-Content D:\pscript\temp\Directory.txt
$file_data = Get-Content D:\pscript\temp\Directory.txt

For converting string to integer, you can typecast it or declare it at the first point.
[int] $file_data = Get-Content D:\pscript\temp\Directory.txt
However, if this needs to work, Directory.txt should have number which can fit into the category of an integer.

Related

Cannot find an overload for "ToString" and the argument count: "1"

i'm not understanding what i'm doing wrong here since i seem to do the same thing but only one works.
i have a text file with a number list that i want to process (round the values):
39.145049
40.258140
41.400803
42.540093
43.664530
and here my script:
$a = get-content "input.txt"
$b = $a -join ','
$b | % {$_.ToString("#.###")}
this results in the following error:
Cannot find an overload for "ToString" and the argument count: "1".
At D:\script.ps1:9 char:9
+ $b | % {$_.ToString("#.###")}
+ ~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodException
+ FullyQualifiedErrorId : MethodCountCouldNotFindBest
however if i take the result after joining which is:
39.145049,40.258140,41.400803,42.540093,43.664530
and create the following script:
$b = 39.145049,40.258140,41.400803,42.540093,43.664530
$b | % {$_.ToString("#.###")}
it works just fine and outputs:
39.145
40.258
41.401
42.54
43.665
where am i going wrong on this one?
This happens as the inputs are not of the same type.
$b1 = $a -join ','
$b2 = 39.145049,40.258140,....
$b1.GetType().Name
String
$b2.GetType().Name
Object[]
As the input in the first case is a single string, foreach loop doesn't process it as a collection of decimal values but a single string. Thus,
$b | % {$_.ToString("#.###")}
Is going to do (as pseudocode):
'39.145049,40.258140,41.400803,42.540093,43.664530'.ToString("#.###")
Whilst the array version is doing
39.145049.ToString("#.###")
40.258140.ToString("#.###")
41.400803.ToString("#.###")
Powershell's able to figure out in the later case that the values are numbers. In the first case, it's just a string and thus the automatic conversion doesn't work.
What actually works in the first case is to cast the values as nubmers. Like so,
$a | % {$([double]$_).ToString("#.###")}
39,145
40,258
41,401
42,54
43,665

PowerShell error 'can't call null-value expresssion' [duplicate]

I am simply trying to create a powershell script which calculates the md5 sum of an executable (a file).
My .ps1 script:
$answer = Read-Host "File name and extension (ie; file.exe)"
$someFilePath = "C:\Users\xxx\Downloads\$answer"
If (Test-Path $someFilePath){
$stream = [System.IO.File]::Open("$someFilePath",[System.IO.Filemode]::Open, [System.IO.FileAccess]::Read)
$hash = [System.BitConverter]::ToString($md5.ComputeHash($stream))
$hash
$stream.Close()
}
Else{
Write-Host "Sorry, file $answer doesn't seem to exist."
}
Upon running my script I receive the following error:
You cannot call a method on a null-valued expression.
At C:\Users\xxx\Downloads\md5sum.ps1:6 char:29
+ $hash = [System.BitConverter]::ToString($md5.Compute ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
To my understanding, this error means the script is attempting to do something, but another part of the script does not have any information to permit the first part of the script to work properly. In this case, $hash.
Get-ExecutionPolicy outputs Unrestricted.
What is causing this error?
What exactly is my null valued expression?
Any help is appreciated. I apologize if this is trivial and will continue my research.
References:
http://blogs.technet.com/b/heyscriptingguy/archive/2013/03/27/troubleshoot-the-invokemethodonnull-error-with-powershell.aspx
How to get an MD5 checksum in PowerShell
The simple answer for this one is that you have an undeclared (null) variable. In this case it is $md5. From the comment you put this needed to be declared elsewhere in your code
$md5 = new-object -TypeName System.Security.Cryptography.MD5CryptoServiceProvider
The error was because you are trying to execute a method that does not exist.
PS C:\Users\Matt> $md5 | gm
TypeName: System.Security.Cryptography.MD5CryptoServiceProvider
Name MemberType Definition
---- ---------- ----------
Clear Method void Clear()
ComputeHash Method byte[] ComputeHash(System.IO.Stream inputStream), byte[] ComputeHash(byte[] buffer), byte[] ComputeHash(byte[] buffer, int offset, ...
The .ComputeHash() of $md5.ComputeHash() was the null valued expression. Typing in gibberish would create the same effect.
PS C:\Users\Matt> $bagel.MakeMeABagel()
You cannot call a method on a null-valued expression.
At line:1 char:1
+ $bagel.MakeMeABagel()
+ ~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
PowerShell by default allows this to happen as defined its StrictMode
When Set-StrictMode is off, uninitialized variables (Version 1) are assumed to have a value of 0 (zero) or $Null, depending on type. References to non-existent properties return $Null, and the results of function syntax that is not valid vary with the error. Unnamed variables are not permitted.

PowerShell ValidateLength with Read-Host

I am trying to use ValidateLength declaration with Read-Host, however I cannot get it to work. If I use it without Read-Host it works flawless. Here are some basic examples:
[ValidateLength(1,3)]$test = '123'
[ValidateLength(1,3)]$test1 = Read-Host
123
Attribute cannot be added because it would cause the variable test1 with value
123 to become invalid.
At line:1 char:1
+ [ValidateLength(1,3)]$test1 = Read-Host
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : MetadataError: (:) [], ValidationMetadataExcepti
on
+ FullyQualifiedErrorId : ValidateSetFailure
Is it possible to use ValidateLength declaration with Read-Host?
Declare your Read-Host as a string (since ValidateLength can not accept anything except a string) and the problem is solved.
[ValidateLength(1,3)]$test1 = [String](Read-Host "Input")
I am not sure why you have to cast a type on it, but it solves the problem.

Weird PowerShell Exec Output Capture Behavior

I'm writing a simple PowerShell script that handles the output of mkvinfo. It captures the output of mkvinfo, stores in a variable $s and does some post-processing on $s. The strange part is while $s has content, I can't extract a substring from it.
The error message I'm getting was:
Exception calling "Substring" with "1" argument(s): "startIndex cannot be larger than length of string.
Parameter name: startIndex"
This is a sample code:
$filePath = $folder + $file.name
$mkvinfoExe = "C:\mkvinfo.exe"
$s = & $mkvinfoExe $filePath
$s | out-host
$s.Substring($s.Length-1) | out-host
Are you sure $s is a string and not an array? If it is an array, $s.Length will be the number of elements in the array and you could get the error that you are getting.
For example:
PS > $str = #("this", "is", "a")
PS > $str.SubString($str.Length - 1)
Exception calling "Substring" with "1" argument(s): "startIndex cannot be larger than length of string.
Parameter name: startIndex"
At line:1 char:1
+ $str.SubString($str.Length - 1)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : ArgumentOutOfRangeException
Just found out because mkvinfo outputs multiple lines, $s is actually a String array (or List?). Switching to $s[0].Substring($s[0].Length-1) solves it.

Casting in PowerShell. Weird syntax

Reading XML from a file into a variable can be done like this:
[xml]$x = Get-Content myxml.xml
But why not:
$x = [xml]Get-Content myxml.xml
Which gives:
Unexpected token 'Get-Content' in expression or statement.
At line:1 char:20
+ $x=[xml]get-content <<<< myxml.xml
+ CategoryInfo : ParserError: (get-content:String) [], ParentContainsErrorRecordException
+ FullyQualifiedErrorId : UnexpectedToken
That is, why is the cast operation done on the left-hand side of the equals sign? Typically in programming languages the casting is done on the right-hand side like (say) in Java:
a = (String)myobject;
$x = [xml](Get-Content myxml.xml)
In PowerShell everything is an object. That includes the cmdlets. Casting is the process of converting one object type into another.
What this means for casting is that, like in math, you can add in unnecessary brackets to help you clarify for yourself what exactly is happening. In math, 1 + 2 + 3 can become ((1 + 2) + 3) without changing its meaning.
For PowerShell the casting is performed on the next object (to the right), so $x = [xml] get-content myxml.xml becomes $x = ([xml] (get-content)) myxml.xml. This shows that you are trying to cast the cmdlet into an xml object, which is not allowed.
Clearly this is not what you are trying to do, so you must first execute the cmdlet and then cast, AKA $x = [xml] (get-content myxml.xml). The other way to do it, [xml] $x = get-content myxml.xml, is declaring the variable to be of the type xml so that whatever gets assigned to it (AKA the entire right-hand side of the equal sign) will be cast to xml.