[英]Passing arguments to a function
I found this link for creating vss Shadow copies under Windows.我在 Windows 下找到了用于创建 vss 影子副本的链接。 But the code uses fixed strings for the parameters:但是代码使用固定字符串作为参数:
function createVssSnapshot{
[cmdletbinding()]
param(
[string]$targetVolume="C:\",
[string]$accessPath='C:\vssSnapshot',
[bool]$openSnapshotAfter=$true
)
[..]
I'd like to modify it in order to be more flexible:我想修改它以更灵活:
function [String]createVssSnapshot{
[cmdletbinding()]
param(
[String]$targetVolume,
[String]$accessPath,
[Bool]$openSnapshotAfter
)
[..]
and call it using并使用
$result = createVssSnapshot("C:\", "C:\vssSnapshot", $false)
But I get the following error:但我收到以下错误:
createVssSnapshot : Die Argumenttransformation für den Parameter "targetVolume" kann nicht verarbeitet werden. Der Wert kann nicht in den Typ "System.String" konvertiert werden.
In F:\Powershell_4_Pure\Object_based.ps1:143 Zeichen:28
+ $result = createVssSnapshot("C:\", "C:\vssSnapshot", $false)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidData: (:) [createVssSnapshot], ParameterBindingArgumentTransformationException
+ FullyQualifiedErrorId : ParameterArgumentTransformationError,createVssSnapshot
Sorry for German error message, but it seems targetVolume isn't of type System.String.很抱歉出现德语错误消息,但似乎 targetVolume 不是 System.String 类型。
What am I missing here?我在这里想念什么?
For future questions: How can I modify PowerShell ISE to have english error messages?对于未来的问题:如何修改 PowerShell ISE 以获得英文错误消息?
In PowerShell, parameter arguments are passed to command by name or position , but arguments for separate parameters are NOT separated by comma (unlike many C-like languages).在PowerShell中,参数arguments通过名称传递给命令
The correct way to pass the arguments shown would be:通过所示 arguments 的正确方法是:
$result = createVssSnapshot "C:\" "C:\vssSnapshot" -openSnapshotAfter:$false
I'd strongly suggest changing the type constraint on the $openSnapshotAfter
parameter to a [switch]
instead of a [bool]
- it will always default to $false
and you can then specify it by just doing -openSnapshotAfter
instead of -openSnapshotAfter:$true
.我强烈建议将$openSnapshotAfter
参数上的类型约束更改为[switch]
而不是[bool]
- 它始终默认为$false
,然后您可以通过执行-openSnapshotAfter
而不是-openSnapshotAfter:$true
来指定它-openSnapshotAfter:$true
。
Since you'll no longer be providing default values for the first 2 parameters, I'd also recommend marking those Mandatory
- this way PowerShell will refuse to een attempt executing your function if the caller doesn't pass arguments for those:由于您将不再为前 2 个参数提供默认值,因此我还建议您将其标记为Mandatory
- 这样 PowerShell 将拒绝尝试执行您的 function 如果调用者没有通过 ZDBC11CAABD5BDA99FDZE6F14Z 那些:
function New-VssSnapshot {
[CmdletBinding()]
param(
[Parameter(Mandatory)]
[string]$TargetVolume,
[Parameter(Mandatory)]
[string]$AccessPath,
[switch]$OpenSnapshotAfter
)
# ...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.