PowerShell script error: the string is missing the terminator: - powershell

Incredibly simple powershell script...
#Server side storage copy
$SourceStorageAccount = "myStorageAccount"
$SourceStorageKey = "myKey"
$SourceStorageContext = New-AzureStorageContext –StorageAccountName $SourceStorageAccount -StorageAccountKey $SourceStorageKey
fails with the error
At E:\DeploymentScripts\Storage\Test.ps1:6 char:51
+ ... geContext –StorageAccountName $SourceStorageAccount -StorageAccount ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The string
is missing the terminator: ".
+ CategoryInfo : ParserError: (:) [], ParseException
+ FullyQualifiedErrorId : TerminatorExpectedAtEndOfString
The strangest part is if I copy and paste the contents of the ps1 file into a PowerShell command line, it works fine !? What's going on?
Obviously I have removed my storage container name and key, you will need to assign your own Azure storage account name and api key to replicate it.
EDIT: A screen shot of the script edited in Notepad++ with all characters visible...

It's similar with this question.
When you copy cmdlets from Web, maybe there are some special characters. I suggest you could copy the cmdlets to Notepad then copy to PowerShell.
It's helpful to use cat filename.ps1 in the terminal you can see determine which characters are bad, it's not obvious in the editor.

So parts of the code are copied and pasted from websites which have non-standard dash characters. I found it easier to see the characters when you use the cat command from the powershell command line to list the file
Here's a screenshot of what it looks like listed in the powershell:-

Related

Script runs in ISE but not in Powershell

I have a powershell script. This script runs perfectly fine if I open it in Powershell ISE, however, if I right click on the file and click 'run with powershell' the script throws an error.
Furthermore, I read in previous threads that the following execution pattern solved the issue for some people:
powershell -STA -File script.ps1
In this case this didn't solve the issue, however it did allow me to read the error:
At C:\Users\sancarn\AppData\Local\Temp\script.ps1:20 char:20
+ $parent = [System.Windows.Forms.TreeNode]$global:database.Ite ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Unable to find type [System.Windows.Forms.TreeNode].
At C:\Users\sancarn\AppData\Local\Temp\script.ps1:27 char:36
+ ... [void]$node.nodes.add([System.Windows.Forms.TreeNode]::new(" ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Unable to find type [System.Windows.Forms.TreeNode].
At C:\Users\sancarn\AppData\Local\Temp\script.ps1:33 char:45
+ ... PSCustomObject]IWDBGetChildren([System.Windows.Forms.TreeNode]$node) ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Unable to find type [System.Windows.Forms.TreeNode].
+ CategoryInfo : ParserError: (:) [], ParentContainsErrorRecordException
+ FullyQualifiedErrorId : TypeNotFound
This having been said, I'm not sure I can really do anything about this error specifically... I already load System.Windows.Forms and System.Drawing... Does anyone have any idea how to execute this file properly?
Edit
Other attempts at trying to fix the issue:
powershell -NoExit -STA -File script.ps1
powershell -NoExit -STA -File script.ps1 -Scope Global
Edit 2
I have also tried adding:
Add-Type -AssemblyName System.Windows.Forms
To the top of the powershell script. The issue remains unresolved however.
Edit:
Not sure why this is being flagged as a duplicate after
this answer already has a recommended answer and
the recommended answer demonstrates why this is different.
...
As #PetSerAl said in his comment, the answer is in https://stackoverflow.com/a/34637458
Every PowerShell script is completely parsed before the first statement in the script is executed. An unresolvable type name token inside a class definition is considered a parse error. To solve your problem, you have to load your types before the class definition is parsed, so the class definition has to be in a separate file.
Ultimately to resolve the issue I need to either load my class definitions as a separate file, or store my declarations in a header file, which calls the class definitions (and the rest of the script).
I am amazed this was even an issue but it works now, so that's good...
Edit
In my case it is a bit different to the post linked by the solution author. I'm actually building a ruby library for executing Powershell on windows machines. Currently I don't write data to a file and I can't guarantee that a here-string/invoke-expression will work.
Invoke-Expression #"
$anotherString=#"
hello world!
"#
"# <--- Powershell will throw an error here!
Instead I've decided to encode the body if a header is present, and then decode and execute at runtime
require 'base64'
if header!=""
encoded_body = Base64.strict_encode64(body.encode("utf-16le"))
body = <<-END_TRANSFORMATION
#{header}
$encoded_body = "#{encoded_body}"
Invoke-Expression $([System.Text.Encoding]::Unicode.GetString([System.Convert]::FromBase64String($encoded_body)))
END_TRANSFORMATION
end
So far this has appeared to work in all cases, doesn't need external files, and will work even if users use here-doc strings in their Powershell scripts!

Powershell Get-FileMetaData not recognized

I am trying to use the PowerShell command 'Get-FileMetaData' however PowerShell ISE outputs the following error:
Get-FileMetaData : The term 'Get-FileMetaData' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path
was included, verify that the path is correct and try again.
At line:1 char:1
+ Get-FileMetaData E:\Test_Output
+ ~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (Get-FileMetaData:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
The path is correct, I have also tried various existing paths. I cant find anything about what version this command requires, but using $PSVersionTable.PSVersion output states 'Major 5' so I believe I am using PS v5.
Has anyone else had issue with this command? I have found various forums mentioning its function, but cant find much on troubleshooting it.
Thanks for any help!
That is not a core PowerShell cmdlet so I would expect that to fail for most people. As far as I know that comes from the Script Gallery. You need to download that first.
So if you want that to be loaded then take that module will need to be imported either manually or automatically.
You can read more about module loading on MSDN
Using the free tool 'exiftool' I have put together to following script:
$creator = C:\Windows\exiftool.exe "-Creator" $Image.FullName
This allows $creator to be the files Creator which in the case of our production images is the same as the Author.

Unable to run 7-Zip in Powershell

This came up in a discussion on another question I asked on running executables in Windows Powershell
Whenever I run 7z in my workplace machine that has PS 2.0, I get this error
Bad numeric constant: 7.
At line;1 char:2
+ 7 <<<< z
+ CategoryInfo : ParserError: <7:String> [], ParentContainsErrorRecordException
+ FullyQualifiedErrorId : BadNumericConstant.
Note that this error occurs even if I give the full filename 7z.exe. However, if I go into Command Line mode by entering cmd it works without any problems.
Any help would be appreciated.
Try this:
& "Path\to\7z.exe" arg1 arg2 etc
It sounds like PowerShell is trying to interpret your [String] literally as an [Int]

All commands failing in powershell (4.0.) Even "c:" and "cd" and "dir"

I'm not sure when this started... whenever I open PowerShell, I can't execute even the most basic commands. I always get the following error message:
PS C:\> dir
dir : Cannot find drive. A drive with the name '.' does not exist.
At line:1 char:1
+ dir
+ ~~~
+ CategoryInfo : ObjectNotFound: (.:String) [], DriveNotFoundException
+ FullyQualifiedErrorId : DriveNotFound
---
This had been working fine but now all of a sudden I can't do anything. I've tried removing PowerShell 4 and re-installing... no change. Sorry for the formatting here... It looks organized in my view above but the preview text looks horrid.
I don't remember ever having java installed, but looking at my regular %path% I see that %java_home% is in there, but the value is never used or defined anywhere. Once I removed that from my path, the error above went away.
Strange that it would even be an issue for powershell. You'd think it would just skip past a non-existent directory in my path and move onto the next one when resolving a command.

Powershell Continuations (>>) Broken In ISE But Not Normal Prompt

I've been working on this for 2 hours and I'm pulling my hair out. I was working in ISE on my profile script. I don't know if it's relevant but I was trying to store some commands in a variable and execute them later. Anyway I started getting a weird error when trying to create a here-string:
PS > $foo = #"
Ordinarily I would expect
>>
to follow, but instead I get this message:
PS C:\Users\lamartin> #"
The string is missing the terminator: "#.
+ CategoryInfo : ParserError: (:) [], ParentContainsErrorRecordException
+ FullyQualifiedErrorId : TerminatorExpectedAtEndOfString
To make a long story short I have discovered that ALL my multi-line commands are broken, but only in ISE:
PS > gci |
An empty pipe element is not allowed.
+ CategoryInfo : ParserError: (:) [], ParentContainsErrorRecordException
+ FullyQualifiedErrorId : EmptyPipeElement
PS > gci |% {
Missing closing '}' in statement block.
+ CategoryInfo : ParserError: (:) [], ParentContainsErrorRecordException
+ FullyQualifiedErrorId : MissingEndCurlyBrace
I removed all profiles and all modules. I verified there was nothing extra being loaded (that I could find). Here is something interesting I did find out. It turns out that Powershell actually ALWAYS errors whenever you do a continuation. It just hides it:
http://connect.microsoft.com/PowerShell/feedback/details/371321/benign-errors-for-missing-closing-are-left-in-the-error-variable
And sure enough if I type in one of the above commands in a regular window, while it works silently, if I later go back and look at the $error object there is an identical error. So basically ISE has decided to stop supressing these errors. I looked at all the settings I could think of $WarningPreference $ErrorActionPreference, etc but they are the same in ISE and normal console.
Thanks in advance for any help.
Update
Wow I feel stupid. Apparently this is expected behavior. I could have SWORN that it was behaving differently just a little bit earlier. I guess I was tired.
In PowerShell ISE, you can run a multiline command in the Command Pane. Press SHIFT+ENTER to enter each line of a multiline command, and press ENTER after the last line to execute the multiline command. You can find this in How to Use the Console Pane in the Windows PowerShell ISE.