# Function not handling variable correctly

**URL:** <https://forums.powershell.org/t/function-not-handling-variable-correctly/25955>\
**Category:** PowerShell Help\
**Created:** [June 24, 2025, 3:40pm UTC](https://forums.powershell.org/t/function-not-handling-variable-correctly/25955 "2025-06-24T15:40:57Z")\
**Posts on this page:** 15\
**Page:** 1

<div class="post-metadata">

**Author:** ![kkoop](https://avatars.discourse-cdn.com/v4/letter/k/48db29/32.png) [@kkoop](https://forums.powershell.org/u/kkoop)\
**Post date:** [June 24, 2025, 3:40pm UTC](https://forums.powershell.org/t/function-not-handling-variable-correctly/25955/1 "2025-06-24T15:40:57Z")

</div>

I have this function in my script:

```auto
function writeLog {
Param ([string]$LogString)
	$Stamp = (Get-Date).toString("yyyy/MM/dd HH:mm:ss")
	$LogMessage = "$Stamp $LogString"
	Add-content $writeLogFile -value $LogMessage
}

```

In my PS code, I collect a user’s name into the variable:

```auto
$Mgrname

```

and I collect his Direct Reports into the variable:

`$CrewList`

Then, I write the information to the console (through another function which is working fine) and to a text file via the function above:

```auto
writeColor -text " $Mgrname ($Manager) ","DirectReports are:" -color yellow,green
$CurrentCrew

writeLog " $Mgrname current crew is: "
writeLog $CurrentCrew

```

The screen output looks like this:

> Bob Peters (btpeters) DirectReports are:
> 
> Name
> 
> SgPMIE TestUser II  
> SG PMTest 1

However, the output into the log file looks like this:

![image](https://us1.discourse-cdn.com/flex019/uploads/powershell/original/2X/b/bbdfb46809ea5eef5a34f50faab6ad479383a383.png)

Can’t seem to figure out what I’m doing that drops the data out of

```auto
$Crewlist

```

going into the `writeLog` function

Here’s how I’m getting the Direct Reports names:

```auto
$CurrentCrew = get-aduser $Manager -properties * | select-object -expandproperty directreports| ForEach-Object { Get-ADUser -Identity $_ | Select-Object Name }

```

Suggestions anyone?

Thanks!

---

<div class="post-metadata">

**Author:** ![Olaf](https://sea1.discourse-cdn.com/flex019/user_avatar/forums.powershell.org/olaf/32/992_2.png) [@Olaf](https://forums.powershell.org/u/Olaf)\
**Post date:** [June 24, 2025, 4:23pm UTC](https://forums.powershell.org/t/function-not-handling-variable-correctly/25955/2 "2025-06-24T16:23:32Z")

</div>

Where do you define the variable `$writeLogFile` you use in your `writeLog` function? You should not use _outside_ variables inside of functions!! ☝

And since you’re getting objects from your query but needing strings for your function you should use `writeLog $CurrentCrew.Name` to get only the names without the _header_ for your function.

BTW: There are some great solutions for logging out there already. You don’t have to re-invent the wheel again. One of the more famous ones is

> **[Welcome to the PowerShell Framework](https://psframework.org/)**
>
> The project dedicated to empowering your PowerShell scripting.

---

<div class="post-metadata">

**Author:** ![kkoop](https://avatars.discourse-cdn.com/v4/letter/k/48db29/32.png) [@kkoop](https://forums.powershell.org/u/kkoop)\
**Post date:** [June 24, 2025, 4:38pm UTC](https://forums.powershell.org/t/function-not-handling-variable-correctly/25955/3 "2025-06-24T16:38:59Z")

</div>

Thanks, Olaf.

The logfile is defined just before the script lines I quoted and looks like this:

```auto
$writeLogFile = "c:\utils\Logs\NewCrew-$Manager.log"

```

I didn’t include it in the OP because it works as expected, and seemed extraneous. Anyway, I found the text logging function a long time ago and just have it in a template that I use for scripting. It’s been working great except for this one thing.

Would you clarify what _outside_ variable is? I’m still learning PS.

I’ll give your `writeLog` suggestion a try, but the header in the text log is fine with me.

Re-inventing was not a plan, just happened when this function was first thing I found to do what I was looking for in logging what my scripts do.

I appreciate your input and will let you know what the `writeLog` suggestion does.

---

<div class="post-metadata">

**Author:** ![kkoop](https://avatars.discourse-cdn.com/v4/letter/k/48db29/32.png) [@kkoop](https://forums.powershell.org/u/kkoop)\
**Post date:** [June 24, 2025, 4:46pm UTC](https://forums.powershell.org/t/function-not-handling-variable-correctly/25955/4 "2025-06-24T16:46:08Z")

</div>

Progress:

Changed to

```auto
writeLog " $Mgrname current crew is: "
writeLog $CurrentCrew.name

```

And now get this in the text log:

 ![image](https://us1.discourse-cdn.com/flex019/uploads/powershell/original/2X/f/f5b8d9fb60b30574301fa0af0cd2d1aeafde33e6.png)

If I can get a CRLF after each name, I’m in like Flynn

---

<div class="post-metadata">

**Author:** ![Olaf](https://sea1.discourse-cdn.com/flex019/user_avatar/forums.powershell.org/olaf/32/992_2.png) [@Olaf](https://forums.powershell.org/u/Olaf)\
**Post date:** [June 24, 2025, 4:47pm UTC](https://forums.powershell.org/t/function-not-handling-variable-correctly/25955/5 "2025-06-24T16:47:10Z")

</div>

> [@kkoop](#):
>
> Would you clarify what _outside_ variable is? I’m still learning PS.

> **[about\_Scopes - PowerShell](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_scopes?view=powershell-7.5)**
>
> Explains the concept of scope in PowerShell and shows how to set and change the scope of elements.

While it might not be an issue for you now it can cause hard to find errors when your code gets more complex. In general: inside a function you should only use variables you defined inside the function. If you want to use resources from outside a function you should pass it to it as parameter.

---

<div class="post-metadata">

**Author:** ![Olaf](https://sea1.discourse-cdn.com/flex019/user_avatar/forums.powershell.org/olaf/32/992_2.png) [@Olaf](https://forums.powershell.org/u/Olaf)\
**Post date:** [June 24, 2025, 4:50pm UTC](https://forums.powershell.org/t/function-not-handling-variable-correctly/25955/6 "2025-06-24T16:50:45Z")

</div>

> [@kkoop](#):
>
> If I can get a CRLF after each name

I’m not sure if that works / looks good … try

```auto
writeLog ($CurrentCrew.name -join "`n`r")  

```

I’d prefer

```auto
writeLog ($CurrentCrew.name -join ', ')

```

---

<div class="post-metadata">

**Author:** ![kkoop](https://avatars.discourse-cdn.com/v4/letter/k/48db29/32.png) [@kkoop](https://forums.powershell.org/u/kkoop)\
**Post date:** [June 24, 2025, 5:07pm UTC](https://forums.powershell.org/t/function-not-handling-variable-correctly/25955/7 "2025-06-24T17:07:03Z")

</div>

More progress, thank you!

The comma - ', ’ - is okay for short lists, but some of my guys have a dozen Direct Reports

So, I did this

```auto
writeLog " $Mgrname current crew is: "
writeLog ($CurrentCrew.name -join "`n ")

```

And got this:

 ![image](https://us1.discourse-cdn.com/flex019/uploads/powershell/original/2X/6/6b102c60ec55f25a39eeab213ebacac3dde4e26a.png)

So now it seems that to be **truly** in like Flynn I need a CR before the first name, and write it like this:

 ![image](https://us1.discourse-cdn.com/flex019/uploads/powershell/original/2X/1/1b17326099e24dc3344229c06d201163f420c250.png)

(and thanks, also, for the instructional link)

---

<div class="post-metadata">

**Author:** ![Olaf](https://sea1.discourse-cdn.com/flex019/user_avatar/forums.powershell.org/olaf/32/992_2.png) [@Olaf](https://forums.powershell.org/u/Olaf)\
**Post date:** [June 24, 2025, 5:17pm UTC](https://forums.powershell.org/t/function-not-handling-variable-correctly/25955/8 "2025-06-24T17:17:18Z")

</div>

> [@kkoop](#):
>
> The comma - ', ’ - is okay for short lists, but some of my guys have a dozen Direct Reports

I don’t know what you’re using the log files for but if it’s about collecting data you may look into other options. IMHO the purpose of log files is to help with finding errors. If you need to store information for later you may collect data as structured data in CSV files for example.

---

<div class="post-metadata">

**Author:** ![kkoop](https://avatars.discourse-cdn.com/v4/letter/k/48db29/32.png) [@kkoop](https://forums.powershell.org/u/kkoop)\
**Post date:** [June 24, 2025, 5:20pm UTC](https://forums.powershell.org/t/function-not-handling-variable-correctly/25955/9 "2025-06-24T17:20:31Z")

</div>

It’s not formal logging like, for example, court testimony. Just for my record on what I’m getting done and when. Specifically this time, I have to make some changes to direct reports and want to collect before and after info.  
If it gets more serious, I will record CSV information - which I do have a bit of experience with in PS - but for now a simple text file is sufficient.

---

<div class="post-metadata">

**Author:** ![kkoop](https://avatars.discourse-cdn.com/v4/letter/k/48db29/32.png) [@kkoop](https://forums.powershell.org/u/kkoop)\
**Post date:** [June 24, 2025, 6:21pm UTC](https://forums.powershell.org/t/function-not-handling-variable-correctly/25955/10 "2025-06-24T18:21:45Z")

</div>

Success!! Thank you Olaf. Got me on the right track and I have exactly what I wanted:

```auto
writeLog " $Mgrname current crew is: "
writeLog ("`n" + ($CurrentCrew.name -join "`n"))

```

Writes the log file like this:

 ![image](https://us1.discourse-cdn.com/flex019/uploads/powershell/original/2X/3/344197e3e4c665c820058f286f06556b0df5a3e8.png)

---

<div class="post-metadata">

**Author:** ![grey0ut](https://sea1.discourse-cdn.com/flex019/user_avatar/forums.powershell.org/grey0ut/32/5310_2.png) [@grey0ut](https://forums.powershell.org/u/grey0ut)\
**Post date:** [June 24, 2025, 6:51pm UTC](https://forums.powershell.org/t/function-not-handling-variable-correctly/25955/11 "2025-06-24T18:51:17Z")

</div>

I’m on mobile so forgive my lack of examples but you may try using Out-File instead of Add-Content because of the way it handles writing objects.

---

<div class="post-metadata">

**Author:** ![kkoop](https://avatars.discourse-cdn.com/v4/letter/k/48db29/32.png) [@kkoop](https://forums.powershell.org/u/kkoop)\
**Post date:** [June 24, 2025, 7:11pm UTC](https://forums.powershell.org/t/function-not-handling-variable-correctly/25955/12 "2025-06-24T19:11:09Z")

</div>

That’s an interesting idea. I’ll play around with that and see how it differs.

Thanks for the suggestion!

---

<div class="post-metadata">

**Author:** ![grey0ut](https://sea1.discourse-cdn.com/flex019/user_avatar/forums.powershell.org/grey0ut/32/5310_2.png) [@grey0ut](https://forums.powershell.org/u/grey0ut)\
**Post date:** [June 24, 2025, 10:45pm UTC](https://forums.powershell.org/t/function-not-handling-variable-correctly/25955/13 "2025-06-24T22:45:42Z")

</div>

Followup now that I’m on a computer.  
When you’ve got an array of just values, like this:

```auto
$Crew = @(
    "John",
    "Bob",
    "OtherBob",
    "Janet"
)

```

Whether you use Add-Content or Out-File if you’re just passing that array as the input the end result is that the values are written one by one on separate lines in the text file looking like this:

```auto
John
Bob
OtherBob
Janet

```

However, if you try to combine your date string with any kind of variable inside double-quotes you’re now trying to convert whatever is in that variable to some kind of string. If I just wrap $Crew in quotes you can see this is similar to what you were getting:

```auto
PS> "$Crew"
John Bob OtherBob Janet

```

When I ran in to this, what I decided to do if I knew I was trying specifically to write something other than a string (i.e. an object with multiple properties) to a file I would write my date string on its own line with a declaration that what follows is “Object Output” and then write my object variable by itself using Out-File.  
Let’s look at an array of objects that have two properties as an example:

```Powershell
PS> $Users

Name Title
---- -----
John Worker
Bob Worker
OtherBob Worker
Janet Worker

```

If I wanted to record that variable to a text file and have it look the same way the console output does, I would use Out-File.

```Powershell
function Write-LogObject {
    param (
        $InputObject
        )
	$Stamp = (Get-Date).toString("yyyy/MM/dd HH:mm:ss")
    Out-File -FilePath $WriteLogFile -InputObject "$Stamp Output Object:" -Append
	Out-File -FilePath $WriteLogFile -InputObject $InputObject -Append
}

PS> Write-LogObject $Users

```

and now the text file will look like this:

```auto
2025/06/24 15:44:15 Output Object:

Name Title 
---- ----- 
John Worker
Bob Worker
OtherBob Worker
Janet Worker

```

Out-File has different parameters than Add-Content so double-check if you’re going to switch up your code.

---

<div class="post-metadata">

**Author:** ![kkoop](https://avatars.discourse-cdn.com/v4/letter/k/48db29/32.png) [@kkoop](https://forums.powershell.org/u/kkoop)\
**Post date:** [June 25, 2025, 11:17am UTC](https://forums.powershell.org/t/function-not-handling-variable-correctly/25955/14 "2025-06-25T11:17:03Z")

</div>

Thanks, Grey! That’s a really nice solution. Very much appreciate the explanation; helps me learn as well as solve the problem.

---

<div class="post-metadata">

**Author:** ![system](https://us1.discourse-cdn.com/flex019/uploads/powershell/original/1X/385e4f9fe133561ad30a814262fe0e0ae6bc3ef0.png) [@system](https://forums.powershell.org/u/system)\
**Post date:** [July 25, 2025, 11:17am UTC](https://forums.powershell.org/t/function-not-handling-variable-correctly/25955/15 "2025-07-25T11:17:45Z")

</div>

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.
