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
Related
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
Currently I am trying to extract attachments from a list on SharePoint online. I found a code online that is supposed to do this but i get an error. The code that I found is a follows:
$webUrl = "https://mm.sharepoint.com/teams/pj-b0000"
$library = "Photos"
#Local Folder to dump files
$tempLocation = "C:\Users\C\Documents\temp"
$s = new-object Microsoft.SharePoint.SPSite($webUrl)
$w = $s.OpenWeb()
$l = $w.Lists[$library]
foreach ($listItem in $l.Items)
{
Write-Host " Content: " $listItem.ID
$destinationfolder = $tempLocation + "\" + $listItem.ID
if (!(Test-Path -path $destinationfolder))
{
$dest = New-Item $destinationfolder -type directory
}
foreach ($attachment in $listItem.Attachments)
{
$file = $w.GetFile($listItem.Attachments.UrlPrefix + $attachment)
$bytes = $file.OpenBinary()
$path = $destinationfolder + "\" + $attachment
Write "Saving $path"
$fs = new-object System.IO.FileStream($path, "OpenOrCreate")
$fs.Write($bytes, 0 , $bytes.Length)
$fs.Close()
}
}
but i get this error:
new-object : Cannot find type [Microsoft.SharePoint.SPSite]: verify that the assembly containing this type is loaded.
At C:\Users\C\Documents\SPListExtract.ps1:5 char:6
+ $s = new-object Microsoft.SharePoint.SPSite($webUrl)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidType: (:) [New-Object], PSArgumentException
+ FullyQualifiedErrorId : TypeNotFound,Microsoft.PowerShell.Commands.NewObjectCommand
You cannot call a method on a null-valued expression.
At C:\Users\C\Documents\SPListExtract.ps1:6 char:1
+ $w = $s.OpenWeb()
+ ~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
Cannot index into a null array.
At C:\Users\C\Documents\SPListExtract.ps1:7 char:1
+ $l = $w.Lists[$library]
+ ~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : NullArray
so i edited that code a bit but i only get the item in the list and not the attachments that are in the items. The code that i wrote is as follows:
Connect-PnPOnline -Url 'https://mm.sharepoint.com/teams/pj-b0000' -UseWebLogin
$tempLocation = "C:\Users\C\Documents\temp"
$list = Get-PnPListItem -List 'Photos'
foreach ($listItem in $list)
{
Write-Host " Content: " $listItem.ID
$destinationfolder = $tempLocation + "\" + $listItem.ID
if (!(Test-Path -path $destinationfolder))
{
$dest = New-Item $destinationfolder -type directory
}
foreach ($attachment in $listItem.Attachments)
{
$file = $w.GetFile($listItem.Attachments.UrlPrefix + $attachment)
$bytes = $file.OpenBinary()
$path = $destinationfolder + "\" + $attachment
Write "Saving $path"
$fs = new-object System.IO.FileStream($path, "OpenOrCreate")
$fs.Write($bytes, 0 , $bytes.Length)
$fs.Close()
}
}
I see my problem is the inside foreach loop for the $file variable I think. Would someone be able to help me with this?
Much thanks in advance.
The first line in your errors implies you do not have the assembly loaded:
new-object : Cannot find type [Microsoft.SharePoint.SPSite]: verify that the assembly containing this type is loaded.
These assemblies are only installed on a SharePoint server:
https://social.technet.microsoft.com/Forums/en-US/4a78ed2c-efde-40fa-800c-c4ecfa68a7c4/cannot-find-type-microsoftsharepointspsite-when-running-sharepoint-powerscript-in-a-windows-10?forum=sharepointdevelopment
I have a powershell script to delete a folder on a bunch of Windows hosts in our cluster.
It runs fine in the ISE and when running local from my laptop. however, I installed powershell on my Centos7.2 machine and when I try to run I get the following error
Join-Path : Cannot process argument because the value of argument "drive" is
null. Change the value of argument "drive" to a non-null value.
At /home/user/powershell/delete_.file.ps1:11 char:20
+ $newfilepath = Join-Path "\\$computer" "$file"
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Join-Path],
PSArgumentNullException
+ FullyQualifiedErrorId :
ArgumentNull,Microsoft.PowerShell.Commands.JoinPathCommand
Test-Path : Cannot bind argument to parameter 'Path' because it is null.
At /home/user/powershell/delete_.file.ps1:12 char:19
+ if (test-path $newfilepath) {
+ ~~~~~~~~~~~~
+ CategoryInfo : InvalidData: (:) [Test-Path],
ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.TestPathCommand
here is the code to the script
$filelist = #("C$\.file")
$computers = Get-Content /home/user/powershell/sw_win.txt
foreach ($file in $filelist)
{
foreach ($computer in $computers)
{
Write-Host -ForegroundColor Yellow "Analysing $computers"
$newfilepath = Join-Path "\\$computer" "$file"
if (test-path $newfilepath) {
Write-Host "$newfilepath Folder exists"
try
{
Remove-Item $newfilepath -Force -recurse -ErrorAction Stop
}
catch
{
Write-host "Error while deleting $newfilepath on $computer.
`n$($Error[0].Exception.Message)"
}
Write-Host "$newfilepath folder deleted"
} else {
Write-Information -MessageData "Path $newfilepath does not exist"
}
}
}
I think its because $computer is not set, but what doesn't make sense is it works fine using ISE.
Any help would be appreciated
I have a PowerShell script that works. For maintenance reasons I want to create another script where I'll put all the parameters that I'll call from my first script.
How can I create and call the parameter file?
Here is my script:
param([string] $dataSource = "server")
$Stamp = (Get-Date).toString("yyyy/MM/dd HH:mm:ss")
$Stamp1 = (Get-Date).toString("yyyy-MM-dd")
$Logfile = "E:\PowerShell\Log\file$stamp1.log"
$file = "file$stamp1.csv"
$extractFile = #"
E:\PowerShell\Output\$file
"#
[string]$sqlCommand1 =get-content -path E:\PowerShell\SQL\sql.sql
[string]$sqlCommand =$sqlCommand1
$authentication = ("User Id= user ;Password=pswd;" -f $plainCred.Username, $plainCred.Password)
Add-Type -assemblyname system.data
$factory = [System.Data.Common.DbProviderFactories]::GetFactory ("Teradata.Client.Provider")
$connection = $factory.CreateConnection()
$connection.ConnectionString = "Data Source = $dataSource;Connection Pooling Timeout=300;$authentication"
$connection.Open()
if ($connection.State -eq 'Open') {$logstring ="Connexion réussite"} else { $logstring ="echec Connexion" }
$command = $connection.CreateCommand()
$command.CommandText = $sqlCommand
$adapter = $factory.CreateDataAdapter()
$adapter.SelectCommand = $command
$dataset = new-object System.Data.DataSet
try
{
[void] $adapter.Fill($dataset)
$dataset.Tables | Select-Object -Expand Rows
}
finally
{
$connection.Close()
}
if (!$dataset) {$logstring1 ="extraction vide"} else {$logstring1 ="extraction réussite"}
($DataSet.Tables[0] | ConvertTo-Csv -delimiter ";" -NoTypeInformation ) -replace '"', "" | Out-File $extractFile -Force
$datafileExists = Test-Path $extractFile
if ($datafileExists)
{
$logstring2 ="Fichier data créé"
}
else
{
$logstring2 ="Fichier data non créé"
}
Add-content $Logfile -value ($Stamp+':'+$logstring)
Add-content $Logfile -value ($Stamp+':'+$logstring1)
Add-content $Logfile -value ($Stamp+':'+$logstring2)
I created a file of parameters
$Stamp1 = (Get-Date).toString("yyyy-MM-dd")
$Logfile = "E:\PowerShell\Log\file$stamp1.log"
$file = "file$stamp1.csv"
$extractFile = #"
E:\PowerShell\Output\$file
"#
$authentication = ("User Id= user ;Password=paswd;" -f $plainCred.Username, $plainCred.Password)
$Stamp = (Get-Date).toString("yyyy/MM/dd HH:mm:ss")
and I call it from my first script like that :
$ScriptPath = Split-Path $MyInvocation.InvocationName
& "$ScriptPath\param.ps1"
but my variables are not recognised, I have these errors:
Out-File : Cannot bind argument to parameter 'FilePath' because it is null.
At E:\PowerShell\script\Soft.ps1:59 char:104
+ ... "" | Out-File $extractFile -Force
+ ~~~~~~~~~~~~
+ CategoryInfo : InvalidData: (:) [Out-File], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.OutFileCommand
Test-Path : Cannot bind argument to parameter 'Path' because it is null.
At E:\PowerShell\script\Soft.ps1:61 char:29
+ $datafileExists = Test-Path $extractFile
+ ~~~~~~~~~~~~
+ CategoryInfo : InvalidData: (:) [Test-Path], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.TestPathCommand
Add-Content : Cannot bind argument to parameter 'Path' because it is null.
At E:\PowerShell\script\Soft.ps1:78 char:14
+ Add-content $Logfile -value ($Stamp+':'+$logstring)
+ ~~~~~~~~
+ CategoryInfo : InvalidData: (:) [Add-Content], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.AddContentCommand
Add-Content : Cannot bind argument to parameter 'Path' because it is null.
At E:\PowerShell\script\Soft.ps1:79 char:13
+ Add-content $Logfile -value ($Stamp+':'+$logstring1)
+ ~~~~~~~~
+ CategoryInfo : InvalidData: (:) [Add-Content], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.AddContentCommand
Add-Content : Cannot bind argument to parameter 'Path' because it is null.
At E:\PowerShell\script\Soft.ps1:80 char:13
+ Add-content $Logfile -value ($Stamp+':'+$logstring2)
+ ~~~~~~~~
+ CategoryInfo : InvalidData: (:) [Add-Content], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.AddContentCommand
IF you use '&' you execute the ps1 and the variables created are available within that scope. you can change the scope like this:
$test # default scope
$global:test # global scope
$script:test # script scope
The better solution is to use '.' in stead of '&' so you 're code from the ps1 is included in the other ps1.
so the scope is in the same because it is in the same script.
I have a strange problem when writing data to a new file. I have a list of files in a directory that contains data I'm parsing and returning data with the Create-VMwareconf() function. This returns the data in a hashtable that I've assigned to $t. I've pulled the desired folder and filename from the $t function however each time I begin the loop I get the following error for the initial folder creation, the second and third work fine. Interestingly enough the data that should be in the first file is present in the second folder.
If I run the script again it generates all three objects however the sequence of the of the data in the file matching the file name is incorrect.
Any help would be appreciated in how to stop the following error;
$e = (Get-Childitem ".\a\*\*.ini")
Set-Location "C:\WindowsRoot\vmwareconfigfiles\"
ForEach($d in $e){
$vmwaredirectory = New-item -type directory -path .\ -name $dd -Force
$vmwarefile = New-Item -type file -path $vmwaredirectory -name $dd -Force
$t = Create-VMwareconf($d)
$dd = $t.Value["0"]
#Write contents to new file
$t | Out-File $vmwarefile
}
Error received on initial run;
New-Item : Access to the path 'C:\WindowsRoot\vmwareconfigfiles' is denied.
At C:\WindowsRoot\parsedisrec.ps1:93 char:15
+ $vmwarefile = New-Item -type file -path $vmwaredirectory -name $dd -Force
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : PermissionDenied: (C:\WindowsRoot\vmwareconfigfiles:String) [New- Item], UnauthorizedAccessException
+ FullyQualifiedErrorId : NewItemUnauthorizedAccessError,Microsoft.PowerShell.Commands.NewItemCommand
Out-File : Cannot bind argument to parameter 'FilePath' because it is null.
At C:\WindowsRoot\parsedisrec.ps1:97 char:15
+ $t | Out-File $vmwarefile
+ ~~~~~~~~~~~
+ CategoryInfo : InvalidData: (:) [Out-File], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.OutFileCommand
New-Item -Type file fails during the first iteration, because $dd isn't yet initialized then, so you're trying to create a file with the same name as the current directory. You'd get the the same result if you used $null (or even .) as the name:
PS C:\> New-Item -Type file -Path 'C:\some\where' -Name $null -Force
New-Item : Access to the path 'C:\some\where' is denied.
At line:1 char:1
+ New-Item -Type file -Path 'C:\some\where' -Name $null -Force
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : PermissionDenied: (C:\some\where:String) [New-Item], UnauthorizedAccessException
+ FullyQualifiedErrorId : NewItemUnauthorizedAccessError,Microsoft.PowerShell.Commands.NewItemCommand
PS C:\> New-Item -Type file -Path 'C:\some\where' -Name '.' -Force
New-Item : Access to the path 'C:\some\where' is denied.
At line:1 char:1
+ New-Item -Type file -Path 'C:\some\where' -name '.' -Force
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : PermissionDenied: (C:\some\where\.:String) [New-Item], UnauthorizedAccessException
+ FullyQualifiedErrorId : NewItemUnauthorizedAccessError,Microsoft.PowerShell.Commands.NewItemCommand
Change this:
ForEach($d in $e){
$vmwaredirectory = New-item -type directory -path .\ -name $dd -Force
$vmwarefile = New-Item -type file -path $vmwaredirectory -name $dd -Force
$t = Create-VMwareconf($d)
$dd = $t.Value["0"]
into this:
ForEach($d in $e){
$t = Create-VMwareconf($d)
$dd = $t.Value["0"]
$vmwaredirectory = New-item -type directory -path .\ -name $dd -Force
$vmwarefile = New-Item -type file -path $vmwaredirectory -name $dd -Force