I am trying to read a txt file with powershell, on only certain characters
$TxtFilePath = "C:\Users\myname\mycode\mydata.txt"
$TxtData = Get-Content $TxtFilePath | ForEach-Object {
# Ensure the line is long enough before extracting substrings
$Line = $_.PadRight(138) # Pad the line to ensure it has at least 138 characters
$entry = @{
LastName = $Line.Substring(18, 40).Trim()
FirstName = $Line.Substring(58, 40).Trim()
Birthdate = $Line.Substring(128, 10).Trim()
}
[PSCustomObject]$entry
}
that Nth until Nth character is a space for corresponding value (although sometimes for example the name is only 5 character, but chracter 18-58 is prepared for the lastname). When I run that code, the error is """ The value cannot be converted to the type “System.Management.Automation.LanguagePrimitives+InternalPSCustomObject”. Only core types are supported in this language mode. """
And it refers to this line """[PSCustomObject]$entry""" would appreciate any lead
I do expect it can read the txt files according to the rule.
The error message implies that your session runs in ConstrainedLanguage
mode (see the about_Language_Modes help topic).
However, the error message is indicative of a bug, present in Windows PowerShell as well as in PowerShell (Core) 7 as of v7.5.0: You should be able to use a [pscustomobject]
cast in order to construct an instance in constrained language mode, given that the type itself (aka [psobject]
) is supported in this mode:
Workaround:
Use New-Object
rather than a cast to construct your [pscustomobject]
instance:
# ...
$entry = [ordered] @{
LastName = $Line.Substring(18, 40).Trim()
FirstName = $Line.Substring(58, 40).Trim()
Birthdate = $Line.Substring(128, 10).Trim()
}
New-Object pscustomobject -Property $entry
# ...
Note the use of [ordered]
, i.e. of an ordered hashtable, so as to guarantee that the properties are created in definition order.