Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # Designed for a specific implementation
- function Validate-Expression
- {
- Param (
- [string]$Expression )
- # Expected token types (plus 'Member' handled separately)
- $SafeTokenTypes = @(
- 'String'
- 'Variable'
- 'Type'
- 'Operator'
- 'GroupStart'
- 'GroupEnd'
- 'NewLine')
- try
- {
- # Use PowerShell parser to tokenize expression
- $Tokens = [System.Management.Automation.PSParser]::Tokenize( $File, [ref]$Null )
- }
- catch
- {
- # Expression cannot be parsed
- # Return unsafe
- return $False
- }
- # If successfully found tokens...
- # (Else null expression; return nothing)
- If ( $Tokens )
- {
- # For each token
- # (Using index so we can reference next token
- ForEach ( $Index in 0..($Tokens.Count-2) )
- {
- # If token is not something safe
- # or is not a Member followed by an Operator
- # ( "Property =" is safe. "Method(" is not )
- If ( $Tokens[$Index].Type -notin $SafeTokenTypes -and
- ( $Tokens[$Index].Type -ne 'Member' -or
- $Tokens[$Index+1].Type -ne 'Operator' ) )
- {
- # Return Unsafe
- return $False
- }
- }
- # Check last token
- # If token is not something safe
- If ( $Tokens[-1].Type -notin $SafeTokenTypes )
- {
- # Return unsafe
- return $False
- }
- # All tests passed
- # Return safe
- return $True
- }
- }
- function Import-WeirdFile
- {
- Param (
- [string]$Path )
- # Get the first and second "Something =" strings
- $ParentArray, $ArrayItem = Get-Content -Path $Path |
- Where-Object { $_ } |
- Select-Object -First 2 |
- ForEach-Object { $_.Trim() }
- # Get the full file as a single string
- $File = Get-Content -Path $Path -Raw
- # Tweak it as needed
- $File = $File.
- Replace( $ParentArray, '@(' ).
- Replace( $ArrayItem, '[pscustomobject]@{' ).
- Replace( '}', '},' ).
- Replace( '= yes', '= $True' ).
- Replace( '= no', '= $False' )
- # Tweak the stuff at the end
- $File = $File.Trim( " },`n`r`t" ) + ' } )'
- # If expression is safe to run
- If ( Validate-Expression $File )
- {
- # Run the expression
- Invoke-Expression -Command $File
- }
- }
- # Import sprites
- $Sprites = Import-WeirdFile -Path 'C:\Temp\sprites.txt'
Add Comment
Please, Sign In to add comment