如何在脚本中运行 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
转到文档并查看您是否已有 WindowsPowerShell 目录。我没有,所以
> cd \Users\jowers\Documents
> mkdir WindowsPowerShell
> cd WindowsPowerShell
> type file > Microsoft.PowerShellISE_profile.ps1
我们现在已经创建了每次打开 PowerShell 应用程序时都会启动的脚本。
我们这样做的原因是我们可以添加自己的文件夹来保存我们所有的自定义脚本。让我们创建那个文件夹,我将在 Mac/Linux 保存其脚本的目录之后将其命名为“Bin”。
> mkdir \Users\jowers\Bin
现在我们希望每次打开应用时将该目录添加到我们的 $env:path 变量中,因此请返回 WindowsPowerShell 目录并
> start Microsoft.PowerShellISE_profile.ps1
然后添加这个
$env:path += ";\Users\jowers\Bin"
现在,只要您将脚本保存在那个“Bin”目录中,shell 就会自动找到您的命令。
重新启动 powershell,它应该是最先执行的脚本之一。
重新加载后在命令行上运行此命令以查看路径变量中的新目录:
> $env:Path
现在我们可以从命令行或从另一个脚本中调用我们的脚本,就像这样:
$(customScript.ps1 arg1 arg2 ...)
如您所见,我们必须使用扩展名.ps1 调用它们,直到我们为它们创建别名。如果我们想变得花哨。