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

1

u/omglazrgunpewpew Feb 28 '26 edited Mar 03 '26

Ahh, okay, so you’re running the script with -WhatIf, which makes sense why no log file is being created.

Because the script uses [CmdletBinding(SupportsShouldProcess = $true)], PowerShell sets $WhatIfPreference = $true when you pass -WhatIf. Tee-Object participates in ShouldProcess, so instead of writing to disk, you're getting:

What if: Performing the operation "Output to File"…

All that means is the write is being simulated, not executed. So logging function is just respecting WhatIf mode and telling you what it would do.

If you want a real log file, run without -WhatIf. If you want WhatIf for user changes but still want logs written, don’t use Tee-Object for file logging.

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

    [string]$LogPath = (Join-Path $PSScriptRoot "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

    # Always write log, even in -WhatIf
    Add-Content -Path $LogPath -Value $line

    # Optional console output
    Write-Host $line
}

Write-Host "Log location is: $LogPath"
Write-Log "Script started"
Write-Log "WhatIf mode: $WhatIfPreference"