Question

What is the best way to declare full paths in Powershell? I am writing a module that needs to pass full file path variables (ex: $Backup = C:\backups\file1.bak) through multiple psm1 files and is called remotely.

Right now, I need to pass a fully qualified path to Powershell and have it do a lot of different things with it. It seems to work fine when it's all in 1 functional script, otherwise, the path doesn't actually go through to other functions written in other PSM1 files, but all other variables do. It seems to just output a null value.

First I have a FileValidator script which among other things, will find the latest filename in the path, and then concat the latest filename, with the path. Perhaps I need to use joinpath somewhere to fix this is. The code to get the fully qualified path that isn't exporting to other PSM1 files is:

Param: [string] $BackupPath, #= "Z:\backupsfldr\subfldr\"

$LatestSQLBackupDBFileName = Get-ChildItem $BackupPath | Where-Object{($_.LastWriteTime -gt "2014/02/01") -and ($_.Name -like "$DBname*.bak")} | Sort-Object LastWriteTime -Descending | Select-Object -First 1 | select -ExpandProperty name 

$FQNBackup = get-item($BackupPath + $LatestSQLBackupDBFileName)

As you can see, I was testing the output of $FQNBackup in various places but it just made things worse. I'm not sure how to define this in the modules or how to cast/convert it. After declaring the $FQNBackup variable as listed above, I then modify it by trying to do this as found else where on stackoverflow earlier:

$FQNBackup = [System.IO.Path]::GetFullPath($FQNBackup)

I've tried converting it to a string as well but I might be doing it wrong. It seems like I should be able to:

1- Get the path

2- Convert to string

3- Pass the value as a string to other modules.

However is this 'bad' from an architecture design view? Should I just keep it the same object type instead as it jumps from different psm's? That is the real question.

Was it helpful?

Solution

If you need to construct a path from 2 strings you'd normally use the Join-Path cmdlet, e.g. like this:

PS C:\> Join-Path 'C:\some\folder' 'file.ext'
C:\some\folder\file.ext

However, when handling existing files like you do, you could simply use the file object's FullName property:

$FQNBackup = Get-ChildItem $BackupPath | Where-Object {
  $_.LastWriteTime -gt "2014/02/01" -and $_.Name -like "$DBname*.bak"
} | Sort-Object LastWriteTime -Descending | select -First 1 -Expand FullName 

Strings can be passed into functions via string arguments, e.g. like this:

function Foo {
  [CmdletBinding()]
  Param(
    [Parameter(Mandatory=$true)]
    [string]$Bar
  )

  # do stuff
}

Foo -Bar 'some string'
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top