Call PowerShell script PS1 from another PS1 script inside Powershell ISE

后端 未结 11 1059
伪装坚强ぢ
伪装坚强ぢ 2020-12-12 15:27

I want call execution for a myScript1.ps1 script inside a second myScript2.ps1 script inside Powershell ISE.

The following code inside MyScript2.ps1, works fine from

11条回答
  •  醉梦人生
    2020-12-12 15:46

    How do you run PowerShell built-in scripts inside of your scripts?

    How do you use built-in scripts like

    Get-Location
    pwd
    ls
    dir
    split-path
    ::etc...
    

    Those are ran by your computer, automatically checking the path of the script.

    Similarly, I can run my custom scripts by just putting the name of the script in the script-block

    ::sid.ps1 is a PS script I made to find the SID of any user
    ::it takes one argument, that argument would be the username
    echo $(sid.ps1 jowers)
    
    
    (returns something like)> S-X-X-XXXXXXXX-XXXXXXXXXX-XXX-XXXX
    
    
    $(sid.ps1 jowers).Replace("S","X")
    
    (returns same as above but with X instead of S)
    

    Go on to the powershell command line and type

    > $profile
    

    This will return the path to a file that our PowerShell command line will execute every time you open the app.

    It will look like this

    C:\Users\jowers\OneDrive\Documents\WindowsPowerShell\Microsoft.PowerShellISE_profile.ps1
    

    Go to Documents and see if you already have a WindowsPowerShell directory. I didn't, so

    > cd \Users\jowers\Documents
    > mkdir WindowsPowerShell
    > cd WindowsPowerShell
    > type file > Microsoft.PowerShellISE_profile.ps1
    

    We've now created the script that will launch every time we open the PowerShell App.

    The reason we did that was so that we could add our own folder that holds all of our custom scripts. Let's create that folder and I'll name it "Bin" after the directories that Mac/Linux hold its scripts in.

    > mkdir \Users\jowers\Bin
    

    Now we want that directory to be added to our $env:path variable every time we open the app so go back to the WindowsPowerShell Directory and

    > start Microsoft.PowerShellISE_profile.ps1
    

    Then add this

    $env:path += ";\Users\jowers\Bin"
    

    Now the shell will automatically find your commands, as long as you save your scripts in that "Bin" directory.

    Relaunch the powershell and it should be one of the first scripts that execute.

    Run this on the command line after reloading to see your new directory in your path variable:

    > $env:Path
    

    Now we can call our scripts from the command line or from within another script as simply as this:

    $(customScript.ps1 arg1 arg2 ...)
    

    As you see we must call them with the .ps1 extension until we make aliases for them. If we want to get fancy.

提交回复
热议问题