gvphubli.blogspot.com
gvphubli.blogspot.com

Reputation: 110

Powershell script errors out

I referenced many threads on this and other forums, but not able to get this script to work in script form in ps or in bat or cmd file.

These commands work interactively within PowerShell

PowerShell Code:

#save creds
$creds=Get-Credential -Credential np\jcho

#create session
$session = New-CimSession –ComputerName "server-a.np.domainx.com", "server-b.np.domainx.com" -Credential $creds

#query the data needed.
Get-CimInstance -ClassName win32_operatingsystem -CimSession $session | select csname, lastbootuptime

Windows Batch/CMD file code:

powershell -noexit "& ""C:\Users\jcho\Downloads\remote_host_reboot_time.ps1"""
pause

Error Message:

C:\Users\jcho\Downloads>powershell -noexit "& ""C:\Users\jcho\Downloads\remote_host_reboot_time.ps1"""
At C:\Users\jcho\Downloads\remote_host_reboot_time.ps1:5 char:101
+ ... rver-a.np.domainx.com", "server-b.np.domainx.com" -Credential $creds
+                                                      ~~~~~~~~~~~~~~~~~~~~
The string is missing the terminator: ".
    + CategoryInfo          : ParserError: (:) [], ParseException
    + FullyQualifiedErrorId : TerminatorExpectedAtEndOfString

OS and PS Versions:

Window 10
PS Version : 5.1.18362.1171

When I run those 3 PS commands interactively I get the following output, which is what I am expecting from scripted files

Good Output:

csname        lastbootuptime
------        --------------
server-a  12/13/2019 12:30:37 AM
server-b  12/12/2019 12:01:53 AM

I am surprise to see that the windows powershell has been made so convoluted to script/use.

Upvotes: 1

Views: 221

Answers (1)

Chad Baldwin
Chad Baldwin

Reputation: 2602

It looks like the problem has to do with character encoding. This is always an annoying error to troubleshoot because things always "look" normal.

Here's how you can identify the problem for your particular script:

Open your script in notepad++ (or your favorite editor, but I'm using notepad++).

Then under the "Encoding" menu, select "ANSI". You'll see that in your case the hyphen on "ComputerName" is not a standard ASCII hyphen. This is likely because you copy-pasted your script from somewhere else.

For example, when I copy your script into a UTF-8 file in notepad++, then switch the encoding to ANSI, I see this:

New-CimSession –ComputerName

When I look up the hex code for –, which is E28093, I find it's this:

Unicode Character 'EN DASH' (U+2013) https://www.fileformat.info/info/unicode/char/2013/index.htm

Upvotes: 1

Related Questions