What script and where I should write in order to define:
alias for ll="ls -l"
alias/function cd = "original cd; ll"
So, my question has to parts where is the rc files of the Power Shell on Windows 7 and how to alias ll to ls -l and cd to cd; ll?
Create a file in the place where the power shell points when you type $profile and press enter, if it does not exist. (For more info look here.)
Also I have found a lots of good examples next to the powershell.exe in my system there is an example folder, where there is a file named profile.ps1 with the following code:
set-alias cat get-content
set-alias cd set-location
set-alias clear clear-host
set-alias cp copy-item
set-alias h get-history
set-alias history get-history
set-alias kill stop-process
set-alias lp out-printer
set-alias ls get-childitem
set-alias mount new-mshdrive
set-alias mv move-item
set-alias popd pop-location
set-alias ps get-process
set-alias pushd push-location
set-alias pwd get-location
set-alias r invoke-history
set-alias rm remove-item
set-alias rmdir remove-item
set-alias echo write-output
set-alias cls clear-host
set-alias chdir set-location
set-alias copy copy-item
set-alias del remove-item
set-alias dir get-childitem
set-alias erase remove-item
set-alias move move-item
set-alias rd remove-item
set-alias ren rename-item
set-alias set set-variable
set-alias type get-content
function help
{
get-help $args[0] | out-host -paging
}
function man
{
get-help $args[0] | out-host -paging
}
function mkdir
{
new-item -type directory -path $args
}
function md
{
new-item -type directory -path $args
}
function prompt
{
"PS " + $(get-location) + "> "
}
& {
for ($i = 0; $i -lt 26; $i++)
{
$funcname = ([System.Char]($i+65)) + ':'
$str = "function global:$funcname { set-location $funcname } "
invoke-expression $str
}
}
Also take into account the following problem. You may have the following error while executing the file located in $profile:
"Microsoft.PowerShell_profile.ps" cannot be loaded because the execution of scripts is disabled on this system. Please see "get-help about_signing" for more details.
Solution:
Check the current execution-policy
PS C:\Windows\System32> Get-ExecutionPolicy
Restricted
PS C:\Windows\System32>
To change the execution policy to allow PowerShell to execute scripts from local files, run the following command:
PS C:\Windows\System32> Set-Executionpolicy RemoteSigned -Scope CurrentUser
Related
Using a batch file to call a Powershell script (this part is working and saving the output files locally):
PowerShell.exe -NoProfile -Command "& {Start-Process PowerShell.exe -ArgumentList '-NoProfile -ExecutionPolicy Bypass -WindowStyle Hidden -File ""%~dpn0.ps1 -Update""' -Verb RunAs}"
Trying to add in a parameter to redirect the output of the script to a folder (per the code comments it can be to a local or UNC path):
-OutputPath Z:\Current
Have tried inserting it everywhere I can think of in the script, cannot get it to work; am thinking it should go in like this(?):
PowerShell.exe -NoProfile -Command "& {Start-Process PowerShell.exe -ArgumentList '-NoProfile -ExecutionPolicy Bypass -WindowStyle Hidden -File ""%~dpn0.ps1 -OutputPath Z:\Current""' -Verb RunAs}"
Here is where the output path is determined in the code:
# If -OutputPath not specified, set default
If (-not($OutputPath)) {
Switch ($OSPlatform) {
"Windows" {
$OutputPath = "$env:PUBLIC\Documents\ Compliance"
if (!(Test-Path $OutputPath)) {
$null = New-Item -Path $(Split-Path -Path $OutputPath -Parent) -Name $(Split-Path -Path $OutputPath -Leaf) -ItemType Directory
}
}
"Linux" {
$OutputPath = "/opt/STIG_Compliance"
if (!(Test-Path $OutputPath)) {
sudo mkdir $OutputPath
}
}
}
}
From what I can find online, the -OutputPath Z:\Current should come immediately after the .ps1 command, but not sure where it should be inserted amongst the other options being used in the batch file.
The script is not throwing off any errors, but is running and saving the output in the default locatin. I am not that well-versed in Powershell; am I missing something?
Thanks in advance for your help!!
It seems like you're trying to pass the OutputPath parameter to your PowerShell script through the command line argument -File. I believe the correct way to pass parameters to a PowerShell script is to include them in the argument list of the PowerShell command.
You could update your command to include the OutputPath parameter in the argument list, like this:
PowerShell.exe -NoProfile -Command "& {Start-Process PowerShell.exe -ArgumentList '-NoProfile -ExecutionPolicy Bypass -WindowStyle Hidden -File ""%~dpn0.ps1""', '-OutputPath', 'Z:\Current' -Verb RunAs}"
Also, make sure to update your PowerShell script to properly use the OutputPath parameter, like this:
# If -OutputPath not specified, set default
if (-not $OutputPath) {
switch ($OSPlatform) {
"Windows" {
$OutputPath = "$env:PUBLIC\Documents\Compliance"
if (!(Test-Path $OutputPath)) {
$null = New-Item -Path $(Split-Path -Path $OutputPath -Parent) -Name $(Split-Path -Path $OutputPath -Leaf) -ItemType Directory
}
}
"Linux" {
$OutputPath = "/opt/STIG_Compliance"
if (!(Test-Path $OutputPath)) {
sudo mkdir $OutputPath
}
}
}
}
# Redirect output to the specified output path
if ($OutputPath) {
$OutputFile = Join-Path -Path $OutputPath -ChildPath "output.txt"
Write-Output "Writing output to $OutputFile"
# Your code to generate output here
# ...
Out-File -FilePath $OutputFile -InputObject "Output data"
}
else {
# Your code to generate output here
# ...
}
Hopefully this helps ya.
"System.Threading.Tasks.Task`1[System.String]" text comes on before the profile loading text
here is my
I changed my profile script to:
### PowerShell template profile
### Version 1.03 - Tim Sneath <tim#sneath.org>
### From https://gist.github.com/timsneath/19867b12eee7fd5af2ba
###
### This file should be stored in $PROFILE.CurrentUserAllHosts
### If $PROFILE.CurrentUserAllHosts doesn't exist, you can make one with the following:
### PS> New-Item $PROFILE.CurrentUserAllHosts -ItemType File -Force
### This will create the file and the containing subdirectory if it doesn't already
###
### As a reminder, to enable unsigned script execution of local scripts on client Windows,
### you need to run this line (or similar) from an elevated PowerShell prompt:
### Set-ExecutionPolicy -ExecutionPolicy RemoteSigned
### This is the default policy on Windows Server 2012 R2 and above for server Windows. For
### more information about execution policies, run Get-Help about_Execution_Policies.
# Import Terminal Icons
Import-Module -Name Terminal-Icons
# Find out if the current user identity is elevated (has admin rights)
$identity = [Security.Principal.WindowsIdentity]::GetCurrent()
$principal = New-Object Security.Principal.WindowsPrincipal $identity
$isAdmin = $principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
# If so and the current host is a command line, then change to red color
# as warning to user that they are operating in an elevated context
# Useful shortcuts for traversing directories
function cd... { Set-Location ..\.. }
function cd.... { Set-Location ..\..\.. }
# Compute file hashes - useful for checking successful downloads
function md5 { Get-FileHash -Algorithm MD5 $args }
function sha1 { Get-FileHash -Algorithm SHA1 $args }
function sha256 { Get-FileHash -Algorithm SHA256 $args }
# Quick shortcut to start notepad
function n { notepad $args }
# Drive shortcuts
function HKLM: { Set-Location HKLM: }
function HKCU: { Set-Location HKCU: }
function Env: { Set-Location Env: }
# Creates drive shortcut for Work Folders, if current user account is using it
if (Test-Path "$env:USERPROFILE\Work Folders") {
New-PSDrive -Name Work -PSProvider FileSystem -Root "$env:USERPROFILE\Work Folders" -Description "Work Folders"
function Work: { Set-Location Work: }
}
# Set up command prompt and window title. Use UNIX-style convention for identifying
# whether user is elevated (root) or not. Window title shows current version of PowerShell
# and appends [ADMIN] if appropriate for easy taskbar identification
function prompt {
if ($isAdmin) {
"[" + (Get-Location) + "] # "
} else {
"[" + (Get-Location) + "] $ "
}
}
$Host.UI.RawUI.WindowTitle = "PowerShell {0}" -f $PSVersionTable.PSVersion.ToString()
if ($isAdmin) {
$Host.UI.RawUI.WindowTitle += " [ADMIN]"
}
# Does the the rough equivalent of dir /s /b. For example, dirs *.png is dir /s /b *.png
function dirs {
if ($args.Count -gt 0) {
Get-ChildItem -Recurse -Include "$args" | Foreach-Object FullName
} else {
Get-ChildItem -Recurse | Foreach-Object FullName
}
}
# Simple function to start a new elevated process. If arguments are supplied then
# a single command is started with admin rights; if not then a new admin instance
# of PowerShell is started.
function admin {
if ($args.Count -gt 0) {
$argList = "& '" + $args + "'"
Start-Process "$psHome\powershell.exe" -Verb runAs -ArgumentList $argList
} else {
Start-Process "$psHome\powershell.exe" -Verb runAs
}
}
# Set UNIX-like aliases for the admin command, so sudo <command> will run the command
# with elevated rights.
Set-Alias -Name su -Value admin
Set-Alias -Name sudo -Value admin
# Make it easy to edit this profile once it's installed
function Edit-Profile {
if ($host.Name -match "ise") {
$psISE.CurrentPowerShellTab.Files.Add($profile.CurrentUserAllHosts)
} else {
notepad $profile.CurrentUserAllHosts
}
}
# We don't need these any more; they were just temporary variables to get to $isAdmin.
# Delete them to prevent cluttering up the user profile.
Remove-Variable identity
Remove-Variable principal
Function Test-CommandExists {
Param ($command)
$oldPreference = $ErrorActionPreference
$ErrorActionPreference = 'SilentlyContinue'
try { if (Get-Command $command) { RETURN $true } }
Catch { Write-Host "$command does not exist"; RETURN $false }
Finally { $ErrorActionPreference = $oldPreference }
}
#
# Aliases
#
# If your favorite editor is not here, add an elseif and ensure that the directory it is installed in exists in your $env:Path
#
if (Test-CommandExists nvim) {
$EDITOR = 'nvim'
} elseif (Test-CommandExists pvim) {
$EDITOR = 'pvim'
} elseif (Test-CommandExists vim) {
$EDITOR = 'vim'
} elseif (Test-CommandExists vi) {
$EDITOR = 'vi'
} elseif (Test-CommandExists code) {
#VS Code
$EDITOR = 'code'
} elseif (Test-CommandExists notepad) {
#fallback to notepad since it exists on every windows machine
$EDITOR = 'notepad'
}
Set-Alias -Name vim -Value $EDITOR
function ll { Get-ChildItem -Path $pwd -File }
function g { Set-Location $HOME\Documents\Github }
function Get-PubIP {
(Invoke-WebRequest http://ifconfig.me/ip ).Content
}
function uptime {
#Windows Powershell
Get-WmiObject win32_operatingsystem | Select-Object csname, #{
LABEL = 'LastBootUpTime';
EXPRESSION = { $_.ConverttoDateTime($_.lastbootuptime) }
}
}
function reload-profile {
& $profile
}
function find-file($name) {
Get-ChildItem -recurse -filter "*${name}*" -ErrorAction SilentlyContinue | ForEach-Object {
$place_path = $_.directory
Write-Output "${place_path}\${_}"
}
}
function unzip ($file) {
Write-Output("Extracting", $file, "to", $pwd)
$fullFile = Get-ChildItem -Path $pwd -Filter .\cove.zip | ForEach-Object { $_.FullName }
Expand-Archive -Path $fullFile -DestinationPath $pwd
}
function grep($regex, $dir) {
if ( $dir ) {
Get-ChildItem $dir | select-string $regex
return
}
$input | select-string $regex
}
function touch($file) {
"" | Out-File $file -Encoding ASCII
}
function df {
get-volume
}
function sed($file, $find, $replace) {
(Get-Content $file).replace("$find", $replace) | Set-Content $file
}
function which($name) {
Get-Command $name | Select-Object -ExpandProperty Definition
}
function export($name, $value) {
set-item -force -path "env:$name" -value $value;
}
function pkill($name) {
Get-Process $name -ErrorAction SilentlyContinue | Stop-Process
}
function pgrep($name) {
Get-Process $name
}
# Import the Chocolatey Profile that contains the necessary code to enable
# tab-completions to function for `choco`.
# Be aware that if you are missing these lines from your profile, tab completion
# for `choco` will not function.
# See https://ch0.co/tab-completion for details.
$ChocolateyProfile = "$env:ChocolateyInstall\helpers\chocolateyProfile.psm1"
if (Test-Path($ChocolateyProfile)) {
Import-Module "$ChocolateyProfile"
}
Invoke-Expression (&starship init powershell)
There is a script named Get-Stuff.ps1 that is headed it with a PSScriptInfo block. The script is published to a NuGet repository. It is then installed to the expected location, C:\Users\lit\Documents\WindowsPowerShell\Scripts\Get-Stuff.ps1. Get-InstalledScript reports that it is installed. However, it is not found to be an executable. The C:\Users\lit\Documents\WindowsPowerShell\Scripts\ directory is not in $Env:PSModulePath.
What step did I miss to make this command executable after installation?
PS C:\> (Get-ChildItem -Recurse -File -Path 'C:\' -Filter 'Get-Stuff*' -ErrorAction SilentlyContinue).FullName
C:\src\Modules\scripts\Get-Stuff.ps1
PS C:\> Test-ScriptFileInfo -Path 'C:\src\Modules\scripts\Get-Stuff.ps1'
Version Name Author Description
------- ---- ------ -----------
1.0.0.1 Get-Stuff lit Get-Stuff produces .csv files of record counts from tables.
PS C:\> Publish-Script -Path 'C:\src\Modules\scripts\Get-Stuff.ps1' -NuGetApiKey 'yanon' -Repository 'yrepo'
PS C:\> Find-Script -Name Get-Stuff
Version Name Repository Description
------- ---- ---------- -----------
1.0.0.1 Get-Stuff yrepo Get-Stuff produces .csv files of record counts from tables.
PS C:\> Find-Script -Name Get-Stuff | Install-Script
PS C:\> (Get-ChildItem -Recurse -File -Path 'C:\' -Filter 'Get-Stuff*' -ErrorAction SilentlyContinue).FullName
C:\src\Modules\scripts\Get-Stuff.ps1
C:\Users\lit\Documents\WindowsPowerShell\Scripts\Get-Stuff.ps1
C:\Users\lit\Documents\WindowsPowerShell\Scripts\InstalledScriptInfos\Get-Stuff_InstalledScriptInfo.xml
PS C:\> Get-InstalledScript -Name Get-Stuff
Version Name Repository Description
------- ---- ---------- -----------
1.0.0.1 Get-Stuff yrepo Get-Stuff produces .csv files of record counts from tables.
PS C:\> Get-Command Get-Stuff
Get-Command : The term 'Get-Stuff' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of
the name, or if a path was included, verify that the path is correct and try again.
At line:1 char:1
+ Get-Command Get-Stuff
+ ~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (Get-Stuff:String) [Get-Command], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException,Microsoft.PowerShell.Commands.GetCommandCommand
PS C:\> $PSVersionTable.PSVersion.ToString()
5.1.17763.1490
It is $env:PATH that matters with respect to by-file-name-only invocations of *.ps1 files (script files), not $env:PSModulePath, which only applies to modules.
Unfortunately, earlier versions of the PowerShellGet module did not offer to add the directories targeted by the Install-Script cmdlet to $env:PATH persistently, but as of at least v2.2.4 they do (a prompt is presented), the next time you call Install-Script to perform an actual installation.
Try updating your PowerShellGet version with either Update-Module PowerShellGet or, if that fails, Install-Module -Force PowerShellGet (which in Windows PowerShell requires elevation, unless you specify -Scope CurrentUser).
If you want to make these $env:PATH additions yourself, run the following code:
Note:
Modifying $env:PATH persistently, via the registry, is only supported on Windows (on Unix, mechanisms for defining persistent environment variables differ across platforms).
However, on Unix too the in-session $env:PATH variable is updated.
& {
Write-Verbose -vb "Adding Install-Script install directories to `$env:PATH..."
$isWin = $env:OS -eq 'Windows_NT'
$isAdmin = if ($isWin) { [bool] (net session 2>$null) } else { 0 -eq (id -u) }
$ErrorActionPreference = 'Stop'
# Determine the locations: current-user, all-user.
$scriptDirs = (Join-Path (Split-Path ($PROFILE, "$HOME/.local/share/powershell/Modules")[$env:OS -ne 'Windows_NT']) Scripts),
(Join-Path (Split-Path ("$env:ProgramFiles\$(if ($PSVersionTable.PSEdition -ne 'Core') { 'Windows' })PowerShell\Modules", '/usr/local/share/powershell/Modules')[$env:OS -ne 'Windows_NT']) Scripts)
if (-not $isWin) {
# Note: There's no unified mechanism across macOS and Linux.
Write-Warning "On Unix, this script only supports modifying the *current session*'s `$env:PATH variable."
} elseif (-not $isAdmin) {
Write-Warning "Since this session isn't elevated, only the *current-user* location will be added *persistently*."
}
$pathVarSep = [IO.Path]::PathSeparator
$i = 0
foreach ($dir in $scriptDirs) {
# Always update the in-session variable.
Write-Verbose -vb "-- Adding $dir..."
if ($env:PATH -split $pathVarSep -notcontains $dir) {
$env:PATH = ($env:PATH -replace "$pathVarSep`$") + $pathVarSep + $dir
}
else {
Write-Verbose -vb "Already present in-session: $dir"
}
# On Windows, also try to update the *persistent* definitions
if ($isWin) {
$scope = ('User', 'Machine')[$i++ -eq 1]
if ($scope -eq 'Machine' -and -not $isAdmin) { break } # skip due to lack of permissions
# Note: We query the registry directly, so as to preserve unexpanded REG_EXPAND_SZ values.
$currVal = Get-ItemPropertyValue ('registry::HKEY_CURRENT_USER\Environment', 'registry::HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment')[$scope -eq 'Machine'] Path
if ($currVal -split $pathVarSep -notcontains $dir) {
[Environment]::SetEnvironmentVariable('Path', (($currVal -replace "$pathVarSep`$") + $pathVarSep + $dir), $scope)
} else {
Write-Verbose -vb "Already present persistently in the $scope scope: $dir"
}
}
}
Write-Verbose -vb 'Done.'
}
I get the an invalid path error with this script:
$buildZIP= 'starmatic'
echo $buildZIP
$command = ”\\XXXXXXXXXX\L$\Gopi_Prod_App\ToZipNew.ps1 $buildZIP”
Invoke-Expression -Command $command
This is ToZipNew.ps1:
Param(
[Parameter(Position=1, Mandatory=$true)]
[ValidateNotNullOrEmpty()]
[string]$build
)
echo "$build"
$S = "L:\Gopi_Prod_App\$build\App_Data\*"
$D = "\Gopi_Prod_App\Starmatic_UI.zip"
echo $S
echo $D
Get-ChildItem "$S" | Compress-Archive -DestinationPath "$D" -Verbose
#Compress-Archive -Path "$S" -CompressionLevel Fastest -DestinationPath "$D"
Error I am getting:
Compress-Archive : The path 'L:\Gopi_Prod_App' either does not exist or is not a
valid file system path.
At \\XXXXXXXXXXX\L$\Gopi_Prod_App\ToZipNew.ps1:13 char:45
+ ... t-ChildItem "$S" | Compress-Archive -DestinationPath "$D" -Verbose
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (L:\Gopi_Prod_App:String) [Compress-Archive], InvalidOperationException
+ FullyQualifiedErrorId : ArchiveCmdletPathNotFound,Compress-Archive
Invoke-Expression is almost always the wrong tool for whatever job you have at hand. Also, it looks to me like you actually want to run the script on the remote host. However, your Invoke-Expression statement is reading the script from the remote share and executing it locally.
Change
$command = ”\\XXXXXXXXXX\L$\Gopi_Prod_App\ToZipNew.ps1 $buildZIP”
Invoke-Expression -Command $command
into
Invoke-Command -Computer 'XXXXXXXXXX' -ScriptBlock {
& 'L:\Gopi_Prod_App\ToZipNew.ps1' $using:buildZIP
}
to run the script on the remote host XXXXXXXXXX.
If you do want to run the script locally connect the share \\XXXXXXXXXX\L$ as a network drive L: and call the script from that drive:
New-PSDrive -Name 'L' -PSProvider FileSystem -Root '\\XXXXXXXXXX\L$' -Persist
& 'L:\Gopi_Prod_App\ToZipNew.ps1' $buildZIP
Remove-PSDrive -Name 'L'
I have made he following code using the code present on this forum.
cls
$computername = Get-Content 'C:\Users\C201578-db\Documents\server.txt'
$sourcefile = "\\iceopsnas\LNT_SoftwareRep.grp\CORE\COTS\EMC\Avamar\Avamar_7.0\CR06794393\AvamarClient-windows-x86_64-7.0.102-47.msi"
#This section will install the software
foreach ($computer in $computername)
{
$destinationFolder = "\\$computer\C$\Avamar"
#This section will copy the $sourcefile to the $destinationfolder. If the Folder does not exist it will create it.
if (!(Test-Path -path $destinationFolder))
{
New-Item $destinationFolder -Type Directory
}
Copy-Item -Path $sourcefile -Destination $destinationFolder
Write-Host "Copied Successfully"
Invoke-Command -ComputerName $computer -ScriptBlock { & cmd /c "msiexec.exe /i C:\Avamar\AvamarClient-windows-x86_64-7.0.102-47.msi" /qb ADVANCED_OPTIONS=1 CHANNEL=100}
Write-Host "Installed Successfully"
}
I tried all permutations and combinations but no luck. Tried all the suggestions that I got while posting this question but nothing. The copy procedure is successful but the .msi file is not getting installed. Maybe this question gets marked duplicate but still suggest some edits before doing that.
try defining your command as a script block instead:
$command = "msiexec.exe /i C:\Avamar\AvamarClient-windows-x86_64-7.0.102-47.msi"
$scriptblock = [Scriptblock]::Create($command)
Invoke-Command -ComputerName $computer -ScriptBlock $scriptblock
As a workaround (the lack of details doesnt help to daignose the problem), you could use the third party tool psexec.exe to run the installer on the remote host.
Try to replace your invoke-command with
psexec.exe \\$computer -s -u Adminuser -p AdminPassword msiexec /i C:\Avamar\AvamarClient-windows-x86_64-7.0.102-47.msi /qb ADVANCED_OPTIONS=1 CHANNEL=100
It's working fine with psexec.exe, I have installed it on more than 100 user's desktop. Setup your user's ip addresses on clients.txt file. Below is my code :
cls
$computername = Get-Content 'C:\Setup\clients.txt'
$sourcefile = "C:\Setup\MySyncSvcSetup.msi"
$serviceName = "MySyncWinSvc"
$adminUserName = "username"
$adminPassword = "password#123"
#This section will install the software
foreach ($computer in $computername)
{
#First uninstall the existing service, if any
C:\PSTools\psexec.exe \\$computer -s -u $adminUserName -p $adminPassword msiexec.exe /x C:\SetupFiles\MySyncSvcSetup.msi /qb
Write-Host "Uninstalling Service"
$destinationFolder = "\\$computer\C$\SetupFiles"
#This section will copy the $sourcefile to the $destinationfolder. If the Folder does not exist it will create it.
if (!(Test-Path -path $destinationFolder))
{
New-Item $destinationFolder -Type Directory
}
Copy-Item -Path $sourcefile -Destination $destinationFolder
Write-Host "Files Copied Successfully"
C:\PSTools\psexec.exe \\$computer -s -u $adminUserName -p $adminPassword msiexec.exe /i C:\SetupFiles\MySyncSvcSetup.msi /qb /l* out.txt
Write-Host "Installed Successfully"
C:\PSTools\psexec.exe \\$computer -s -u $adminUserName -p $adminPassword sc.exe start $serviceName
Write-Host "Starting the Service"
}