如何在脚本中运行PowerShell内置脚本?
如何使用内置脚本
Get-Location
pwd
ls
dir
split-path
::etc...
它们由您的计算机运行,自动检查脚本的路径。
类似地,我可以通过在脚本块中放入脚本名来运行自定义脚本
::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)
继续到powershell命令行并键入
> $profile
这将返回每次打开应用程序时PowerShell命令行将执行的文件的路径。
就像这样
C:\Users\jowers\OneDrive\Documents\WindowsPowerShell\Microsoft.PowerShellISE_profile.ps1
转到Documents,查看是否已经有WindowsPowerShell目录。我没有,所以
> cd \Users\jowers\Documents
> mkdir WindowsPowerShell
> cd WindowsPowerShell
> type file > Microsoft.PowerShellISE_profile.ps1
现在,我们已经创建了每次打开PowerShell应用程序时都会启动的脚本。
这样做的原因是,我们可以添加自己的文件夹,其中包含所有自定义脚本。让我们创建这个文件夹,我将其命名为“Bin”,以Mac/Linux保存脚本的目录命名。
> mkdir \Users\jowers\Bin
现在我们想要在每次打开应用程序时将该目录添加到$env:path变量中,因此返回到WindowsPowerShell目录并
> start Microsoft.PowerShellISE_profile.ps1
然后加上这个
$env:path += ";\Users\jowers\Bin"
现在,只要您将脚本保存在“Bin”目录中,shell就会自动找到您的命令。
重新启动powershell,它应该是第一个执行的脚本之一。
重新加载后在命令行上运行这个命令,在你的path变量中看到你的新目录:
> $env:Path
现在我们可以从命令行或从另一个脚本中调用脚本,简单如下:
$(customScript.ps1 arg1 arg2 ...)
如您所见,我们必须使用.ps1扩展名来调用它们,直到我们为它们创建别名。如果我们想变得更花哨。