Search code examples
powershellscriptingprofile

PowerShell ignore profile script when calling another script


this is racking my brain. I have a profile script that I use to prep my system, it works great. Now the problem is, the system I am working on is managed by a company and they are pushing scripts for system validations and remediation like a normal company would do, however, what ever tool they are using to do it it not calling the -noprofile command in PowerShell. So what I'm finding is that every time they call a script under my user context, its runs my Microsoft.PowerShell_profile.ps1 first....which can be really annoying. I have not contacted the service desk to say "hey can you change your processes because it making my system do this...?"

Is there a way I can write in my profile script something like this:

If($MyInvocation.MyCommand.ToString() -ne 'Microsoft.PowerShell_profile.ps1'){
    Break
}

I'm finding this does not work. if the PowerShell command is called:

powershell -file d:\Scripts\testscript.ps1

How do I get detect the file name call from the profile script. I can detect it in a testscript.ps1 using any of these variables:

'$MyInvocation.InvocationName:' + $MyInvocation.InvocationName
'$MyInvocation.MyCommand: ' + $MyInvocation.MyCommand
'$MyInvocation.MyCommand.Name: ' + $MyInvocation.MyCommand.Name
'$MyInvocation.MyCommand.Path: ' + $MyInvocation.MyCommand.Path
'$PSCommandPath: ' + $PSCommandPath
'$PSScriptRoot :' + $PSScriptRoot

Am I asking the impossible?


Solution

  • A simple way to distinguish in your $PROFILE file is to test if any arguments were passed to the PowerShell executable on startup:

    if ([Environment]::GetCommandLineArgs().Count -gt 1) { exit }
    

    Note: There's always at least one argument, namely the executable itself.

    If there's a chance that even your interactive sessions are started with arguments, you'd have to examine the [Environment]::GetCommandLineArgs() array more specifically.