Custom commands
John needs to access Exchange PowerShell a lot. He's tired of logging in the actual Exchange server all the time, he prefers to use his local computer to run cmdlets and manage mailboxes.
He created a script, called "mail.ps1" to import all the Exchange cmdlets in his local machine, but he wants to be able to run the mail command simply, whenever he opens a PowerShell window. All without browsing to his personal folder and use the .ps1 extension.
Also, he shares the client machine with a few other administrators, and he wants all the other guys to be able to use the mail command as well.
1. Utilize the "$Profile script" to create a function for himself1
Powershell has a special file in the actual user's Documents folder, that automatically runs when powershell starts. By default it is not there, it needs to be manually created.
Then we can add any commands, create functions, anything that we need.
PowerShell even has a pre-set variable for it, called $PROFILE. We can check where it is stored and what the file is called.
However, it does not exist for the users by default. He creates it with a simple command, then opens it and adds his contents.
PS C:\> $PROFILE C:\Users\jdoe\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1 PS C:\> PS C:\> New-Item -Force -Type File $PROFILE Directory: C:\Users\jdoe\Documents\WindowsPowerShell Mode LastWriteTime Length Name ---- ------------- ------ ---- -a---- 20/04/2020 14:46 0 Microsoft.PowerShell_profile.ps1 PS C:\>notepad $PROFILE
He can now open a new PowerShell window, and simply use the mail command to connect to Exchange.
2. Allow Everyone to use the custom commands
Besides having $PROFILE that resolves to $HOME\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1, there is another useful location, a script that runs for everyone who opens a PS window on the local machine.
Just use $PROFILE.AllUsersAllHosts instead of $PROFILE. Or edit it using it's fully qualified location: C:\Windows\System32\WindowsPowerShell\v1.0\profile.ps1
PS C:\> $PROFILE C:\Windows\System32\WindowsPowerShell\v1.0\profile.ps1 PS C:\> PS C:\> New-Item -Force -Type File $PROFILE.AllUsersAllHosts Directory: C:\Users\jdoe\Documents\WindowsPowerShell Mode LastWriteTime Length Name ---- ------------- ------ ---- -a---- 20/04/2020 14:46 0 Microsoft.PowerShell_profile.ps1 PS C:\>notepad $PROFILE.AllUsersAllHosts
Then test that the command runs in any user profiles
Comments