r/PowerShell • • Feb 27 '26

Question Script not creating the log file

I have a script I am working on that should make a log file, but the script isn't making the file. I'm not very experienced with this, but it works as an independent command.

[CmdletBinding(SupportsShouldProcess = $true, ConfirmImpact = 'Medium')]
param(
    [Parameter(Mandatory=$true)]
    [string]$CsvPath,

    [string]$LogPath = ".\profile-import-$(Get-Date -Format 'yyyyMMdd-HHmmss').log"
)

function Write-Log {
    param([string]$Message)
    $line = "{0}  {1}" -f (Get-Date -Format "yyyy-MM-dd HH:mm:ss"), $Message
    $line | Tee-Object -FilePath $LogPath -Append | Out-Null
}

# Connect to Microsoft Graph
Import-Module Microsoft.Graph.Users

$scopes = @("User.ReadWrite.All")
Write-Log "Connecting to Microsoft Graph with scopes: $($scopes -join ', ')"
Connect-MgGraph -Scopes $scopes | Out-Null
2 Upvotes

26 comments sorted by

View all comments

Show parent comment

2

u/PinchesTheCrab Feb 27 '26

That syntax on $LogPath isn't right, and you shouldn't rely on scope bleeding to supply it to the function. Functions take input from parameters. If you think you'll have to call write-log a bunch, then consider psdefault parameters or some other method.

This might work:

[CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'Medium')]
param(
    [parameter(Mandatory)]
    [string]$CsvPath,

    [string]$LogPath = "$($PSScriptRoot)\profile-import-$(Get-Date -Format 'yyyyMMdd-HHmmss').log")

$PSDefaultParameterValues['Write-Log:Path'] = $LogPath

function Write-Log {
    param(
        [parameter(Mandatory)]
        [string]$Message,

        [parameter(Mandatory)]
        [string]$Path
    )
    $line = '{0:yyyy-MM-dd HH:mm:ss}  {1}' -f (Get-Date), $Message
    $line | Out-File -FilePath $Path -Append
}

# Connect to Microsoft Graph
Import-Module Microsoft.Graph.Users

$scopes = @('User.ReadWrite.All')
Write-Log "Connecting to Microsoft Graph with scopes: $($scopes -join ', ')"
Connect-MgGraph -Scopes $scopes | Out-Null