Powershell Dynamic path location for files - powershell

I'm trying to make a script that installs apps etc. the script contains 7 ps1 scripts and they are linked together but when I move the folder the script won't work since the path changed is there a way so I can always have the right path?
& 'Z:\Windows installatie\Scripts\Menus\Apps.ps1'
this is when it's from a USB but the drive letter always changes.
I tried using a wild card but that didn't work.
& '*\Windows installatie\Scripts\Menus\Apps.ps1'

If you would like to test for the existence of a folder or file under an unknown drive letter, and you know the path is going to be unique enough, then you could just test for it by iterating through Get-PSDrive -PSProvider FileSystem.
$Drive = Get-PSDrive -PSProvider FileSystem | Where-Object { Test-Path ($_.Root + "path\to\myScript.ps1") }
if ($null -ne $Drive -and $Drive.Count -eq 1) {
& (Join-Path -Path $Drive.Root -ChildPath "path\to\myScript.ps1")
}
Not incredibly elegant, but will do the job.
If you know that you only have one USB mounted at a time, then you could also check for details about the drive that is a USB.

Related

Accessing USB stick without drive letter

I am using powershell 2.0 in windows 7.
I would like to copy a file from my USB stick to a directory on my main hard drive using cmd or powershell. However, I need this to function on any PC without any input of the USB's current drive letter. In case that didn't make sense, let me rephrase it. I need a powershell or cmd command/ batch script to copy a file from my USB stick to my hard drive without any input.
Ideal command would assign the variable mydrive to the drive letter and allow me to run something like this in cmd
copy myvar:/path/fileToCopy.txt/ C:/path/of/target/directory/
I would really appreciate if I could use just my USB sticks name ('DD') to copy like this:
copy DD:/path/fileToCopy.txt/ C:/path/of/target/directory/
I've done well over an hours worth of research trying to find a way to pull this off and can't. Any help is greatly appreciated. Especially if it is clear how to use it. I am very new to powershell and cmd commands and don't understand the syntax. So stuff like [put drive name here] to show me how to use it would be amazing and is where a lot of forums are missing out.
You can do this like below:
$destination = 'C:\path\of\target\directory'
$sourceFile = 'path\fileToCopy.txt' # the path to the file without drive letter
# get (an array of) USB disk drives currently connected to the pc
$wmiQuery1 = 'ASSOCIATORS OF {{Win32_DiskDrive.DeviceID="{0}"}} WHERE AssocClass = Win32_DiskDriveToDiskPartition'
$wmiQuery2 = 'ASSOCIATORS OF {{Win32_DiskPartition.DeviceID="{0}"}} WHERE AssocClass = Win32_LogicalDiskToPartition'
$usb = Get-WmiObject Win32_Diskdrive | Where-Object { $_.InterfaceType -eq 'USB' } |
ForEach-Object {
Get-WmiObject -Query ($wmiQuery1 -f $_.DeviceID.Replace('\','\\')) #'# double-up the backslash(es)
} |
ForEach-Object {
Get-WmiObject -Query ($wmiQuery2 -f $_.DeviceID)
}
# loop through these disk(s) and test if the file to copy is on it
$usb | ForEach-Object {
# join the DeviceID (like 'H:') with the file path you need to copy
$file = Join-Path -Path $_.DeviceID -ChildPath $sourceFile
if (Test-Path -Path $file -PathType Leaf) {
Copy-Item -Path $file -Destination $destination
break # exit the loop because you're done
}
}
Hope that helps
If you upgrade your version of PowerShell, you can replace the Get-WmiObject with Get-CimInstance for better performance. See this and that

Using Powershell to test-path on a network drive

I can't get the Test-Path cmdlet to find a folder on a remote system's additional drive.
The following works for the system drive.
Test-Path -PATH '\\ServerName\C$\FolderName'
The next example always returns false.
Test-Path -PATH '\\ServerName\D$\FolderName'
I have verified the path and its spelling. Test-Path will find the path if I remote to the computer and run
Test-Path -PATH 'D:\FolderName'
I must be missing something. Will someone please enlighten me?
You need specified the UNC path in this way.
$path = 'filesystem::\\servername\D$\FolderName'
If(Test-path -Path $path){
Your code....
}
https://blogs.technet.microsoft.com/heyscriptingguy/2013/01/13/powertip-test-the-presence-of-a-remote-share-by-using-powershell/
Chances are the d-drive in this instance is not a logical disk on ServerName but a remote drive...
The Get-PSDrive CmdLet will return the details of the various drives available to your machine.
Get-PSDrive -PSProvider FileSystem will return, as you guessed it, file system drives! Pay particular attention to the Root property as this will show whether the drive in question is logical or remote.
You need to run this CmdLet when logged on the box, or alternatively you can use the Invoke-Command something like so:
Invoke-Command -ComputerName "ServerName" -Credential $(Get-Credential) -ScriptBlock {
Get-PSDrive -PSProvider FileSystem
}
You mention in one of the comments that it is a thumbdrive. Thumbdrives are not administratively shared by windows and therefore that share does not exist.
If you create a folder on the thumbdrive, such as d:\test and share that as "test", then you can test-path to "\servername\test" and get a good result.

Using a mapped drive as a variable

We're looking at swapping a file server with a newer one. The new one will have a new IP and name.
My aim is to remove the mapped drive our users have for the current server and replace it with a new one. The problem is our users have it on different letters. So I need to run a script that will replace the UNC path regardless of drive letter.
My script so far can find me the drive letter, but it's not removing the mapping.
--
Get-PSDrive | ForEach {
If ( $_.DisplayRoot -eq '\\OLDSERVER\PATH' ) {
Remove-PSDrive -Name $_.Name
New-PSDrive –Name $_.Name –PSProvider FileSystem –Root "\\NEWSERVER\PATH" –Persist
}
}
Powershell cannot remove a mapping it didnt put in. I've changed it to a net-use command and it works.

copy a directory from a remote system to a USB drive replace a hardware image and then copy the directory back sounds simple enough

Thought this would be simple but.. i'm not a programmer im just trying to make something more efficient than having to re-type command after command on 20 systems mistakes happen.
so what im trying to do is copy a directory from a remote system to a USB drive replace a hardware image and then copy the directory back sounds simple enough I think it may be a double hop issue but I am lacking in how to fix it I am using a Domain Admin acccount and running powershell as administrator.
Clear #Clear Screen
$USBDrive = read-host -prompt "Drive letter for USB Drive?" #Get Drive Letter for EXT Media
cd $USBDrive':' #Change to external media drive
$BGM = read-host -prompt "# of BGM's?" #QTY of BGM's
# Create copies of Convertor Files
DO{
Write-Host BGM# $BGM
Test-Path \\172.16.10.$BGM"\c$\Program Files\Box Tech\BoxManager Version 3.7\172.16.10."$BGM"_cvtrdata"
New-item \App0$BGM -itemType Directory
Copy-Item -path \\172.16.10.$BGM"\c$\Program Files\Box Tech\BoxManager Version 3.7\172.16.10."$BGM"_cvtrdata" -destination \\App0$BGM\ -Recurse
$BGM = $BGM - 1
}
WHILE($BGM -gt 0)
Test-Path returns that it directory does not exist, Test-Path \172.16.10.$BGM"\c$\Program Files\Box Tech\BoxManager Version 3.7\172.16.10."$BGM"_cvtrdata"
If I use the exact path it returns true in test-path Test-Path "\172.16.10.1\c$\Program Files\Box Tech\BoxManager Version 3.7\172.16.10.1_cvtrdata"
but the copy fails I wold even be happy using robocopy to copy the files.

Count files in a network folder using PowerShell

I've searched numerous MSDN/Technet and StackOverflow articles regarding this but I can't find a solution to my problem.
SO references below.
I am trying to run a script on my server that simply counts the files in a folder on a network location.
I can get it working if it's a local folder, and I can get it working when I map the network drive. However I can't use a network drive because I'll be running this script from a web interface that doesn't have a user account (local drives work fine).
My script is:
$Files = Get-ChildItem \\storage\folder -File
$Files.count
I get the error:
Get-ChildItem : Cannot find path '\\storage\folder' because it does not exist.
[0]open folder from Network with Powershell
[1]File counting with Powershell commands
[2]Count items in a folder with PowerShell
[3]Powershell - remote folder availability while counting files
Two things that I can think of,
One would be to add -path to your get-childitem call. I tested this on my Powershell and it works fine.
$files = get-childitem -path C:\temp
$files.count
This returns the number of files in that path.
However I am testing this on a local file. If you are sure it is the remote access part giving you trouble I would suggest trying to set credentials. Besides the get-credentials option, you could also try setting them yourself.
$Credentials = New-Object System.Management.Automation.PsCredential("Username", "password")
Then perhaps you can set the drive and still be able to access your files. Hope that helps.
Try this:
set-location \\\storage\folder\
dir -recurse | where-object{ $_.PSIsContainer } | ForEach{ Write-Host $_.FullName (dir $_.FullName | Measure-Object).Count }
This will count the number of files in each sub-folder (recurse) and display the full path and count in the output.