基本的PowerShell功能无输出 [英] No output with basic PowerShell function

查看:102
本文介绍了基本的PowerShell功能无输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

距我刚开始与PowerShell相处已经有一段时间了,到今天我可以说我已经完成了很多日常任务.每天在学校都是新的一天,而现在,当我开始使用各种功能时,我又一次跌跌撞撞...这是我的问题:

It's already a while since I just started to get along with PowerShell and by today I can say I get many things for my daily tasks done. Everyday is a new day at school though and now, while I was starting to work with functions, I stumble again... Here is my problem:

即使使用许多初学者教程中最简单的功能,它也无法在我的工作PC,家用PC或工作的管理服务器上运行.

Even with the simplest function taken from many beginner's tutorials it is not working on my work PC nor on my home PC nor on my work's admin servers.

例如:

function MyDate {
    Get-Date
}

将名称为MyDate.ps1的PS1文件保存到本地文件夹,然后从PowerShell提示符运行这样的小东西

Saved the PS1 file with the name MyDate.ps1 to a local folder and just run this tiny little thing from the PowerShell prompt like that

PS C:\PS> C:\PS\MyDate.ps1

这就是PS-Functions-for-Dummies教程中确切解释的方式.仅在本教程中,输出应显示日期.在我看来,什么都没有.没有错误,没有关于红色PS的特定信息,什么都没有!如果我在这样的完整脚本中使用该函数:

That's how it was exactly explained in a PS-Functions-for-Dummies tutorial. Just in the tutorial the output should show the date. In my siutation there is just nothing. No error, no red-PS-specific information, nothing! If I use the function within my full script like that:

function MyDate {
    Get-Date
}
MyDate

PS C:\PS> C:\PS\MyDate.ps1

Montag, 1. Oktober 2018 19:28:32

好吧,然后我得到了日期输出.想知道为什么不直接在提示符下不调用脚本内的函数,因为应该使用函数吗?同样,在许多这些非常简单的示例中,它应该可以工作.那我在哪里错了?

Well, then I get the date output. Wondering why not directly from the prompt without calling the function within the script, as functions are supposed to be used? And again, in many of these pretty simple examples it is supposed to work.. Where am I wrong then?

编辑:不确定现在是否是向问题添加更多更新的正确策略?

Not sure if this is now the right policy to add more updates to a question?

我可能会分享一个更具体的脚本示例,以及我想如何将其转换"为一个函数.简短的例子是:

I will probably share a more specific example of my scripts and how I want to "transform" it into a function. Short example would be:

$myServers = Get-Content D:\Servers\Windows2016.txt
foreach ($myServer in $myServers) {
    Get-Printer -ComputerName $myServer |
        Where-Object {$_.DeviceType -eq "Printer"} |
        Select Name, PortName
}

对于其他支持团队,它必须尽可能简单.所以我的想法是围绕这几行包装"一个函数,以便另一个人可以像这样执行它

For other support teams it has to be as simple as possible. So my idea was to "wrap" a function around these few lines, so that another person would execute it like this

C:\Scripts\Our-Printers -File D:\Servers\Windows2016.txt

这样,

Our-Printers 当然就是我的函数名称.

Our-Printers would then be my function name of course.

我已经尝试过了,但是却丢弃了这些东西,尽管它在第一次尝试中不起作用,这就是为什么我想从一些基本的东西开始,而现在看来我不明白.但是,顺便说一句,在脚本中我的函数已经起作用了,只是它们没有以示例的方式要求输入.这意味着我可以在大型脚本中定义函数,并可以根据用户输入更改顺序甚至跳过某些函数...

I tried that already but discarded the stuff though as it did not work in first try, that's why I wanted to start with pretty basic stuff and at the moment it seems that I don't get it. But by the way, within a script my functions worked already, just they are not made to require input in that way of the example. Which means I defined functions in a large script and with that I am able to change orders or even skip certain functions based on user input...

推荐答案

在脚本中定义函数意味着您编写了可以通过符号名称调用的代码块.但是,该功能不会通过运行脚本自动调用.您实际上仍然需要这样做.

Defining a function in a script means you write a block of code that can be invoked via a symbolic name. The function is not automatically invoked by running the script, though. You still need to actually do that.


PS C:\> Get-Content .\a.ps1
function GetDate {
    Get-Date
}
PS C:\> .\a.ps1
PS C:\> Get-Content .\b.ps1
function GetDate {
    Get-Date
}
GetDate                  # ← actually invoke the function
PS C:\> .\b.ps1

Montag, 1. Oktober 2018 19:50:32

调用脚本时,仅会自动执行脚本中的(脚本-)全局作用域代码.

Only (script-)global scope code in a script is executed automatically when the script is invoked.

取决于脚本的目的,这可能不是您想要的.例如,如果您打算仅从某个外部脚本或命令运行该脚本以使其执行某些操作,则在执行脚本时自动调用该函数是有意义的.另一方面,如果您打算将该脚本用作一种库,并存储希望分别调用的不同函数,则可以从脚本中忽略函数调用.然后,您可以按Mathias的描述点对脚本源,并调用所需的功能.

Depending on the purpose of your script this may or may not be what you want. For instance, if you intend to just run the script from some external script or command to have it do something it makes sense to automatically invoke the function when the script is executed. If on the other hand you intend to use the script as a kind of library, storing different functions that you want to be able to invoke separately, you'd omit function invocations from the script. Then you can dot-source the script as Mathias described and invoke the function(s) you need.


PS C:\> Get-Content .\a.ps1
function GetDate {
    Get-Date
}
PS C:\> . .\a.ps1    # ← load the function definition into the current scope
PS C:\> GetDate      # ← actually invoke the function

Montag, 1. Oktober 2018 19:50:32


编辑:您的最终目标可以通过任何一种方式实现.有文件(称为 profiles ),那么PowerShell会在启动时自动提供资源.您可以定义一个函数并将其放在适当的配置文件中(针对每个用户或整个系统).重新启动PowerShell之后,人们便可以调用该功能.


Your ultimate goal could be achieved either way. There are files (called profiles) that PowerShell sources automatically when launched. You could define a function and put that in the appropriate profile (per user or system-wide). After restarting PowerShell people will then be able to invoke the function.

或者,您可以将代码放在脚本中(而无需将其包装在函数中),然后将该脚本放在目标用户可以执行它的位置.

Alternatively you could put the code in a script (without wrapping it in a function), and put that script someplace where the intended users can execute it.

这两种方法中哪种更适合您的情况取决于许多因素.您有一个域或工作组吗?如果是域,您可以对AD进行更改吗?您是否拥有可以放置文件的共享位置?您有软件部署系统吗?依此类推.

Which of these two approaches is preferable for your situation depends on a number of factors. Do you have an domain or a workgroup? In case of a domain, can you make changes to the AD? Do you have a shared location where you could put files? Do you have a software deployment system? And so on.

另一个重要的问题是:用户将仅从PowerShell还是从其他地方(例如CMD)调用代码.如果是后者,通常更喜欢脚本而不是配置文件中的功能.

Another important question is: will the users invoke the code just from PowerShell or also from elsewhere (e.g. CMD). In case of the latter one would normally prefer a script over a function in a profile.

以任何一种方式

Either way you'd parametrize your script or function like this:

[CmdletBinding()]
Param(
    [Parameter(Mandatory=$true)]
    [string]$File
)

$myServers = Get-Content $File
foreach ($myServer in $myServers) {
    Get-Printer -ComputerName $myServer |
        Where-Object {$_.DeviceType -eq "Printer"} |
        Select-Object Name, PortName
}

参数定义分别位于脚本或函数的开头.

The parameter definition belongs at the beginning of the script or function respectively.

添加基于注释的帮助,以便人们可以运行获取帮助我们的打印机我们的打印机-?,以了解他们应该如何使用它,例如

Add comment-based help, so that people can run Get-Help Our-Printers or Our-Printers -? to see how they're supposed to use it, e.g.

<#
.SYNOPSIS
List printers.

.DESCRIPTION
List printers. The computers to check are read from a file.

.PARAMETER File
A file with a list of computer names (one per line).
#>

使用参数验证,用于强制输入有效,例如

Use parameter validation for enforcing valid input, e.g.

[CmdletBinding()]
Param(
    [Parameter(Mandatory=$true)]
    [ValidateScript({Test-Path -LiteralPath $_})]
    [string]$File
)

这篇关于基本的PowerShell功能无输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆