Powershell: how to assign path in the beginning of a script - powershell

As a beginner: How can I place a path to folder in Powershell script? I would like to hard-code a path to a folder where the rest of the script would do some data munging. How to do that?

Do you mean?
$path = "C:\Windows"
Get-ChildItem $path
This will let you reference path in cmdlet parameters.
As per your comment:
Set-Location C:\Windows
will change working directory of the script to C:\Windows

Related

PowerShell - Restore directory of script location while being ran as administrator

My Situation:
I have to run a PowerShell script as Administrator (because of accessing a privileged folder) and my script is also referencing files in the same directory as the script. I need to use a relative file path but I can't due to PowerShell switching the directory to C:\WINDOWS\system32 when ran as admin.
In PowerShell, is there a way to restore the directory to the current directory that the script is located?
My Script: (will be ran as admin)
Copy-Item -Path .\file1.txt -Destination 'C:\Users\privileged_folder'
Directory Structure:
MyDir\
file1.txt
myscript.ps1 <- ran as admin
By Changing Location
In your script, you can set the location to the script folder. From within your script, either of the following techniques will work:
# PowerShell 3+
cd $PSScriptRoot
# PowerShell 2
cd ( Split-Path -Parent $MyInvocation.MyCommand.Definition )
Changing to $PSScriptRoot works in all currently supported versions of PowerShell, but using Split-Path to get the script directory is useful if you for some reason still have nodes running PowerShell 2.
If you want to change back to the previous directory after your script is done executing (probably a good move) you can also make use of Push-Location and Pop-Location instead of cd or Set-Location:
# Also aliased to pushd
Push-Location $PSScriptRoot
# My script stuff
# Also aliased to popd
Pop-Location
These two cmdlets treat locations as a stack - Push-Location changes your location and adds the directory to the location stack while Pop-Location will remove the current directory from the stack and return you to the previous location. It works much like push and pop operations on arrays.
By Prefixing the Relative Paths
You could also prefix your relative paths in your script with either $PSScriptRoot or ( Split-Path -Parent $MyInvocation.MyCommand.Definition ) as shown in the previous section. If we attach the prefix to the otherwise relative path of file1.txt:
$filepath1 = "${PSScriptRoot}\file1.txt"
Now you have an absolute path to file1.txt. Note that this technique will work with any relative path to $PSScriptRoot, it does not have to be in the same folder as your ps1 script.

Change directory in PowerShell

My PowerShell prompt's currently pointed to my C drive (PS C:\>). How do I change directory to a folder on my Q (PS Q:\>) drive?
The folder name on my Q drive is "My Test Folder".
Unlike the CMD.EXE CHDIR or CD command, the PowerShell Set-Location cmdlet will change drive and directory, both. Get-Help Set-Location -Full will get you more detailed information on Set-Location, but the basic usage would be
PS C:\> Set-Location -Path Q:\MyDir
PS Q:\MyDir>
By default in PowerShell, CD and CHDIR are alias for Set-Location.
(Asad reminded me in the comments that if the path contains spaces, it must be enclosed in quotes.)
To go directly to that folder, you can use the Set-Location cmdlet or cd alias:
Set-Location "Q:\My Test Folder"
Multiple posted answer here, but probably this can help who is newly using PowerShell
SO if any space is there in your directory path do not forgot to add double inverted commas "".
You can simply type Q: and that should solve your problem.
Set-Location -Path 'Q:\MyDir'
In PowerShell cd = Set-Location
You can also use the sl command to be able to change directories. It is Set-Location but it is much shorter.
Example:
# Too verbose
Set-Location -Path C:\
# Just the right amount of characters to type
sl C:\
If your Folder inside a Drive contains spaces In Power Shell you can Simply Type the command then drive name and folder name within Single Quotes(''):
Set-Location -Path 'E:\FOLDER NAME'
The Screenshot is attached here
On Powershell use Set-Location instead of cd.
Put path in quotes. Single quotes works for me.
Set-Location 'C:\Program Files\MongoDB\Server\6.0'

batch file not adding folder structure correctly with spaces?

The batch file runs a PowerShell script. The issue is the path location has spaces. The batch file is only seeing the first word before the space.
SET targetDir="\\server.com\xxx\First Folder with spaces\Second folder with spaces"
SET archiveDir="\\server.com\xxx\First Folder with spaces\Second folder with spaces\Archive"
SET siteID=ABC
REM Run the import Powershell script for files.
powershell.exe -File D:\localPath\powershell\PowerShellScript.ps1 -Path "%targetDir%" -Filter *.dlu -Site %siteID% -ArchiveDir "%archiveDir%"
so when I run my PowerShell script it gets the parameters from the batch file
param
(
[string] $Path = $(Throw "You must specify a directory path containing the files to import."),
[string] $Filter = $(Throw "You must provide a file pattern/filter (e.g. *.dlu) to be used for locating the files to import"),
[string] $Site = $(Throw "You must provide a site identifier for the import."),
[string] $ArchiveDir = $null # If not provided, the imported files will be deleted rather than archived to another location.
)
but when I have the paths output to the screen I get:
Path= C:\First
Site= ABC
Archive= C:\First
What am I doing wrong?
If I run the .bat file with the hard code it works perfect.
REM SET targetDir="\\server.com\xxx\First Folder with spaces\Second folder with spaces"
REM SET archiveDir="\\server.com\xxx\First Folder with spaces\Second folder with spaces\Archive"
REM SET siteID=ABC
REM Run the import Powershell script for files.
powershell.exe -File D:\localPath\powershell\PowerShellScript.ps1 -Path "\\server.com\xxx\First Folder with spaces\Second folder with spaces" -Filter *.dlu -Site ABC -ArchiveDir "\\server.com\xxx\First Folder with spaces\Second folder with spaces\Archive"
It's because you are duplicating the quotes. You set the quotes in the SET targetDir= statement, then you also do the quotes again in your call to powershell.exe. The resulting command is:
powershell.exe -File D:\localPath\powershell\PowerShellScript.ps1 -Path ""\\server.com\xxx\First Folder with spaces\Second folder with spaces"" -Filter *.dlu -Site ABC -ArchiveDir ""\\server.com\xxx\First Folder with spaces\Second folder with spaces\Archive""
#MobyDisk already told what is the root cause of the problem at hand.
You should change your SET command lines in the batch file as follows:
SET "targetDir=\\server.com\xxx\First Folder with spaces\Second folder with spaces"
SET "archiveDir=\\server.com\xxx\First Folder with spaces\Second folder with spaces\Archive"
Note the moved opening quotation mark ". This change avoids the quotes to become part of the variable values.
(You could simply also remove all the quotes, but then you might run into trouble with some special characters like ^, &. Any % signs in the path need still to be doubled though not to be removed unintentionally.)

Power shell script for copying files with a specific name and a specific extension to a folder from where the script is executing

All,
My intention is to copy all the files with starting with the name 'US.Services' and with the extension .dll from a directory and its sub directories to the place where the script is being executed, i have the following but nothing gets copied. Any help would be appreciated.
Get-Childitem -Path ".\.\" -Filter *US.Services*.dll -Recurse |
Copy-Item -Destination "."
Thanks -Nen
Since PowerShell v3 can use the $PSScriptRoot automatic variable to refer to the location where the script is saved (in PowerShell v2 that would be $here = $MyInvocation.MyCommand.Path | Split-Path.
Be aware the both those approaches work only when the script is executed, if you just paste them to PowerShell console they won't return any value.
If I understand your question correctly you look for files that start with the given string and end with the extension, so you need to use the * wildcard here: US.Services*.dll.
Get-Childitem -Path $PSScriptRoot -Recurse -Filter "US.Services*.dll" |
Copy-Item -Destination $PSScriptRoot
This will likely produce exceptions if there are files with the same name copied to the single directory, as two files cannot be named the same within single directory.

Why is PowerShell resolving paths from $home instead of the current directory?

I expect this little powershell one liner to echo a full path to foo.txt, where the directory is my current directory.
[System.IO.Path]::GetFullPath(".\foo.txt")
But it's not. It prints...
C:\Documents and Settings\Administrator\foo.txt
I am not in the $home directory. Why is it resolving there?
[System.IO.Path] is using the shell process' current directory. You can get the absolute path with the Resolve-Path cmdlet:
Resolve-Path .\foo.txt
According to the documentation for GetFullPath, it uses the current working directory to resolve the absolute path. The powershell current working directory is not the same as the current location:
PS C:\> [System.IO.Directory]::GetCurrentDirectory()
C:\Documents and Settings\user
PS C:\> get-location
Path
----
C:\
I suppose you could use SetCurrentDirectory to get them to match:
PS C:\> [System.IO.Directory]::SetCurrentDirectory($(get-location))
PS C:\> [System.IO.Path]::GetFullPath(".\foo.txt")
C:\foo.txt