Use script who use functions stocked in another ps1 with Start-job - wpf

I'm trying a little WPF interface with powershell for compare two files. For do that, I want start 2 jobs with script who was stocked in "Jobs.ps1"
Param(
$PathFile1,
$PathFile2,
$Json
)
$Hash = CreateHashConverted -Path $PathFile1 -Fichier $Json
$List = [System.Collections.ArrayList]::New()
$List = CompareFile -Path $PathFile2 -Hash $Hash
return $List
But actually, "CreateHashConverted" and "CompareFile" uses somes functions who was stocked in "JsonFunctions.ps1" and "ReadFunctions.ps1"
When i try to use my start job
$null = Start-Job -Name "1vers2" -FilePath "$PSScriptRoot\..\Logique\Jobs.ps1" -ArgumentList $txtb_file1,$txtb_file2,$lb_LISTE.SelectedItem
My job doesn't know CreateHashConverted and CompareFile
Thank's for help

Use the -InitializationScript parameter to import the function definitions needed by the job:
$null = Start-Job -Name "1vers2" -InitializationScript { . "$PSScriptRoot\..\Logique\JsonFunctions.ps1"; . "$PSScriptRoot\..\Logique\ReadFunctions.ps1" } -FilePath "$PSScriptRoot\..\Logique\Jobs.ps1" -ArgumentList $txtb_file1,$txtb_file2,$lb_LISTE.SelectedItem

Related

Run multiple *.sql query files log to file

My goal is to have a PowerShell script run several Sqlquery.sql files against a specific SQL server and then log the output to a log file.
I can't get the logging to work and I don't know what I'm missing. My log file is always empty and I'm at a loss for that I am missing.
Contents of C:\Temp:
Build1.SQL
Build2.SQL
Build3.sql
Build4.sql
Build5.SQL
Build6.SQL
$PatchPostConvSQLScripts = Get-ChildItem -Path C::\Temp -Filter *.sql -Name
$Queries = $PatchPostConvSQLScripts
foreach ($query in $Queries){
Write-Host "Starting: $query"
Invoke-Sqlcmd -ServerInstance $DBServer -InputFile $query |
Out-File "C:\TEMP\scriptResults.log"
Write-Host "Completed: $query"
}
Once I get it logging to a file, I'll need to get a newline each time with a `n`r, but baby steps right now.
Is there a better way to do this that I just don't know?
The main reason you got nothing in log file is that Output-File rewrite whole data in it on each run. Try to use -Verbose as mentioned in answer by TechSpud to collect print/server statements, or write output to temp file and Add-Content to main log file:
$DBServer = "MYPC\SQLEXPRESS"
$sqlPath = "C:\TEMP\"
$log = "scriptResults.log"
$tempOut = "temp.log"
$files = Get-ChildItem -Path $sqlPath -Filter *.sql -Name
foreach ($file in $files){
Write-Host "Starting: $file"
Invoke-SQLcmd -ServerInstance $DBServer -InputFile $sqlPath$file | Out-File $sqlPath$tempOut
Get-Content $sqlPath$tempOut | Add-Content $sqlPath$log
Write-Host "Completed: $file"
}
Firstly, as #Ben Thul has mentioned in his comment, check that your SQL files actually output something (a resultset, or messages), by running them in Management Studio.
Then, you'll need to use the -Verbose flag, as this command will tell you.
Get-Help Invoke-Sqlcmd -Full
Invoke-Sqlcmd does not return SQL Server message output, such as the
output of PRINT statements, unless you use the PowerShell -Verbose parameter.
$Queries = Get-ChildItem -Path C::\Temp -Filter *.sql -Name
Clear-Content -Path "C:\TEMP\scriptResults.log" -Force
foreach ($query in $Queries){
Write-Host "Starting: $query"
Invoke-Sqlcmd -ServerInstance $DBServer -InputFile $query -Verbose |
Add-Content -Path "C:\TEMP\scriptResults.log"
Write-Host "Completed: $query"
}

How to search Powershell array for specific strings and use this result in a copy-item -include script

I'm trying to create a synchronization script in Powershell so that my applications in MDT are being copied on a regular basis to our main file server, based on the folder name (in MDT, applications are in one folder, where our main server has applications split depending on the department who uses them).
From what I read on the web, the best way would be to populate an array with "Get-ChildItem", which I kinda figured how to do (see code below).
After the array is populated though, I don't know how to search that array for specific results, nor do I know how to use those results with copy-item.
In a nutshell, here's what I need to do: Build an array using "Get-ChildItem", query the resulting array for specific folders, and have those folders be copied to specific destinations.
Here's the code I have so far:
$arr = Get-ChildItem \\slmtl-wds02.domain.inc\deploymentshare$\applications |
Where-Object {$_.PSIsContainer} |
Foreach-Object {$_.Name}
$sourcepath = \\slmtl-wds02.domain.inc\deploymentshare$\applications
$destSLARC = \\slmtl-fs01.domain.inc\folder\it_services\private\software\service_desk\pc\SLARCMTL
$destSLMTL = \\slmtl-fs01.domain.inc\folder\it_services\private\software\service_desk\pc\SLMTL
$destSLGLB = \\slmtl-fs01.domain.inc\folder\it_services\private\software\service_desk\pc\SLGLB
$destSLTECH = \\slmtl-fs01.domain.inc\folder\it_services\private\software\service_desk\pc\SLTECH
Thanks in advance for your help :)
$sourceLocation = "c:\analysis\"
$targetLocation = "c:\analysisCopy\"
$included = #("folder1", "folder2")
$result = #()
foreach ($i in $included){
$result += get-ChildItem $sourceLocation -filter $i | Where-Object {$_.PSIsContainer}
}
$result | foreach-Object { copy-item $_.FullName -Destination $targetLocation -Recurse}
Hope this works change the path D:\ to your desired path enter the name of folder you looking for
$Keyword=[Microsoft.VisualBasic.Interaction]::InputBox("Enter your Query")
[System.Reflection.Assembly]::LoadWithPartialName('Microsoft.VisualBasic') | Out-Null
Get-ChildItem D:\ -recurse | Where-Object {$_.PSIsContainer -eq $fasle -and $_.Name -match "$keyword"} | Copy-Item -Destination d:\test

Get $webclient.downloadstring to write to text file in Powershell

I'm not a programmer/scripter. I just need to get the following script to write to a file:
[CmdletBinding()]
param ()
# Create a web client object
$webClient = New-Object System.Net.WebClient
# Returns the public IP address
$webClient.DownloadString('http://myip.dnsomatic.com/')
I've tried out-file and export-csv but it write a blank file. I'm sure it's something simple...but having no knowledge makes it difficult for me.
You could also use the DownloadFile method:
$webClient.DownloadFile('http://myip.dnsomatic.com/', 'c:\ip.txt')
The add-content cmdlet should do what you want.
Assuming $webClient.DownloadString('http://myip.dnsomatic.com/') returns a string, try:
Add-Content -Path $filename -Value $webClient.DownloadString('http://myip.dnsomatic.com/')
Reference:
http://technet.microsoft.com/en-us/library/dd347594.aspx
$PublicIP="C:\PublicIP.txt"
$WebClient=New-Object net.webclient
$String=$WebClient.DownloadString("http://checkip.dyndns.com") -replace "[^\d\.]"
If (Test-Path $PublicIP) {
Remove-Item $PublicIP
}
New-Item $PublicIP -type file
Add-Content -Path $PublicIP -Value $String

Powershell Script using Invoke-SQL command,needed for SQL job, the SQL Server version of Powershell is somewhat crippled, is there a workaround?

Full Question: Have Powershell Script using Invoke SQL command, using snappins, I need them to be included in a SQL job, the SQL Server version of Powershell is somewhat crippled, does anyone know a workaround?
From what I have gathered, SQL Management Studio's version of powershell is underpowered, not allowing for the use of snappins, as such it does not recognize the cmdlets that I used in the script. I have tried running it in the job as a command line prompt rather than a Powershell script, which causes the code to work somewhat, however I check the history on the job and it says that invoke-sql is still not a recognized cmdlet. I speculate that because I am running the code on a remote server, with different credentials than my standard my profile with the snappins preloaded isn't being loaded, though this is somewhat doubtful.
Also, as I am a powershell rookie, any advice on better coding practices/streamlining my code would be much appreciated!
Code is as follows:
# define parameters
param
(
$file = "\\server\folder\file.ps1"
)
"invoke-sqlcmd -query """ | out-file "\\server\folder\file.ps1"
# retrieve set of table objects
$path = invoke-sqlcmd -query "select TableName from table WITH (NoLock)" -database db -server server
[reflection.assembly]::LoadWithPartialName("Microsoft.SqlServer.Smo")
$so = New-Object Microsoft.SqlServer.Management.Smo.ScriptingOptions
$so.DriPrimaryKey = $false
$so.Nocollation = $true
$so.IncludeIfNotExists = $true
$so.NoIdentities = $true
$so.AnsiPadding = $false
# script each table
foreach ($table in $path)
{
#$holder = $table
$table = get-item sqlserver:\sql\server\default\databases\database\tables\dbo.$($table.TableName)
$table.script($so) | out-file -append $file
}
(get-content "\\server\folder\file.ps1") -notmatch "ANSI_NULLS" | out-file "\\server\folder\file.ps1"
(get-content "\\server\folder\file.ps1") -notmatch " AS "| out-file "\\server\folder\file.ps1"
(get-content "\\server\folder\file.ps1") -notmatch "Quoted_" | out-file "\\server\folder\file.ps1"
(get-content "\\server\folder\file.ps1") -replace "\) ON \[PRIMARY\].*", ")" | out-file "\\server\folder\file.ps1"
(get-content "\\server\folder\file.ps1") -replace "\[text\]", "[nvarchar](max)" | out-file "\\server\folder\file.ps1"
(get-content "\\server\folder\file.ps1") -replace " SPARSE ", "" | out-file "\\server\folder\file.ps1"
(get-content "\\server\folder\file.ps1") -replace "COLUMN_SET FOR ALL_SPARSE_COLUMNS", "" | out-file "\\server\folder\file.ps1"
""" -database database -server server" | out-file "\\server\folder\file.ps1" -append
So I figured out the answer to my own question. Using this site: http://www.mssqltips.com/tip.asp?tip=1684 and
http://www.mssqltips.com/tip.asp?tip=1199
I figured out that he was able to do so using a SQL Server Agent Proxy, so I followed the yellow brick road, and basically I set up a proxy to my account and was able to use the external powershell through a feature. A note, you need to create a credential under the securities tab in object explorer prior to being able to select one when creating the proxy. Basically I ended up creating a proxy named powershell, using the powershell subsystem, and use my login info to create a credential. VOILA!
You have to add the snapins each time. In your editor you likely already have them loaded from another script/tab/session. In SQL Server you will need to add something like this to the beginning of the script:
IF ( (Get-PSSnapin -Name sqlserverprovidersnapin100 -ErrorAction SilentlyContinue) -eq $null )
{
Add-PsSnapin sqlserverprovidersnapin100
}
IF ( (Get-PSSnapin -Name sqlservercmdletsnapin100 -ErrorAction SilentlyContinue) -eq $null )
{
Add-PsSnapin sqlservercmdletsnapin100
}
I'm not sure the error you are trying to workaround - can you post that?
Have you tried this from a PowerShell prompt?
Add-PSSnapin SqlServerCmdletSnapin100

How to get an variable output from remote pssession

I have a script to get virtual harddisk info from vmm, im executing it remotely from a server, currently im unable to get the variable value outside of the pssession in the local host, could you please help me out with achieveing the same.
PS C:\Windows\system32> enter-pssession iscvmm02
[iscvmm02]: PS C:\Users\su\Documents>Add-PSSnapin Microsoft.SystemCenter.VirtualMachineManager
[iscvmm02]: PS C:\Users\su\Documents>$hide= Get-VMMServer -ComputerName "iscvmm02.corp.avanade.org"
[iscvmm02]: PS C:\Users\su\Documents>$VM = Get-VM | where { $_.ComputerNameString -contains "idpsm02.corp.air.org" }
[iscvmm02]: PS C:\Users\su\Documents>$harddisk=$VM.VirtualHardDisks
[iscvmm02]: PS C:\Users\su\Documents>$h=$harddisk.length
[iscvmm02]: PS C:\Users\su\Documents>for($i=0;$i-lt$h;$i++){
New-Variable -Name "HardDiskType_$i" -value $harddisk[$i].vhdtype
New-Variable -Name "HardDiskLocation_$i" -value $harddisk[$i].Location
}
[iadpscvmm02]: PS C:\Users\su\Documents>Exit-PSSession
PS C:\Windows\system32>$harddisktype_0
PS C:\Windows\system32>$harddisklocation_0
as you can see both the variable output's give null value, im unable to retain the values
This example gets listing from remote computer's C drive and assigns it into a local variable. So tune your VMM script accordingly.
$session = New-PSSession -ComputerName RemoteSystem
Invoke-Command -Session $session -ScriptBlock { $remoteC = gci c:\ }
# This shouldn't print anything.
$localC
# Print the result on remote computer an assing its output to localC variable
$localC = Invoke-Command -Session $session -ScriptBlock { $remoteC }
# Print the local variable, it should contain remoteC data.
$localC

Resources