1

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
1
  • 1
    Have you tried casting the variable to an integer type: for ([int]$file_data -le 130; $file_data++ ){ ... } Commented Jun 8, 2022 at 14:12

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Added both this and "for ([int]$file_data -le 130; $file_data++ )" from the comment and it worked. Many thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.