New Object PSCredential not working - using Unicode punctuation syntactically

我是研究僧i 提交于 2019-12-01 09:37:55
Mathias R. Jessen

The in front of the TypeName and ArgumentList parameters are not hyphens, but EN dashes (U+2013), and this trips up the parser. Replace them with a hyphen (-):

'New-object –TypeName System.Management.Automation.PSCredential –ArgumentList ($UserID,$SecurePassword)' -replace '\p{Pd}','-'

\p{Pd} is the unicode class for "Punctuation, dashes"

Editor's note: PowerShell, perhaps surprisingly, does not have a problem with using (en dash) in lieu of the regular ASCII-range - ("dash", technically: hyphen-minus) - try Get-ChildItem –File, for instance.
The OP's only problem is a character-encoding one, which you happen to bypass if you convert to regular "dashes". Turning the Unicode en dashes into ASCII "dashes" is only a stopgap: It masks the OP's true problem of having saved a file with an encoding that Windows PowerShell misinterprets. If that file contained non-ASCII characters as data, it would still be broken.

PowerShell is unusual in that allows interchangeable use of ASCII-range punctuation and whitespace with (non-ASCII) Unicode punctuation and whitespace - see the bottom section of this answer.

Therefore, use of non-ASCII character EN DASH (U+2013) in lieu of ASCII character - HYPHEN-MINUS (U+002D) is not a problem in itself.

The problem in your case was a character encoding problem, as evidenced by your error output: the en dashes weren't recognized as such, because - as you've later stated in a comment - your source code file was UTF-8-encoded but lacked a BOM, causing PowerShell to interpret it as "ANSI" code page-encoded (e.g., code page Windows-1252 on US-English systems).

This misinterpretation causes to be interpreted as â€, and that is the true cause of your problem.

Using UTF-8 to save your source code is generally a good idea, but on Windows PowerShell you must include a BOM.
That said, if your source code happens not to contain any non-ASCII characters, there won't be a problem.

Unfortunately, the BOM requirement is at odds with UTF-8 use on other platforms, where a BOM may even cause problems; perhaps for that reason modern editors such as Visual Studio Code and Sublime Text default to BOM-less UTF-8 and must explicitly be instructed to save with a BOM; while you can typically change the default to including a BOM, it is best to do that only for PowerShell files, if supported.

Note that PowerShell Core doesn't have this problem, as it defaults to UTF-8 (but still correctly recognizes a UTF-8 BOM, if present).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!