我正在编写一个函数来创建一个名为$Credentials
的变量,我在另一个函数中使用它来验证它是否有效。通过在函数中使用return $Credentials
,我希望变量在Function Import-Password
运行后可用,但事实并非如此......
我认为这可以通过使用$script:Credentials
来解决,但如果函数可以输出此变量,我认为不需要它。
感谢您的帮助。
功能导入密码
# Check the password file
Function Import-Password ($UserName,$PasswordFile,[switch]$SendMail) {
try {
if (!(Test-Path $PasswordFile)) {
Write-Host "$env:COMPUTERNAME > Check password file: $PasswordFile > The password file can not be found`n
- Password file :`t $PasswordFile
- Server name :`t $env:COMPUTERNAME" -ForegroundColor Yellow
if ($SendMail) {
Send-Mail "FAILED AD Authentication" "The password file can not be found" "- Password file : $PasswordFile<br>- Server name : $env:COMPUTERNAME"
}
break
}
$Password = cat $PasswordFile | ConvertTo-SecureString -Force -ErrorAction Stop
$Credentials = New-Object System.Management.Automation.PSCredential -ArgumentList $UserName,$Password
return $Credentials
}
catch {
Write-Host "$env:COMPUTERNAME > Check password file: $PasswordFile > The password has been hashed with another account than the account used to run this script (all 3 users/owners need to be the same)`n
- Script account:`t $env:USERDNSDOMAIN\$env:USERNAME
- Password user :`t $UserName
- Password file :`t $PasswordFile
" -ForegroundColor Yellow
if ($SendMail) {
Send-Mail "FAILED AD Authentication" "The password has been hashed with another account than the account used to run this script (all 3 users/owners need to be the same)" "- Script account: $env:USERDNSDOMAIN\$env:USERNAME<br>- Password user : $UserName<br>- Password file : $PasswordFile"
}
break
}
}
Import-Password $UserName $PasswordFile
答案 0 :(得分:5)
您必须捕获函数的输出,以便稍后在您的脚本中使用它,例如:
$cred = Import-Password $UserName $PasswordFile