Here are 2 equivalent code samples, the only difference is that first sample uses function while other does not.
This code fails, because function returns invalid object:
function Initialize-Table
{
param (
[parameter(Mandatory = $false)]
[string] $TableName = "InstallationTable"
)
# Create Table object
$InstallTable = New-Object System.Data.DataTable "$TableName"
# Define Columns
$UserColumn = New-Object System.Data.DataColumn User, ([string])
$InstallColumn = New-Object System.Data.DataColumn InstallRoot, ([string])
# Add the Columns
$InstallTable.Columns.Add($UserColumn)
$InstallTable.Columns.Add($InstallColumn)
return $InstallTable
}
Write-Host "Initialize-Table"
Write-Host "***************************"
$InstallTable = Initialize-Table
if (!$InstallTable)
{
Write-Warning "Table not initialized"
exit
}
However following is exactly the same, except that function code is put directly into script, and the table is valid!
Write-Host "Initialize-Table"
Write-Host "***************************"
$TableName = "InstallationTable"
# Create Table object
$InstallTable = New-Object System.Data.DataTable "$TableName"
# Define Columns
$UserColumn = New-Object System.Data.DataColumn User, ([string])
$InstallColumn = New-Object System.Data.DataColumn InstallRoot, ([string])
# Add the Columns
$InstallTable.Columns.Add($UserColumn)
$InstallTable.Columns.Add($InstallColumn)
if (!$InstallTable)
{
Write-Warning "Table not initialized"
exit
}
Why my function does not work (first sample)? it's the same damn code.
if(!$InstallTable)check fails, and I'm unable to use the variable to write and read data into the table.returnmeans write to stdout. (so powershell tries to write NET object to console) in every programming languagereturndoes exactly what it's name implies, but herereturnmeanno return