Some Useful PowerShell Commands
1. Reads a line of input from the console. Prompt user to input a value for a variable
$Name = Read-Host -Prompt 'Input your Name '
2. Inserting blank lines or new empty line in PowerShell Console or write message on PowerShell Console
write-host "`n" or write-host "My name is $Name"
3. Assigning string value to variable with the input from user inserted in it. Make sure it is within double quotes.
$path = "C:\users\$Name"
4. Check whether folder/file exists or not
If(!(test-path $path)) { write-host "$path does not exist" }
5. Create new file or folder if it doesn’t exist
$path = "C:\users\$Name" If(!(test-path $path)) { New-Item -ItemType Directory -Force -Path $path }
or
$path = "C:\users\$Name\test.txt" If(!(test-path $path)) { New-Item -Path $path -ItemType "file" }
6. Update System Environment variable values permanent from within PowerShell Console.
$path = "C:\users\$Name" $oldpath = (Get-ItemProperty -Path 'Registry::HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Session Manager\Environment' -Name PATH).path #append $path value to $oldpath $newpath = “$oldpath;$path” #update the $newpath value to system environment value Set-ItemProperty -Path 'Registry::HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Session Manager\Environment' -Name PATH -Value $newPath
7. Download exe using http url and save the file in folder
Invoke-WebRequest -Uri https://dl.k8s.io/release/v1.21.0/bin/windows/amd64/kubectl.exe -OutFile "C:\tmp\kubectl.exe"
8. Download a zip file and unzip it in specified folder
Invoke-WebRequest -Uri https://curl.se/windows/dl-7.77.0_2/curl-7.77.0_2-win64-mingw.zip -OutFile "C:\tmp\curl-7.77.0.zip" Expand-Archive -LiteralPath "C:\tmp\curl-7.77.0.zip" -DestinationPath "C:\tmp\curl-7.77.0"
9. Write content into a file or update data to a file
$path = "C:\users\testuser" Set-Content -Path $path\test.txt -Value "This is new Text file"
10. Update data to a file which has double quotes on it. Wrap data in double quotes then the single quote will be inserted in file.
$path = "C:\users\testuser" Set-Content -Path $path\test.txt -Value "This is ""Double Quote"" value in new Text file"