Preventing script warning on a PowerShell Profile

Tagged: 

This topic contains 7 replies, has 3 voices, and was last updated by  Mark Hammonds 1 year, 11 months ago.

  • Author
    Posts
  • #30851

    Steven Ayers
    Participant

    I finish up my nifty little profile, giving our support team a few lazy functions to a) make connecting to 365 quicker, b) backup things in case any apprentices/1st liners get a bit adventurous and it doesn't work out in their favour – everybody wins.

    I stick it on my colleagues computer as my test subject, and it spins up a "Only run scripts you trust" error, only with an option to 'Run Once'... I have used Unblock-File now and it's fine, but I can't run that on every machine!

    I'm storing this in Documents\WindowsPowershell\Microsoft.Powershell_profile.ps1 (alongside ISE version)

    I was considering a start-process powershell.exe -ArgumentList "-executionpolicy bypass $home\Documents\WindowsPowershell\Microsoft.Powershell_profile.ps1" but surely this will require approval of it's own?

    Any ideas would be much appreciated, I've included the code below (sharing is caring).

    Steven.

    # DETECT TIME & USER
    $username = ($env:USERNAME).replace('.',' ')
    $TextInfo = (Get-Culture).TextInfo
    $username = $TextInfo.ToTitleCase($username)
    # CREATE APPDATA FOLDER
        $PSData = "$env:APPDATA\Company"
            If (!(Test-Path $PSData)) {
                md $PSData | Out-Null
                
            }
            else {
                
            }
    # IMPORT OFFICE 365 FUNCTIONS
        try {
            Import-Module MSOnline
                try {
                    # CONNECT-OFFICE365
                        function Connect-Office365 {
                            
                            $Hour = (Get-Date).Hour
                                If ($Hour -lt 12) {
                                    $greeting = "Good Morning $username"
                                }
                                ElseIf ($Hour -gt 16) {
                                    $greeting = "Good Evening $username"
                                }
                                Else {
                                    $greeting = "Good Afternoon $username"
                                }
                            $ConnectMessage = "$greeting. Please enter global admin credentials for the tenant you wish to connect to."
                                do {
                                    $stillblank = $false
                                    $CompanyCred = Get-Credential -Message "$ConnectMessage"
                                        if ($CompanyCred -eq $null) {
                                            $ConnectMessage = "You did not enter any credentials, please try again."
                                            $attempt++
                                        }
                                        if ($attempt -eq 2) {
                                            $stillblank = $true
                                        }
                                } while (($CompanyCred -eq $null) -and ($stillblank -eq $false))
                                if ($stillblank -eq $true) {
                                    Write-Error "Credentials are null."
                                }
                                if ($stillblank -eq $false) {
                                    try {
                                    $CompanySession = New-PSSession –ConfigurationName Microsoft.Exchange -WarningAction SilentlyContinue `
                                    -ConnectionUri https://ps.outlook.com/powershell -Credential $CompanyCred -Authentication Basic -AllowRedirection -ErrorAction SilentlyContinue
                                    Import-PSSession $CompanySession -AllowClobber | Out-Null
                                    Connect-MsolService –Credential $CompanyCred | out-null
                                    $CompanyName = (Get-MsolCompanyInformation).DisplayName
                                        if ($CompanyName -ne $null) {
                                            Write-host " "
                                            Write-host "Connected to $CompanyName."
                                            Write-host " "
                                        }
                                    }
                                    catch {
                                    Write-Error "Authentication Failed, please check your credentials. You can also try clearing PSSession by running Get-PSSession | Remove PSSession."
                                    }
                                }
                        }
                    New-Alias c365 Connect-Office365
                    Write-host "To connect to Office 365, please use the Connect-Office365 cmdlet. Use Get-Help on the cmdlet for more information." -ForegroundColor Yellow
                    Write-host " "
                    # BACKUP USER
                        function Backup-MsolUser {
                            
                            [CmdletBinding()]
                                param(
                                [parameter(Mandatory=$true)][string]$UserPrincipalName
                                )
                            $ErrorActionPreference = "SilentlyContinue"
                            $MsolUser = Get-MsolUser -UserPrincipalName $UserPrincipalName | select * -ErrorAction SilentlyContinue
                                if ($MsolUser -ne $null) {
                                    $Filename = ($UserPrincipalName.Replace('@','-')).Replace('.','-')
                                    $Date = ((get-date).ToShortDateString()).Replace('/','-')
                                    $Time = ((get-date).ToShortTimeString()).Replace(':','-')
                                    $DateTime = $date+"-"+$time
                                    $MsolUser | Export-Clixml "$PSData\$DateTime-MsolUser-$Filename.xml"
                                    $MsolUser | Export-CSV "$PSData\$DateTime-MsolUser-$Filename.csv"
                                }
                                if ($MsolUser -eq $null) {
                                    $ErrorActionPreference = "Continue"
                                    Write-Error "Could not retrieve the user `'$UserPrincipalName`', Please check you have used the correct User Principal Name and you that are connected to a tenant."
                                }
                        }
                        function Backup-Mailbox {
                            
                            [CmdletBinding()]
                                param(
                                [parameter(Mandatory=$true)][string]$Identity
                                )
                            $ErrorActionPreference = "SilentlyContinue"
                            $Mailbox = Get-Mailbox -Identity $Identity | select * -ErrorAction SilentlyContinue
                                if ($Mailbox -ne $null) {
                                    $Filename = $Mailbox.Alias
                                    $Date = ((get-date).ToShortDateString()).Replace('/','-')
                                    $Time = ((get-date).ToShortTimeString()).Replace(':','-')
                                    $DateTime = $date+"-"+$time
                                    $Mailbox | Export-Clixml "$PSData\$DateTime-Mailbox-$Filename.xml"
                                    $Mailbox | Export-CSV "$PSData\$DateTime-Mailbox-$Filename.csv"
                                }
                                if ($Mailbox -eq $null) {
                                    $ErrorActionPreference = "Continue"
                                    Write-Error "Could not retrieve the user `'$Identity`', Please check you have used the correct Identity and you that are connected to a tenant."
                                }
                        }
                }
                Catch {
                }
        }
        Catch {
            Write-host "Office 365 Module could not be loaded, please check if Windows Azure Active Directory Module for Windows PowerShell is installed." -foregroundcolor Yellow
            Write-host " "
        }
    
    $Name = ($env:USERNAME).replace('.','')
    $Date = ((get-date).ToShortDateString()).Replace('/','-')
    $Time = ((get-date).ToShortTimeString()).Replace(':','-')
    $DateTime = $Date+"-"+$Time
    Start-Transcript $PSData\$Name-$DateTime-PSTranscript.log -IncludeInvocationHeader | Out-Null
  • #30852

    Mark Hammonds
    Participant

    Look into PowerShell Web access as a possible solution.

  • #30853

    Steven Ayers
    Participant

    Thank you for pointing me towards the Web. I was sending this as an attachment over email which is why that had errors.

    When I retrieved it from a share on my computer, I had the error of "running scripts is disabled on this system", so execution policy.

    If anyone has found out how to bypass execution on profiles, please let me know 🙂

  • #30855

    Jonathan Warnken
    Participant

    The profile will load under the execution policy that the powershell instance starts under
    powershell = default execution policy
    powershell -ExecutionPolicy Bypass = execution policy set to bypass for this instance of powershell

    If you are getting "running scripts is disabled on this system" the systems are set to the default execution policy of restricted. You will need to change it to a setting that is appropriate for your environment. This can be done via group policy or a script.

  • #30857

    Steven Ayers
    Participant

    Yeah I was trying to avoid changing GPO's or having to run a shortcut, but I think it may just be impossible to do it purely from a script.

    Thank you for your help 🙂

  • #30872

    Mark Hammonds
    Participant

    to clarify I suggested it so all you have to do is set up one server with an execution policy of remote signed. sign your script then allow all of your IT professionals connect to that server through a web browser to run the script.

    https://technet.microsoft.com/en-us/library/hh831611.aspx

    im sorry if I don't understand I am still really new to powershell I seen this in one of Microsoft virtual academy's and thought is was a cool way to provide users the use of powershell while limiting the commands to a hand full of approved ones

    also I think the 2012 server execution policy is set to remote signed by default

  • #30873

    Steven Ayers
    Participant

    You suggested the word 'Web', which was the one that got me thinking, haha.

    And no, unfortunately web access would not be appropriate, I want something to natively run on people's machines and to avoid changing how they work completely. This is all about being lazy and convenient, so making people login to a web browser would defeat the point, also, I think I'd get shot for spinning up a server for this 😛

    Thanks anyway though, you indirectly helped me find the answer!

  • #30874

    Mark Hammonds
    Participant

    No worries i'm a special kind of idiot most of the time I have no idea whats going on but I try to help anyway.

You must be logged in to reply to this topic.