Guest User

Untitled

a guest
Feb 24th, 2018
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.54 KB | None | 0 0
  1. # Designed for a specific implementation
  2. function Validate-Expression
  3. {
  4. Param (
  5. [string]$Expression )
  6.  
  7. # Expected token types (plus 'Member' handled separately)
  8. $SafeTokenTypes = @(
  9. 'String'
  10. 'Variable'
  11. 'Type'
  12. 'Operator'
  13. 'GroupStart'
  14. 'GroupEnd'
  15. 'NewLine')
  16.  
  17. try
  18. {
  19. # Use PowerShell parser to tokenize expression
  20. $Tokens = [System.Management.Automation.PSParser]::Tokenize( $File, [ref]$Null )
  21. }
  22. catch
  23. {
  24. # Expression cannot be parsed
  25. # Return unsafe
  26. return $False
  27. }
  28.  
  29. # If successfully found tokens...
  30. # (Else null expression; return nothing)
  31. If ( $Tokens )
  32. {
  33. # For each token
  34. # (Using index so we can reference next token
  35. ForEach ( $Index in 0..($Tokens.Count-2) )
  36. {
  37. # If token is not something safe
  38. # or is not a Member followed by an Operator
  39. # ( "Property =" is safe. "Method(" is not )
  40. If ( $Tokens[$Index].Type -notin $SafeTokenTypes -and
  41. ( $Tokens[$Index].Type -ne 'Member' -or
  42. $Tokens[$Index+1].Type -ne 'Operator' ) )
  43. {
  44. # Return Unsafe
  45. return $False
  46. }
  47. }
  48. # Check last token
  49. # If token is not something safe
  50. If ( $Tokens[-1].Type -notin $SafeTokenTypes )
  51. {
  52. # Return unsafe
  53. return $False
  54. }
  55.  
  56. # All tests passed
  57. # Return safe
  58. return $True
  59. }
  60. }
  61.  
  62. function Import-WeirdFile
  63. {
  64. Param (
  65. [string]$Path )
  66.  
  67. # Get the first and second "Something =" strings
  68. $ParentArray, $ArrayItem = Get-Content -Path $Path |
  69. Where-Object { $_ } |
  70. Select-Object -First 2 |
  71. ForEach-Object { $_.Trim() }
  72.  
  73. # Get the full file as a single string
  74. $File = Get-Content -Path $Path -Raw
  75.  
  76. # Tweak it as needed
  77. $File = $File.
  78. Replace( $ParentArray, '@(' ).
  79. Replace( $ArrayItem, '[pscustomobject]@{' ).
  80. Replace( '}', '},' ).
  81. Replace( '= yes', '= $True' ).
  82. Replace( '= no', '= $False' )
  83.  
  84. # Tweak the stuff at the end
  85. $File = $File.Trim( " },`n`r`t" ) + ' } )'
  86.  
  87. # If expression is safe to run
  88. If ( Validate-Expression $File )
  89. {
  90. # Run the expression
  91. Invoke-Expression -Command $File
  92. }
  93. }
  94.  
  95. # Import sprites
  96. $Sprites = Import-WeirdFile -Path 'C:\Temp\sprites.txt'
Add Comment
Please, Sign In to add comment