We have a script that runs nightly and takes all the new users from a database and makes a mailbox for them. Somehow, it doesn't like something that's inputted into the full names of employees and it's converting it to a "" for the log file. It's putting "N\A" in the file name of the log file and it can't create a file with a backslash in it.
Ignore names in the script, I've changed a lot of them to keep private information safe.
Why is this script sometimes generating a log file with a backslash in it?
Here is an example of the error
**Error Message**
Out-File : Could not find a part of the path '\\Server\common\Logs\New_Hire\Employee_Automated\Jesse N\A Bogdan_419772.txt'.
At \\Server\common\Folder\AppDevelopment\Powershell\SSIS_Package_Run_Scripts\Set-MailboxSettings.ps1:117
char:81
+ ... FullName) Error completing Exchange Options." | Out-File $log -Append
+ ~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : OpenError: (:) [Out-File], DirectoryNotFoundException
+ FullyQualifiedErrorId : FileOpenFailure,Microsoft.PowerShell.Commands.OutFileCommand
Out-File : Could not find a part of the path '\\temfs19\IT\Logs\New_Hire\Craft_Automated\Jesse N\A
Berumer_416882.txt'.
At \\Server\common\FilePath\ApplicationDevelopment\Powershell\SSIS_Package_Run_Scripts\Set-EmployeeMailboxSettings.ps1:128
char:7
+ " | Out-File $log -Append
+ ~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : OpenError: (:) [Out-File], DirectoryNotFoundException
+ FullyQualifiedErrorId : FileOpenFailure,Microsoft.PowerShell.Commands.OutFileCommand
Here is the script:
## Import Modules
Import-Module ActiveDirectory
Import-Module ExchangeOnlineManagement
<#
#Set Office 365 Credentials
$encrypted = Get-Content C:\psscript\password.txt | ConvertTo-SecureString
$cred = New-Object System.Management.Automation.PsCredential("script@organization.com", $encrypted)
Import-Module MSOnline
$O365Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://ps.outlook.com/PowerShell-LiveID?PSVersion=3.0 -Credential $Cred -Authentication Basic -AllowRedirection
Import-Module ActiveDirectory
Import-PSSession $O365Session -AllowClobber
Connect-MsolService -Credential $cred
#>
## Connect to EXO using cert-based auth
Connect-ExchangeOnline -CertificateThumbPrint "cbc51f887fdc5e2l1cda672044f37f1bfda99d74" -AppID "fc6d6201-8369-417b-909d-b6f5d2d3ea5c" -Organization "organization.onmicrosoft.com" -ShowBanner:$false
## Set Variables for Script
$ServerInstance = "Server"
$DatabaseName = "Database"
$SchemaName = "dbo"
$TableName = "Org_AD_Account"
## Get Usernames
$users = Invoke-Sqlcmd -ServerInstance $ServerInstance -Database $DatabaseName -Query "SELECT * FROM [dbo].[v_Example_ExchDeliveryRestrictions]"
## Run for one User
#$users = Invoke-Sqlcmd -ServerInstance $ServerInstance -Database $DatabaseName -Query "SELECT * FROM [dbo].[v_Example_ExchDeliveryRestrictions] WHERE EmployeeNumber = '490935'"
foreach ($user in $users)
{
try
{
#Get All Variables
$username = [string]$user.EmployeeNumber
$Log = "\\Server\Path\Logs\New_Hire\Employee_Automated"
$UsernameLog = ($user.FullName).replace("/", "")
$Log = "$log\$($UsernameLog)_$($username).txt"
###############################################################################
## -- Start Log File
###############################################################################
Write-Output "
********************** `r`n
Set-CraftMailboxSettings Script Start `r`n
Start Time: $(Get-Date) `r`n
********************** `r`n
###################################################################
" | Out-File $log -Append
###############################################################################
## -- Check if User Already has a mailbox
###############################################################################
$exists = $null
$exists = Get-Mailbox $username
if ($exists)
{
Write-Output "[Exists] $($user.FullName) has a mailbox." | Out-File $log -Append
##Add Only allow senders in the following list
Set-Mailbox -Identity $username -AcceptMessagesOnlyFrom @{ add = "IT" }
##Require sender authentication
Set-Mailbox -Identity $username -RequireSenderAuthenticationEnabled $true
get-mailbox -Identity $username | Select-Object name, acceptmessagesonlyfrom, requiresenderauthenticationenabled | Out-File $log -Append
###############################################################################
## -- Mark User as complete in the database
###############################################################################
Invoke-Sqlcmd -ServerInstance $ServerInstance -Database $DatabaseName -Query "UPDATE [dbo].[Craft_AD_Account] SET ExchDeliveryRestrictions = 'Y', UpdateDate = GETDATE() WHERE EmployeeNumber = $($user.EmployeeNumber)"
}
else
{
#Check if employee number exists in AD
$existsEmployeeNum = $null
$existsEmployeeNum = get-aduser -SearchBase "OU=Org,DC=myorg,DC=com" -Filter * -Properties employeenumber | Where-Object {$_.employeenumber -eq $username}
if ($existsEmployeeNum)
{
#This user exists with another username
###############################################################################
## -- Mark User as complete N in the database
###############################################################################
Invoke-Sqlcmd -ServerInstance $ServerInstance -Database $DatabaseName -Query "UPDATE [dbo].[Org_AD_Account] SET ExchDeliveryRestrictions = 'N', UpdateDate = GETDATE() WHERE EmployeeNumber = $($username)"
Write-Output "[Exists] $($user.FullName) exists in AD with another username, they likely need email. No Action Required." | Out-File $log -Append
}
else
{
#This user doesn't exist with any username in AD
Write-Output "[NOTExists] $($user.FullName) DOES NOT have a mailbox." | Out-File $log -Append
}
} #if exists
}
catch
{
Write-Output "[Error] $($user.FullName) Error completing Exchange Options." | Out-File $log -Append
} #catch
###############################################################################
## -- End Log File
###############################################################################
Write-Output "
********************** `r`n
Set-CraftMailboxSettings Script END `r`n
End Time: $(Get-Date) `r`n
Script ran successfully
********************** `r`n
" | Out-File $log -Append
} #foreach
I have tried to see if we even needed the script anymore because it's 3 years old now, and we thought some of our processes changed for new employees, but we still need this script.
Again, the script DOES work, but it tries to create log files for some employees with a backslash in it.
My apologies if I've done stuff out of the norm or best practices for posting here, I'm new and I'm not a programmer (I'm a sysadmin).
Thanks!