There are a lot of good answers here. This is an old question and mostly the OP seems to have answered it for themselves.
However, in the general case this is a complicated issue especially if you want to put code like this in to your $profile. I had put some unguarded output in a $profile which caused a remote scp command to fail. This created sadness and found me reading this thread.
The real problem with mine and other solutions is it's not possible to know the intent of the person running a script. Someone using a -f or -c option may or may not be expecting an interactive experience. That can be especially problematic if you are trying to check something like this in your $profile.
The code below tries to respect intention if it's put forward. For example, if the -i or -noni option is given, it assumes that's what you want. Everything else is open for interpretation. If you need to support both types of behavior (interactive/non-interactive) you can use options and short cuts differently. For example, let '-c' run the command 'interactive' and -command run 'non-interactive'. Note, you should consider doing such a thing as a nasty hack that will bite you or someone else later, but it can get you out of a jam and 'scripting life' is often filled with compromises. No matter what you choose, document, early, often and everywhere, remember you might have to support the code you write ;-)
function IsShellInteractive {
if ([Environment]::UserInteractive -eq $false) {
return $false
}
# Get the args, minus the first executable (presumable the full path to powershell or pwsh exe)
$options = [Environment]::GetCommandLineArgs() | Select-Object -Skip 1
# trust any stated intention
if (($options -contains "-i") -or ($options -contains "-interactive")) {
return $true
}
if (($options -contains "-noni") -or ($options -contains "-noninteractive")) {
return $false
}
# [[-File|-f] <filePath> [args]]
# [-Command|-c { - | <script-block> [-args <arg-array>]
# | <string> [<CommandParameters>] } ]
# [-EncodedCommand|-e|-ec <Base64EncodedCommand>]
# [-NoExit|-noe]
# [-NoProfile|-nop]
# [-InputFormat|-ip|-if {Text | XML}]
# [-OutputFormat|-o|-op {Text | XML}]
# [-PSConsoleFile <file> ]
# Who Knows ?
# options like
# -noexit, -noe and -psconsolefile" are 'likely' interactive
# others like
# -noprofile,-nop,-inputformat,-ip,-if,-outputformat,-o,-op are 'likely' non-interactive
# still others like
# -file,-f,-command,-c,encodedcommand,-e,-ec could easily go either way
# remove ones you don't like, or use short cuts one way and long form another
$nonInteractiveOptions = "-file,-f,-command,-c,encodedcommand,-e,-ec,-noprofile,-nop,-inputformat,-ip,-if,-outputformat,-o,-op" -split ","
foreach ($opt in $options) {
if ($opt -in $nonInteractiveOptions) {
return false;
}
}
return $true
}