locked
Executing a PowerShell Script from a Command Line RRS feed

  • Question

  • I"m really getting tired of fighting the process of executing a PowerShell script from a command line (task scheduler, in this case). I'm just trying to execute this simple script:

    Write-Host "Press any key to continue ..."

    $x = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")

    # SIG # Begin signature block
    # MIIEYQYJKoZIhvcNAQcCoIIEUjCCBE4CAQExCzAJBgUrDgMCGgUAMGkGCisGAQQB
    # gjcCAQSgWzBZMDQGCisGAQQBgjcCAR4wJgIDAQAABBAfzDtgWUsITrck0sYpfvNR
    # AgEAAgEAAgEAAgEAAgEAMCEwCQYFKw4DAhoFAAQUwnZ6YtKQbSg98GmUnGmZO+85
    # paigggJmMIICYjCCAcugAwIBAgIQFu5DU9l/Ap1MdalTP+y/aTANBgkqhkiG9w0B
    # AQQFADAxMS8wLQYDVQQDHiYAUwBIAEgALQBBAEMAVAAwADEAXwBSAG8AbwB0AF8A
    # QwBlAHIAdDAeFw0xNjAzMTUxNzIxMzVaFw0zOTEyMzEyMzU5NTlaMDExLzAtBgNV
    # BAMeJgBTAEgASAAtAEEAQwBUADAAMQBfAFIAbwBvAHQAXwBDAGUAcgB0MIGfMA0G
    # CSqGSIb3DQEBAQUAA4GNADCBiQKBgQCoE1Jj3GQix42t2J2bd6DHePM9B5kjISIC
    # rTx8cDsROaIrRFcdD9O070r1ZARe+E+hBArW6s9fAFKPWDiuPj/bSIu1Zy/U+AX3
    # RZrCnsxTZ+jHRYnFWkb5eE5ceazwVzYkhV1hcmebJlfbP4g/OdXcIUlFWM1Pt06b
    # Y3VVMW34/QIDAQABo3sweTATBgNVHSUEDDAKBggrBgEFBQcDAzBiBgNVHQEEWzBZ
    # gBC+ifk+H66FjXvBC5GopLzVoTMwMTEvMC0GA1UEAx4mAFMASABIAC0AQQBDAFQA
    # MAAxAF8AUgBvAG8AdABfAEMAZQByAHSCEBbuQ1PZfwKdTHWpUz/sv2kwDQYJKoZI
    # hvcNAQEEBQADgYEAm/wrCy2n75pvqFtT3ClHocDi97BFSMpkuuiCrowh3IRfOzF7
    # YiDCAx1bulrd5jHSB51m/l8mLp7hynw8nR/2SRNoluE+tTow17YnzgKwSuCtMS6j
    # 01pV57rmltB1CxuW9q8ZrC121sRLvGDfZx1npgTqiXKb/3ZajMTSDz0lTkwxggFl
    # MIIBYQIBATBFMDExLzAtBgNVBAMeJgBTAEgASAAtAEEAQwBUADAAMQBfAFIAbwBv
    # AHQAXwBDAGUAcgB0AhAW7kNT2X8CnUx1qVM/7L9pMAkGBSsOAwIaBQCgeDAYBgor
    # BgEEAYI3AgEMMQowCKACgAChAoAAMBkGCSqGSIb3DQEJAzEMBgorBgEEAYI3AgEE
    # MBwGCisGAQQBgjcCAQsxDjAMBgorBgEEAYI3AgEVMCMGCSqGSIb3DQEJBDEWBBSP
    # 28fhYEacyHZjOpJNtul6q/xmQzANBgkqhkiG9w0BAQEFAASBgI9Yr6ZO9SuAIvRp
    # AoWuC6pa7uQF7JWJsT6aYP/cxbne89MM4EIOZpRovhXuNqON0e7Jvzc6CxnU4qgl
    # Z+9QfOuefr2Hafnoju+q7NtNUgsG5jGegcAc5kF15+Dba529ondjNwwhQjHbXIrk
    # TxwYbIpOYiHtmM2N5SCKzniXe9hl
    # SIG # End signature block

    As you can see, it's been signed. 

    When I try to execute it using any of the following commands, it fails with this error:

    File C:\ACT Backups\test.ps1 cannot be loaded because the execution of scripts
    is disabled on this system. Please see "get-help about_signing" for more detail
    s.
        + CategoryInfo          : NotSpecified: (:) [], ParentContainsErrorRecordE
       xception
        + FullyQualifiedErrorId : RuntimeException

    The execution statements I tried:

    powershell -file "test.ps1" -executionpolicy restricted

    powershell -file "test.ps1" -executionpolicy allsigned

    powershell -file "test.ps1" -executionpolicy remotesigned

    powershell -file "test.ps1" -executionpolicy unrestricted

    powershell -file "test.ps1" -executionpolicy bypass

    powershell -file "test.ps1" -executionpolicy undefined

    This is getting REALLY, REALLY, REALLY old fighting this crap.  This is a machine with two users that can get to it and I absolutely do not care who runs what on it. 

    Friday, April 15, 2016 9:10 PM

Answers

  • That is NOT listed in the PowerShell.exe /? text.

    That's correct, a small oversight for the powershell.exe /? help in v2. MS updated the /? description for v3 and later to make the parsing rules more explicit. That's why I posted the help text directly from v3. The updated help is also listed in the online version which is easily searchable.


    -- Bill Stewart [Bill_Stewart]


    • Edited by Bill_Stewart Monday, April 18, 2016 3:50 AM
    • Proposed as answer by Bill_Stewart Monday, April 18, 2016 2:43 PM
    • Marked as answer by Bill_Stewart Thursday, June 2, 2016 9:02 PM
    Monday, April 18, 2016 3:45 AM

All replies

  • 1. open a command prompt as administrator

    2. type in, powershell, hit enter

    3. type in, set-executionpolicy allsigned, hit enter

    Should be fixed now

    Friday, April 15, 2016 9:13 PM
  • The -File parameter must be LAST on the powershell.exe command line. This is documented in the powershell.exe /? help:


    -File
        Runs the specified script in the local scope ("dot-sourced"), so that the
        functions and variables that the script creates are available in the
        current session. Enter the script file path and any parameters.
        File must be the last parameter in the command, because all characters
        typed after the File parameter name are interpreted
        as the script file path followed by the script parameters.
    


    -- Bill Stewart [Bill_Stewart]

    • Proposed as answer by jrv Friday, April 15, 2016 10:47 PM
    • Unproposed as answer by Greg Wilkerson Sunday, April 17, 2016 12:03 AM
    • Proposed as answer by jrv Sunday, April 17, 2016 12:35 AM
    Friday, April 15, 2016 9:30 PM
  • There is no substitute for learning PowerShell.  Those who try to guess at how it works form copying bad code will never learn.

    We have been saying this for years and still everyone plays stupid like 'W'.  C'mon. Get with the program kids.


    \_(ツ)_/

    Friday, April 15, 2016 10:50 PM
  • That is NOT listed in the PowerShell.exe /? text. However, place the file switch at the end does work.  I'm sure this has to do with the differing version of PowerShell floating around.  Below in the EXACT text that I get returned:

    B:\>powershell.exe /?

    PowerShell[.exe] [-PSConsoleFile <file> | -Version <version>]
        [-NoLogo] [-NoExit] [-Sta] [-NoProfile] [-NonInteractive]
        [-InputFormat {Text | XML}] [-OutputFormat {Text | XML}]
        [-WindowStyle <style>] [-EncodedCommand <Base64EncodedCommand>]
        [-File <filePath> <args>] [-ExecutionPolicy <ExecutionPolicy>]
        [-Command { - | <script-block> [-args <arg-array>]
                      | <string> [<CommandParameters>] } ]

    PowerShell[.exe] -Help | -? | /?

    -PSConsoleFile
        Loads the specified Windows PowerShell console file. To create a console
        file, use Export-Console in Windows PowerShell.

    -Version
        Starts the specified version of Windows PowerShell.

    -NoLogo
        Hides the copyright banner at startup.

    -NoExit
        Does not exit after running startup commands.

    -Sta
        Start the shell using a single-threaded apartment.

    -NoProfile
        Does not use the user profile.

    -NonInteractive
        Does not present an interactive prompt to the user.

    -InputFormat
        Describes the format of data sent to Windows PowerShell. Valid values are
        "Text" (text strings) or "XML" (serialized CLIXML format).

    -OutputFormat
        Determines how output from Windows PowerShell is formatted. Valid values
        are "Text" (text strings) or "XML" (serialized CLIXML format).

    -WindowStyle
        Sets the window style to Normal, Minimized, Maximized or Hidden.

    -EncodedCommand
        Accepts a base-64-encoded string version of a command. Use this parameter
        to submit commands to Windows PowerShell that require complex quotation
        marks or curly braces.

    -File
        Execute a script file.

    -ExecutionPolicy
        Sets the default execution policy for the session.

    -Command
        Executes the specified commands (and any parameters) as though they were
        typed at the Windows PowerShell command prompt, and then exits, unless
        NoExit is specified. The value of Command can be "-", a string. or a
        script block.

        If the value of Command is "-", the command text is read from standard
        input.

        If the value of Command is a script block, the script block must be enclosed

        in braces ({}). You can specify a script block only when running PowerShell.
    exe
        in Windows PowerShell. The results of the script block are returned to the
        parent shell as deserialized XML objects, not live objects.

        If the value of Command is a string, Command must be the last parameter
        in the command , because any characters typed after the command are
        interpreted as the command arguments.

        To write a string that runs a Windows PowerShell command, use the format:
            "& {<command>}"
        where the quotation marks indicate a string and the invoke operator (&)
        causes the command to be executed.

    -Help, -?, /?
        Shows this message. If you are typing a PowerShell.exe command in Windows
        PowerShell, prepend the command parameters with a hyphen (-), not a forward
        slash (/). You can use either a hyphen or forward slash in Cmd.exe.

    EXAMPLES
        PowerShell -PSConsoleFile SqlSnapIn.Psc1
        PowerShell -version 1.0 -NoLogo -InputFormat text -OutputFormat XML
        PowerShell -Command {Get-EventLog -LogName security}
        PowerShell -Command "& {Get-EventLog -LogName security}"

        # To use the -EncodedCommand parameter:
        $command = 'dir "c:\program files" '
        $bytes = [System.Text.Encoding]::Unicode.GetBytes($command)
        $encodedCommand = [Convert]::ToBase64String($bytes)
        powershell.exe -encodedCommand $encodedCommand

    Sunday, April 17, 2016 12:07 AM
  • Agreed.  I use this extensively for many basic operation with SQL Server.  Excellent subsystem when used within its bounds.  The error trapping sucks and for more complicated tasks I resort to .NET based code.
    Sunday, April 17, 2016 12:10 AM
  • What I ended up doing installing the group policy administrative templates for PowerShell and configure the policy for allow local require remote signed.

    Problem solved.

    • Marked as answer by Greg Wilkerson Sunday, April 17, 2016 12:12 AM
    • Unmarked as answer by Bill_Stewart Sunday, April 17, 2016 9:29 PM
    Sunday, April 17, 2016 12:12 AM
  • Agreed.  I use this extensively for many basic operation with SQL Server.  Excellent subsystem when used within its bounds.  The error trapping sucks and for more complicated tasks I resort to .NET based code.

    PowerShell error handling is Net error handling and it is exactly the same as in any other Net language.

    You seem to have a very old V1 version of PowerShell.  Are you running on Vista?  XP?


    \_(ツ)_/

    Sunday, April 17, 2016 12:34 AM
  • What I ended up doing installing the group policy administrative templates for PowerShell and configure the policy for allow local require remote signed.

    Problem solved.


    You mark yourself as an answer.  You did not answer this question. Bill did. You altering the GP settings is NOT the answer.

    \_(ツ)_/

    Sunday, April 17, 2016 12:35 AM
  • Agreed.  I use this extensively for many basic operation with SQL Server.  Excellent subsystem when used within its bounds.  The error trapping sucks and for more complicated tasks I resort to .NET based code.

    PowerShell error handling is Net error handling and it is exactly the same as in any other Net language.

    You seem to have a very old V1 version of PowerShell.  Are you running on Vista?  XP?


    \_(ツ)_/

    Windows 7 in the case of that output. The server this is running on is Windows 2008 (might be R2). I'd have to connect to it to know for sure; not going to take the time for that, now. 
    Sunday, April 17, 2016 11:42 AM
  • What I ended up doing installing the group policy administrative templates for PowerShell and configure the policy for allow local require remote signed.

    Problem solved.


    You mark yourself as an answer.  You did not answer this question. Bill did. You altering the GP settings is NOT the answer.

    \_(ツ)_/

    Changing the GP allows me to run that PowerShell script, and any other PowerShell script on that server without having to set the execution policy when calling the script.   And, I don't have to mess with signed scripts.  So, for this situation it is the best answer.  Bill's answer does work. 
    Sunday, April 17, 2016 11:47 AM
  • Both likely have V1.  You should upgrade to V4 if you want to be compliant.  V1 is no longer supported and V2 is pretty much obsolete for most things.

    \_(ツ)_/

    Sunday, April 17, 2016 11:47 AM
  • Both likely have V1.  You should upgrade to V4 if you want to be compliant.  V1 is no longer supported and V2 is pretty much obsolete for most things.

    \_(ツ)_/

    I don't own the server. It's a client's machine. I'll make that suggestion but it's out of my control.
    Sunday, April 17, 2016 11:50 AM
  • By the way, before I forget. Thanks for the help. I do appreciate it. I'm very busy and don't like wasting time messing things that keep me from getting things done.

    Thanks, a lot,

    Greg

    Sunday, April 17, 2016 11:52 AM
  • What I ended up doing installing the group policy administrative templates for PowerShell and configure the policy for allow local require remote signed.

    Problem solved.


    You mark yourself as an answer.  You did not answer this question. Bill did. You altering the GP settings is NOT the answer.

    \_(ツ)_/

    Changing the GP allows me to run that PowerShell script, and any other PowerShell script on that server without having to set the execution policy when calling the script.   And, I don't have to mess with signed scripts.  So, for this situation it is the best answer.  Bill's answer does work. 

    But the issue with your original question was caused by incorrect use of the command line. Bill pointed that out.  His answer is the correct answer to you  question. 

    Yes.  If you set that policy in GP then you don't need to supply that switch but it does not change the reason why the original issues existed.  It just ignores it.

    Remember that the purpose of the forum is to provide answers to others who may be looking for a solution.,  The "topic" should be a clear indication of the question and the marked answer should address that issue.  Your answer does not tells us why the original issue was happening.  It was happening because of incorrect command line usage.  Bill had the answer and the proof.

    For the purposes of the forum I recommend marking Bill's answer as the correct answer.

    Thank you  and good luck with PowerShell.


    \_(ツ)_/

    Sunday, April 17, 2016 11:53 AM
  • Both likely have V1.  You should upgrade to V4 if you want to be compliant.  V1 is no longer supported and V2 is pretty much obsolete for most things.


    \_(ツ)_/

    I don't own the server. It's a client's machine. I'll make that suggestion but it's out of my control.

    Why are you doing this?  Are you an accountant or do you perform some other non-computer function?  Doesn't you client have a system administrator?

    I know that many non-techs are now trying to learn PowerShell but this situation is a bit new.  I am curious about how you came to use PowerShell as a non computer tech and for what purpose.  I am just curious as PS seems to be expanding its usability to all communities.


    \_(ツ)_/

    Sunday, April 17, 2016 11:58 AM
  • Both likely have V1.  You should upgrade to V4 if you want to be compliant.  V1 is no longer supported and V2 is pretty much obsolete for most things.


    \_(ツ)_/

    I don't own the server. It's a client's machine. I'll make that suggestion but it's out of my control.

    Why are you doing this?  Are you an accountant or do you perform some other non-computer function?  Doesn't you client have a system administrator?

    I know that many non-techs are now trying to learn PowerShell but this situation is a bit new.  I am curious about how you came to use PowerShell as a non computer tech and for what purpose.  I am just curious as PS seems to be expanding its usability to all communities.


    \_(ツ)_/

    I'm not a non-tech. That's for sure.  Mostly DBA work.  I started using PS when is was an available sub-system from within the SQL Server Agent job scheduler (SQL Server 2008, I think).  Gave me a reason to throw out all the vb scripts I was using to manipulate database backups files and push them off to DR servers and such.  The PowerShell scripts run in process (don't have to be signed) and makes things much easier. 

    I do a fair amount of c# coding centered around identity management (ILM/FIM/MIM).  Not really an apps guy, professionally.  I'll write app for my own internal use, but not for release to clients.  I use PowerShell in the identity management realm to kick off the management agents from task scheduler and to provision Exchange (not really happy that I have to use PowerShell for that). 

    I'm not a big fan of scripting as a way to accomplish something complex.  I find it easier to whip up a .NET solution.  The new PowerShell ISE seems pretty cool, but I don't have a need to take the time to mess with it too much. 

    Like all tools, there are tasks they are suited well for and others, not. 

    I can't get into the client's environment, but my main contact is their IT sys admin. Their server guy(s) are quite competent.

    I accomplished my goal.  If I could get a dumb, stupid PS script to run by <right click - run with PowerShell), I would be good to go.  I needed the ability run a PowerShell script from within the task scheduler under a particular domain credential.  You guys helped me figure that out (even though I kind of answered my own question).  And, I don't have to sign the damned thing!

    Thanks,

    Greg

    Sunday, April 17, 2016 12:42 PM
  • I was going to say database but hit submit before it hitmy brain.

    If you are a dba on SQLServer or Oracle then definitely get as much background in PS as possible.  I am a developer and a DBA and have used PS since the first preview.  It is enormously helpful.  What I used to do with C# to analyze/fix databases I now do at a prompt and in much less time.

    Here are some demo scripts that I posted for others as a starter and help for learning with PowerShell and data.

    https://onedrive.live.com/redir?resid=BF32AB14D23EA238!13702&authkey=!ALvRzH5pF65IAQY&ithint=folder%2cps1


    \_(ツ)_/

    Sunday, April 17, 2016 1:23 PM
  • That is NOT listed in the PowerShell.exe /? text.

    That's correct, a small oversight for the powershell.exe /? help in v2. MS updated the /? description for v3 and later to make the parsing rules more explicit. That's why I posted the help text directly from v3. The updated help is also listed in the online version which is easily searchable.


    -- Bill Stewart [Bill_Stewart]


    • Edited by Bill_Stewart Monday, April 18, 2016 3:50 AM
    • Proposed as answer by Bill_Stewart Monday, April 18, 2016 2:43 PM
    • Marked as answer by Bill_Stewart Thursday, June 2, 2016 9:02 PM
    Monday, April 18, 2016 3:45 AM