无法获得在PowerShell中
问题描述:
我想从其中包含2个值函数的值从函数值,一个是从目前的方法指出,另一个值是null
。无法获得在PowerShell中
我想到的是打印出从功能$convertAccountEx
价值,但它给我什么。我曾尝试给$convertAccountEx
的$null
值,但没有任何变化。
function ConvertTo-Date(){
Param ($accountEx,$convertAccountEx)
if($accountEx.accountExpires -eq 0){
$convertAccountEx = "Never"
}
else{
$convertAccountEx = [DateTime]::FromFileTime($AccountEx.accountExpires)
}
}
$userObjects = $ADSearch.FindAll()
foreach ($user in $userObjects){
$accountEx = $user.Properties.Item("accountExpires")
ConvertTo-Date -accountEx $accountEx.accountExpires -convertAccountEx $convertAccountEx
$convertAccountEx
}
答
您的代码应该是这样的:
function ConvertTo-Date(){
Param ($accountEx)
if($accountEx.accountExpires -eq 0){
$convertAccountEx = "Never"
}
else{
$convertAccountEx = [DateTime]::FromFileTime($AccountEx.accountExpires)
}
$convertAccountEx
}
$userObjects = $ADSearch.FindAll()
foreach ($user in $userObjects){
$accountEx = $user.Properties.Item("accountExpires")
ConvertTo-Date -accountEx $accountEx.accountExpires
}
你遇到了被称为作用域的问题。这个想法是,你创建的每个变量都应该独立于其运行范围。因此,根据定义,函数中的var是一个与外部不同的var,即使它们共享该名称。在你的例子中解决这个问题的一个简单方法是,只需要返回你函数的值(通过调用它)。
我会建议是:不要只返回值,但它附加到您创建的对象。这里有一个(真的)简单的例子:
function Add-Info {
Param($user)
$user | Add-Member -NotePropertyName NewProperty -NotePropertyValue 'SomeValue'
$user
}
非常感谢您的真实答案。我试图让它在函数内部得到结果。但这不是我的想法。嗯,我会进一步思考这个问题。 – Ender
ü可以使用'$全球:convertAccountEx',然后它会在全球上市 –
技术上是真实的,但我想这归类为不良编码。 – restless1987