Script block if and variable - powershell

my path var which right now I set directly is:
00257d48e8260671794a3c2cfc3fb2d1 My Pictures/Tony/Automatic Upload/Tony’s iPhone/2022-11-13 10-57-52.mov
20e2128b66ded28cc59eb764209ddacd My Pictures/Mom/Automatic Upload/Tony’s iPhone/2022-11-12 09-26-27.dng
44e2128b66de428cc59eb764209ddacd My Pictures/Mom/Automatic Upload/Tony’s iPhone/2024-11-12 09-26-27.dng
in my code this is getting set further up in a foreach loop foreach ($path in $diffmd5.value) {}
heres the get type
$path.GetType()
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True ScriptBlock System.Object
seems like there's an issue using the variable inside the if ?
if ($path | Select-String -Pattern 'My Pictures\/Mom\/') {
>> $path2 = Split-Path -Path $path -Leaf }
Split-Path : Cannot evaluate parameter 'Path' because its argument is specified as a script block and there is no
input. A script block cannot be evaluated without input.
At line:2 char:28
+ $path2 = Split-Path -Path $path -Leaf }
+ ~~~~~
+ CategoryInfo : MetadataError: (:) [Split-Path], ParameterBindingException
+ FullyQualifiedErrorId : ScriptBlockArgumentNoInput,Microsoft.PowerShell.Commands.SplitPathCommand
some issue here? https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_script_blocks?view=powershell-7#using-delay-bind-script-blocks-with-parameters

Related

What is the purpose of Target in Get-ItemProperty of powershell

enter image description here
I am wondering what's the purpose of Target? If the type of Target is hash, how to set the key/value.
PS Set-ItemProperty -Path a.txt -Name Target -Value { "key1":"value1"}
At line:1 char:58
+ Set-ItemProperty -Path a.txt -Name Target -Value { "key1":"value1"}
+ ~~~~~~~~~
Unexpected token ':"value1"' in expression or statement.
+ CategoryInfo : ParserError: (:) [], ParentContainsErrorRecordException
+ FullyQualifiedErrorId : UnexpectedToken
As for your post title:
What is the purpose of Target in Get-ItemProperty of powershell
Use Get-Member to find out.
(Get-ItemProperty -Path 'D:\temp\ZenMusic.mp3' |
Get-Member) -match 'Target' |
Format-List
# Results
<#
TypeName : System.IO.FileInfo
Name : Target
MemberType : CodeProperty
Definition : System.Collections.Generic.IEnumerable`1[[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]
Target{get=GetTarget;}
#>
As you can see, there is no setter for this property.
There is a target property for symlinks that's just a string, but it can't be set with set-itemproperty (Set accessor is unavailable).
New-Item -Path c -ItemType SymbolicLink -Value c:\ # elevated prompt
get-item c | % target | % gettype
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True String System.Object
get-itemproperty -path c -name target
target : {C:\}
PSPath : Microsoft.PowerShell.Core\FileSystem::C:\Users\admin\foo\c
PSParentPath : Microsoft.PowerShell.Core\FileSystem::C:\Users\admin\foo
PSChildName : c
PSDrive : C
PSProvider : Microsoft.PowerShell.Core\FileSystem
Set-ItemProperty -Path c -Name Target -Value c:\users
Set-ItemProperty : Set accessor for property "Target" is unavailable.
At line:1 char:1
+ Set-ItemProperty -Path c -Name Target -Value c:\users
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [Set-ItemProperty], SetValueException
+ FullyQualifiedErrorId : SetWithoutSetterFromCodeProperty,Microsoft.PowerShell.Commands.SetItemPropertyCommand

Find & Replace text from multiple specific files from sub folders dynamically using powershell

I am working on azure CD pipeline, i want to change content of multiple files which exist in following folder structure.
MainFolder => SubFolder1 => myFile1.txt
SubFolder2 => myFile2.txt
SubFolder3 => myFile3.txt
I want to achieve my above requirement using powershell, and i have tried the following code.
$filepath = 'C:\Users\ashishjain06\Desktop\MainFolder'
$mydata = Get-ChildItem $filepath -include *.txt -recurse | Select-Object fullName
$totalRecords = $mydata.Count
for($x = 0; $x -lt $totalRecords; $x++)
{
((Get-Content -path $mydata[$x] -Force) -replace 'oldText','newText') | Set-Content -Path $mydata[$x]
}
When i run above code it's give me following output.
Get-Content : Cannot find drive. A drive with the name '#{FullName=C' does not exist.
At line:6 char:7
+ ((Get-Content -path $mydata[$x] -Force) -replace 'oldText ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (#{FullName=C:String) [Get-Content], DriveNotFoundException
+ FullyQualifiedErrorId : DriveNotFound,Microsoft.PowerShell.Commands.GetContentCommand
Get-Content : Cannot bind argument to parameter 'Path' because it is null.
At line:6 char:25
+ ((Get-Content -path $mydata[$x] -Force) -replace 'oldText ...
+ ~~~~~~~~~~~
+ CategoryInfo : InvalidData: (:) [Get-Content], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.GetContentCommand
Get-Content : Cannot bind argument to parameter 'Path' because it is null.
At line:6 char:25
+ ((Get-Content -path $mydata[$x] -Force) -replace 'oldText ...
+ ~~~~~~~~~~~
+ CategoryInfo : InvalidData: (:) [Get-Content], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.GetContentCommand
Get-Content : Cannot bind argument to parameter 'Path' because it is null.
At line:6 char:25
+ ((Get-Content -path $mydata[$x] -Force) -replace 'oldText ...
+ ~~~~~~~~~~~
+ CategoryInfo : InvalidData: (:) [Get-Content], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.GetContentCommand
Get-Content : Cannot bind argument to parameter 'Path' because it is null.
At line:6 char:25
+ ((Get-Content -path $mydata[$x] -Force) -replace 'oldText ...
+ ~~~~~~~~~~~
+ CategoryInfo : InvalidData: (:) [Get-Content], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.GetContentCommand
I am newbie on powershell, Please help me out to resolve this issue.
Get-ChildIItem returns (an array of) FileInfoObjects with a bunch of properties,
Select-Object drops all but the selected one, but it is still an object with one property FullName.
See $mydata | Get-Member
One method is Select-Object -ExpandProperty FullName,
another one is the property dereference operator . used in the following script.
To have the script work on any user don't include a fixed path, either use $Env:USERPROFILE or better yet, let the system evaluate current users Desktop folder (which might be relocated).
Instead of iterating the arrray $mydata by index let powershell do that with a foreach:
$filepath = Join-Path ([environment]::GetFolderPath('Desktop')) 'MainFolder'
$files = (Get-ChildItem $filepath -Filter *.txt -Recurse).FullName
foreach($file in $files){
(Get-Content -path $file -Force) -replace 'oldText','newText' | Set-Content -Path $file
}
It's still an object with a property unless you do this:
select-object -expandproperty fullname
Replace Select-Object with ForEach-Object, i.e.:
$filepath = 'C:\Users\ashishjain06\Desktop\MainFolder'
#$mydata = Get-ChildItem $filepath -include *.txt -recurse | Select-Object fullName
$mydata = Get-ChildItem $filepath -include *.txt -recurse | ForEach-Object fullName
$totalRecords = $mydata.Count
for($x = 0; $x -lt $totalRecords; $x++)
{
((Get-Content -path $mydata[$x] -Force) -replace 'oldText','newText') | Set-Content -Path $mydata[$x]
}

PS script to bookmark URL in IE

I have written a PS script which will create bookmarks in IE. I need to execute below command before running the ps script.
Set-ExecutionPolicy -Scope Process -ExecutionPolicy Bypass -force
How can I avoid executing above cmd before executing ps script? Or Can anyone suggest me to convert this as .exe or .bat file?
And this script fails if Favourites folder doesn't exist and how can I avoid using favourites folder in this script.
My PS script:-
function create-bookmarks{
$bookmarks = #{
"folder1" = #{
"Jenkins" = "https://jenkins.net";
};
"folder2" = #{
"Jenkins" = "https://jenkins.net";
};
}
foreach ($Name in $bookmarks.keys)
{
$IEFav = [Environment]::GetFolderPath('Favorites','None')
New-Item $IEFav\$Name -ItemType Directory -Force
$Shell = New-Object -ComObject WScript.Shell
$IEFav = Join-Path -Path $IEFav -ChildPath $Name
foreach ($key in $bookmarks[$Name].keys)
{
$FullPath = Join-Path -Path $IEFav -ChildPath "$($key).url"
$shortcut = $Shell.CreateShortcut($FullPath)
$shortcut.TargetPath = $bookmarks[$Name][$key]
$shortcut.Save()
}
}
}
create-bookmarks
Error if Favourite folder does not exists under c:/users/username/Favourites.
PS C:\Users\username\downloads\Bookmarks> .\Bookmarks.ps1
Cannot find an overload for "GetFolderPath" and the argument count: "2".
At C:\Users\username\downloads\Bookmarks\Bookmarks.ps1:27 char:45
+ $IEFav = [Environment]::GetFolderPath <<<< ('Favorites','None')
+ CategoryInfo : NotSpecified: (:) [], MethodException
+ FullyQualifiedErrorId : MethodCountCouldNotFindBest
Directory: C:\
Mode LastWriteTime Length Name
---- ------------- ------ ----
d---- 8/22/2018 6:44 PM DevOps
Join-Path : Cannot bind argument to parameter 'Path' because it is null.
At C:\Users\username\downloads\Bookmarks\Bookmarks.ps1:30 char:31
+ $IEFav = Join-Path -Path <<<< $IEFav -ChildPath $Name
+ CategoryInfo : InvalidData: (:) [Join-Path], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.JoinPathCom
mand

Get-ChildItem : A parameter cannot be found that matches parameter name 'Directory' [duplicate]

This question already has answers here:
A parameter cannot be found that matches parameter name 'directory'
(2 answers)
Closed last year.
I am getting Get-ChildItem : *A parameter cannot be found that matches parameter name 'Directory'* error message , below is the script used, kindly help me in finding the issue?
Script:
Function Clear-ReadOnlyFiles([string]$path)
{
"Clearing readonly attribute from files in $path"
New-Variable -Name read_only -Value 1 -Option readonly
Get-ChildItem -Path $path |
Where-Object { $_.attributes -match 'readonly' } |
ForEach-Object {
$_.attributes = $_.attributes -Bxor $read_only }
}#end Clear-ReadonlyFiles
$ZipCmd = "{0}\7za.exe" -f $BackupDir
$ZipCmdArgs = "-sdel"
# Grab Directories in Location
$Directories = Get-ChildItem -Path $BackupDir -Directory
# Cycle Through and Launch 7za to Compress
# Check if Archive Exists - If yes, delete source folder
ForEach ($Directory in $Directories)
{
$Source = "{0}\{1}" -f $BackupDir,$Directory.Name
$Archive = "{0}.7z" -f $Source
# Clear Read-Only Attribute on Folder
$SubFiles = Get-ChildItem -Path $Directory -Recurse -ReadOnly
ForEach ($SubFile in $SubFiles) {
$SubFile.IsReadOnly = $False
}
#If ($Directory.IsReadOnly -eq $True) { $Directory.set_IsReadOnly($False) }
$AllArgs = #('a', $ZipCmdArgs, $Archive, $Source);
& $ZipCmd $AllArgs
}
Error message:
Get-ChildItem : A parameter cannot be found that matches parameter name 'Directory'.
At C:\Play\BackupCompress.ps1:35 char:57
+ $Directories = Get-ChildItem -Path $BackupDir -Directory <<<<
+ CategoryInfo : InvalidArgument: (:) [Get-ChildItem], ParameterBindingException
+ FullyQualifiedErrorId : NamedParameterNotFound,Microsoft.PowerShell.Commands.GetChildItemCommand
Get-ChildItem : A parameter cannot be found that matches parameter name 'ReadOnly'.
At C:\Play\BackupCompress.ps1:45 char:66
+ $SubFiles = Get-ChildItem -Path $Directory -Recurse -ReadOnly <<<<
+ CategoryInfo : InvalidArgument: (:) [Get-ChildItem], ParameterBindingException
+ FullyQualifiedErrorId : NamedParameterNotFound,Microsoft.PowerShell.Commands.GetChildItemCommand
Property 'IsReadOnly' cannot be found on this object; make sure it exists and is settable.
At C:\Play\BackupCompress.ps1:47 char:18
+ $SubFile. <<<< IsReadOnly = $False
+ CategoryInfo : InvalidOperation: (IsReadOnly:String) [], RuntimeException
+ FullyQualifiedErrorId : PropertyNotFound
I believe that the Directory switch was added in PowerShell 3.0. In older versions you will need to check the PSIsContainer property of each child item, which will be true if the item is a directory:
$Directories = Get-ChildItem -Path $BackupDir | Where-Object { $_.PSIsContainer }
-Directory is a conditional parameter and only works on paths whose provider is "FileSystem". It's present on this page: Get-ChildItem for FileSystem, but not on the generic one.
Make sure that the correct provider appears when you type the following:
Get-Item $BackupDir | Select-Object -Property PSProvider

PowerShell v4 Get-Content : A parameter cannot be found that matches parameter name 'Delimiter'

I am hoping someone can give me the push I need to get this done, but I have had no luck with this exact situation online.
I need to use PowerShell (unfortunately I can't use Python or .NET to so this:( ) to parse though a list of files to determine if they contain a line termination of /r rather than /r/n. This script was previously in production and working, when single files were passed.
I am making adjustments so that multiple files can be accommodated.
I am getting the list of filenames and putting them into an array (which is working) but when I tey to loop the files through the if statement I get this error.
Here is my code:
param(
#[Parameter(Mandatory=$True)]
[String]$FileName = "C:\LineTermTest\*C*.txt"
)
$FileNameArray = Get-ChildItem -Path $FileName | where {!$_.psicontainter }| Select-Object fullname
for ($i=0; $i -le $FileNameArray.Length -1; $i++ )
{
$File = $FileNameArray[$i]
if (Get-Content -path $File -Delimiter "`0" | Select-String "[^`r]`n" )
{
$content = Get-Content $File
$content | Set-Content $File -Replace "`n", "'r'n" -Encoding ASCII
[gc]::collect()
[gc]::WaitForPendingFinalizers()
}
}
and here is the error I get
Get-Content : A parameter cannot be found that matches parameter name 'Delimiter'.
At line:13 char:39
+ if (Get-Content -path $File -Delimiter <<<< "0" | Select-String "[^r]`n" )
+ CategoryInfo : InvalidArgument: (:) [Get-Content], ParameterBindingException
+ FullyQualifiedErrorId : NamedParameterNotFound,Microsoft.PowerShell.Commands.GetContentCommand
Get-Content : A parameter cannot be found that matches parameter name 'Delimiter'.
At line:13 char:39
+ if (Get-Content -path $File -Delimiter <<<< "0" | Select-String "[^r]`n" )
+ CategoryInfo : InvalidArgument: (:) [Get-Content], ParameterBindingException
+ FullyQualifiedErrorId : NamedParameterNotFound,Microsoft.PowerShell.Commands.GetContentCommand
Get-Content : A parameter cannot be found that matches parameter name 'Delimiter'.
At line:13 char:39
+ if (Get-Content -path $File -Delimiter <<<< "0" | Select-String "[^r]`n" )
+ CategoryInfo : InvalidArgument: (:) [Get-Content], ParameterBindingException
+ FullyQualifiedErrorId : NamedParameterNotFound,Microsoft.PowerShell.Commands.GetContentCommand
in your script, $File is a 'PSCustomObject', not a FileInfo object, so you need to use its property 'fullname' like this: Get-Content -path $File.fullname -Delimiter "`0". This is because the objects in $FileNameArray are created by using Select-Object.
You can avoid this by leaving out "| Select-Object fullname" when creating $FileNameArray. That way, the $FileNameArray contains FileInfo objects, and Get-Content can use those directly. This is the preferred way.
So this line:
$FileNameArray = Get-ChildItem -Path $FileName | where {!$_.psicontainter }| Select-Object fullname
becomes this line:
$FileNameArray = Get-ChildItem -Path $FileName | where {!$_.psicontainter }