Creating a parameter script with PowerShell to be called by another script - powershell

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.

Related

Cannot bind argument to parameter 'Path' because it is null. Parameter does not seem to be null at all

Checking if a file exists on a remote machine:
#Check if Dir exists on the machine we are copying from
$dir = ($APPROD001Root + $instance + "\" + $type + "\" + $year + "\" + $monthFormatted)
Write-Host $dir
if(Test-Path -Path $dir){
Write-Host ($dir + " exists!")
$files = Get-ChildItem -Path $dir
#Check if the Dir has files in it
if($files.Length -gt 0){
#Check if the folder exists on the machine we are copying towards, if not create it!
$dirReceivingMachine = ($DBStag01Root + $instance + "\" + $type + "\" + $year + "\" + $monthFormatted)
Write-Host $dirReceivingMachine
if($dirReceivingMachine -eq $null){
Write-Host "the path is null..."
}
$folderExists = Invoke-Command -ScriptBlock { Test-Path -Path $dirReceivingMachine } -Session $session
if(!$folderExists){
Write-Host ("folder " + $dirReceivingMachine + " does not yet exist we want to create it!")
#Invoke-Command - ScriptBlock { New-Item -Path $dirReceivingMachine -ItemType Directory } -Session $session
}
The invoke-command that sets the $folderExists always throws
Cannot bind argument to parameter 'Path' because it is null.
+ CategoryInfo : InvalidData: (:) [Test-Path], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.TestPathCommand
the output I get in terminal is
D:MyData\2018\09
D:\MyData\2018\09 exists!
D:\MyData\2018\09 Cannot bind argument to
parameter 'Path' because it is null.
+ CategoryInfo : InvalidData: (:) [Test-Path], ParameterBindingValidationException
As you can see the Write-Host "The path is null.." never fires, so the variable I am passing into Test-Path is not null yet PS says it is when invoking the command...
No idea why it does this

Why does export-csv not run properly in Powershell on SQL Server?

I am no expert with Powershell; however, I am trying to simply run an Invoke-Sqlcmd and save the results as a .csv file. I am looping through multiple *.sql files as the queries. When I run the following Powershell from a Windows10 desktop, everything runs fine but when I run this from our SQL Server, I am receiving errors on the export-csv command.
Here is my Powershell:
#Prompt for date
$DatePrompt = Read-Host -Prompt 'Enter the database date. (YYYY-MM-DD)'
#Convert to date
$DatabaseDate = [DateTime]::Parse($DatePrompt)
#Create FileDate string
$FileDate = $DatabaseDate.ToString("yyyyMMdd")
#Create SQLDate string
$SQLDate = $DatabaseDate.ToString("yyyy-MM-dd")
#--------------------------------------------------------------------------------------------------------------------------------
#Provide SQLServerName
$SQLServer ="SQLSERVER\MISDATA"
#Provide Database Name
$DatabaseName ="StagingDB"
#Set MonthStart and MonthEnd (YYYY-MM-DD)
$Variables = "FileDate = $SQLDate"
#Scripts Folder Path
$FolderPath ="\\SQLSERVER\MISDATA\Queries"
#Output Folder Path
$OutputFolderPath ="\\SQLSERVER\MISDATA\Results"
#--------------------------------------------------------------------------------------------------------------------------------
#Loop through the .sql files and run them
foreach ($filename in get-childitem -path $FolderPath -filter "*.sql")
{ #Run SQL Query
Invoke-Sqlcmd -ServerInstance $SQLServer -Database $DatabaseName -InputFile $filename.fullname -Variable $Variables -Querytimeout 0|
#Export to CSV
Export-Csv -NoTypeInformation -Path ($OutputFolderPath + "\" + $FileDate + "-" + $filename.basename + ".csv") -Encoding UTF8
#Write to ConsoleHost
Write-Host $filename.name "completed"
}
Here is the error:
Export-Csv : Cannot open file because the current provider (Microsoft.SqlServer.Management.PSProvider\SqlServer) cannot open a file.
At C:\MISDATA\Queries\Run Scripts.ps1:26 char:5
+ Export-Csv -NoTypeInformation -Path ($OutputFolderPath + "\" + $FileDate + " ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Export-Csv], PSInvalidOperationException
+ FullyQualifiedErrorId : ReadWriteFileNotFileSystemProvider,Microsoft.PowerShell.Commands.ExportCsvCommand
sqlquery1.sql completed
Export-Csv : Cannot open file because the current provider (Microsoft.SqlServer.Management.PSProvider\SqlServer) cannot open a file.
At C:\MISDATA\Queries\Run Scripts.ps1:26 char:5
+ Export-Csv -NoTypeInformation -Path ($OutputFolderPath + "\" + $FileDate + " ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Export-Csv], PSInvalidOperationException
+ FullyQualifiedErrorId : ReadWriteFileNotFileSystemProvider,Microsoft.PowerShell.Commands.ExportCsvCommand
sqlquery2.sql completed
Export-Csv : Cannot open file because the current provider (Microsoft.SqlServer.Management.PSProvider\SqlServer) cannot open a file.
At C:\MISDATA\Queries\Run Scripts.ps1:26 char:5
+ Export-Csv -NoTypeInformation -Path ($OutputFolderPath + "\" + $FileDate + " ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Export-Csv], PSInvalidOperationException
+ FullyQualifiedErrorId : ReadWriteFileNotFileSystemProvider,Microsoft.PowerShell.Commands.ExportCsvCommand
sqlquery3.sql completed
You need to specify powershell ruled UNC format.
$OutputFolderPath ="Filesystem::\\SQLSERVER\MISDATA\Results"
or
$OutputFolderPath ="Microsoft.PowerShell.Core\FileSystem::\\SQLSERVER\MISDATA\Results"

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]
}

Extracting attachments from SharePoint online using PowerShell

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

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