Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Convert a string variable into an integer

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading