So after succeeding in passing variables to start-job(huge thanks to the awesome stackoverflow members).
Now I'm struggling to pass a function into the job.
I need to use the Append-ColoredLine function inside the 7zipextraction job.
For some reason I cant find a way of achieving that.
function Append-ColoredLine
{
param (
[Parameter(Mandatory = $true, Position = 0)]
[System.Windows.Forms.RichTextBox]$box,
[Parameter(Mandatory = $true, Position = 1)]
[System.Drawing.Color]$color,
[Parameter(Mandatory = $true, Position = 2)]
[string]$text
)
$box.SelectionStart = $box.TextLength
$box.SelectionLength = 0
$box.SelectionColor = $color
$box.AppendText($text)
$box.AppendText([Environment]::NewLine)
}
$OutputDirectory="C:\Test\2"
$zipfile="C:\Test\2\1.zip"
$uploadevidence="C:\UploadFolder"
function 7zipextraction
{
Set-Alias 7zip $using:7zip_path
# Extracting files
$extract = 7zip x -y $using:zpfile -o"${using:OutputDirectory}"
if ($LASTEXITCODE -ne 0)
{
Append-ColoredLine $using:richtextbox1 Red "$using:Time 7zip Error"
return
}
else
{
Append-ColoredLine $using:richtextbox1 Blue "$using:Time Files extracted successfully"
}
Start-Sleep -s 2
}
Start-Job -Name zip2 -ScriptBlock ${Function:7zipextraction} | Receive-Job -Wait
Related
I have used the following code to display JSON results but now need to change the script to display the output instead of side by side. I have tried a script like below, but just cant seem to get it to do what I want.
My question is :
I want to remove || before the last bracket. if (shExpMatch(host, "*.lync.com") || shExpMatch(host, "*.teams.microsoft.com") || shExpMatch(host, "teams.microsoft.com") || ) As a result , it will be if (shExpMatch(host, "*.lync.com") || shExpMatch(host, "*.teams.microsoft.com") || shExpMatch(host, "teams.microsoft.com"))
I need to change the script to display the my desired output instead of side by side.
Here is my script :
$result = Invoke-WebRequest "https://endpoints.office.com/endpoints/worldwide?noipv6&ClientRequestId=b10c5ed1-bad1-445f-b386-b919946339a7"
$services = ConvertFrom-Json $result
$likeFilter = "12"
$services = $services | Where-Object { $_.id -like $likeFilter }
$urls = [System.Collections.ArrayList]#()
$services
function add_url($url){
if(!$urls.Contains($url)){ $urls.Add($url); }
}
foreach($service in $services){
foreach($url in $service.urls){ add_url($url);
}
}
# OUTPUT
$txt_proxypacText += "// This PAC file will provide proxy config to Microsoft 365 services`r`n"
$txt_proxypacText += "// using data from the public web service for all endpoints`r`n"
$txt_proxypacText += "function FindProxyForURL(url, host)`r`n"
$txt_proxypacText += "{`r`n"
$txt_proxypacText += "var direct = ""DIRECT"";`r`n"
$txt_proxypacText += "var proxyServer = ""PROXY 10.11.12.13:8080"";`r`n"
$txt_proxypacText += "host = host.toLowerCase();`r`n"
$txt_proxypacText += "if ("
foreach($url in $urls){
$txt_proxypacText += "shExpMatch(host, ""$url"") || "
}
$txt_proxypacText += ")`r`n"
$txt_proxypacText += "{`r`n"
$txt_proxypacText += "`r`n return direct;"
$txt_proxypacText += "`r`n}"
$txt_proxypacText += "`r`n return proxyServer;"
$txt_proxypacText += "`r`n}"
Output:
// This PAC file will provide proxy config to Microsoft 365 services
// using data from the public web service for all endpoints
function FindProxyForURL(url, host)
{
var direct = "DIRECT";
var proxyServer = "PROXY 10.11.12.13:8080";
host = host.toLowerCase();
if (shExpMatch(host, "*.lync.com") || shExpMatch(host, "*.teams.microsoft.com") || shExpMatch(host, "teams.microsoft.com") || )
{
return direct;
}
return proxyServer;
}
My Desired Output :
// This PAC file will provide proxy config to Microsoft 365 services
// using data from the public web service for all endpoints
function FindProxyForURL(url, host)
{
var direct = "DIRECT";
var proxyServer = "PROXY 10.11.12.13:8080";
host = host.toLowerCase();
if(shExpMatch(host, "*.lync.com")
|| shExpMatch(host, "*.teams.microsoft.com")
|| shExpMatch(host, "teams.microsoft.com"))
{
return direct;
}
return proxyServer;
}
I would make use of a Here-String with a preformated set of shExpMatch(..) lines.
Using that also relieves you from doubling quotes and string concatenations using +=
# demo urls
$urls = "*.lync.com", "*.teams.microsoft.com", "teams.microsoft.com"
$hostMatches = $(for ($i = 0; $i -lt $urls.Count; $i++) {
$prefix = if ($i -eq 0) { '' } else { ' || '}
'{0}shExpMatch(host, "{1}")'-f $prefix, $urls[$i]
}) -join [Environment]::NewLine
$txt_proxypacText = #"
// This PAC file will provide proxy config to Microsoft 365 services
// using data from the public web service for all endpoints
function FindProxyForURL(url, host)
{
var direct = "DIRECT";
var proxyServer = "PROXY 10.11.12.13:8080";
host = host.toLowerCase();
if ($hostMatches)
{
return direct;
}
return proxyServer;
}
"#
$txt_proxypacText
Output:
// This PAC file will provide proxy config to Microsoft 365 services
// using data from the public web service for all endpoints
function FindProxyForURL(url, host)
{
var direct = "DIRECT";
var proxyServer = "PROXY 10.11.12.13:8080";
host = host.toLowerCase();
if (shExpMatch(host, "*.lync.com")
|| shExpMatch(host, "*.teams.microsoft.com")
|| shExpMatch(host, "teams.microsoft.com"))
{
return direct;
}
return proxyServer;
}
As requested, I think the top part of the code, where you are gathering the urls in an arraylist can be done much easier.
One note before: You are using a $likeFilter variable with a string "12".
In that case, you could probably better use the -eq operator instead of the -like operator that has more use for filtering with wildcards (i.e. "12*").
For now, I'm assuming you want to get only the service with id matching "12" exactly.
$url = "https://endpoints.office.com/endpoints/worldwide?noipv6&ClientRequestId=b10c5ed1-bad1-445f-b386-b919946339a7"
$filter = 12
# get an array of urls from the service(s) that get through the filter
$urls = ((Invoke-WebRequest $url | ConvertFrom-Json) | Where-Object { $_.id -eq $filter }).urls | Select-Object -Unique
# EXAMPLE prepare begin
$urls = #(
'microsoft.com',
'*.microsoft.com',
'teams.microsoft.com',
'*.teams.microsoft.com')
# EXAMPLE prepare End
$urlLines = $urls |
ForEach-Object { return $_.Trim() } |
ForEach-Object {
if($_.StartsWith('*.')) {
return "shExpMatch(host, '$($_)')"
} else {
return "host == '$($_)'"
}}
$innerIf = [String]::Join("`r`n" + (' ' * 8) + "|| ", $urlLines)
#// $txt_proxypacText += " if ($($innerIf))"
Write-Host " if ($($innerIf))"
# Output:
# if (host == "microsoft.com"
# || shExpMatch(host, "*.microsoft.com")
# || host == "teams.microsoft.com"
# || shExpMatch(host, "*.teams.microsoft.com"))
I got this - simple counter method:
$counter = 0
foreach($url in $urls){
If ($counter -eq $urls.Count){
$txt_proxypacText += "shExpMatch(host, ""$url"") `r`n"
}else{
$txt_proxypacText += "shExpMatch(host, ""$url"") || `r`n"
}
$counter++
}
Probably needs some tidying up with the tab characters.
Trying to write a function to create a new line to be added to a table for export. The following outputs the correct values to the console but the CSV is empty.
If I place the code to create $newline at various point in the script it works fine but not when I call it as a function.
$report = #()
Function CreateNewLine
{
$lineproperties = #{
Cluster = $cluster
Node = $node
Database = $d.Name
LogCount = $logcount
LogPath = $p
}
$newline = New-Object PSObject -property $lineproperties
}
# Loop to create values for $cluster etc...
CreateNewLine
$report += $newline
# End loop
$report | Export-CSV 'pathto file' -notype
You have a scope issue here. $newline has no context outside the function. Therefore you would just be adding $null to the $report array. Make the function return the value which can then be captured.
Function CreateNewLine
{
$lineproperties = #{
Cluster = $cluster
Node = $node
Database = $d.Name
LogCount = $logcount
LogPath = $p
}
New-Object PSObject -property $lineproperties
}
# Loop to create values for $cluster etc...
$report += CreateNewLine
The function should have access to those other variables as long as they are in the parent scope of the function.
The function CreateNewLine never returns a value. You need to do the following:
Function CreateNewLine
{
$lineproperties = [PSCustomObject]#{
Cluster = $cluster
Node = $node
Database = $d.Name
LogCount = $logcount
LogPath = $p
}
$lineProperties
}
You can create an object in much easier manner (as Matt said, this works in Powershell 3.0 and later):
Function CreateNewLine
{
[pscustomobject]#{
Cluster = $cluster
Node = $node
Database = "name"
LogCount = $logcount
LogPath = $p
}
}
Then, in any place you want you can use this function:
$cluster = "cluster 1"
$report += createnewline
$cluster = "cluster 2"
$report += createnewline
$report | Export-CSV 'pathto file' -notype
Using this database connection script I have found here. I have modified it and did the proper setting to let the script run but don't understand the error I am getting.
The script code is here:
Param(
[Parameter(
Mandatory = $true,
ParameterSetName = '',
ValueFromPipeline = $true)]
[string]$Query
)
$MySQLAdminUserName = 'myName'
$MySQLAdminPassword = 'myPass'
$MySQLDatabase = 'myDatabase'
$MySQLHost = 'HostingServerForMyDatabase'
$ConnectionString = server= + $MySQLHost + ;port=3306;uid= + $MySQLAdminUserName + ;pwd= + $MySQLAdminPassword + ;database=+$MySQLDatabase+
Try {
[void][System.Reflection.Assembly]LoadWithPartialName(MySql.Data)
$Connection = New-Object MySql.Data.MySqlClient.MySqlConnection
$Connection.ConnectionString = $ConnectionString
$Connection.Open()
$Command = New-Object MySql.Data.MySqlClient.MySqlCommand($Query, $Connection)
$DataAdapter = New-Object MySql.Data.MySqlClient.MySqlDataAdapter($Command)
$DataSet = New-Object System.Data.DataSet
$RecordCount = $dataAdapter.Fill($dataSet, data)
$DataSet.Tables[0]
}
Catch {
Write-Host ERROR Unable to run query $query `n$Error[0]
}
Finally {
$Connection.Close()
}
And so, this is the error I recieve with the following command -
COMMAND: .\MySQL.ps1 -Query "select GUID FROM MYTABLE"
ERROR:Parameter declerations are a comma-serperated list of variable names with optional initializer expressions. At (my script file path)\MySQL.ps1:5 char:30 + ValueFromPipeline = $true)] <<<<
Apparently the error is not from running the script as in shown in the question nor in the link, but some unknown other script.
The error message shows you are missing the closing parentheses.
Parameter declerations are a comma-serperated list of variable names
with optional initializer expressions. At (my script file
path)\MySQL.ps1:5 char:30 + ValueFromPipeline = $true>] <<<<
The code you posted here and in the link does have it correct.
Param(
[Parameter(
Mandatory = $true,
ParameterSetName = '',
ValueFromPipeline = $true)]
[string]$Query
)
Notice $true)]
Correct MySQL.ps1 so it is exactly the same as in your link.
I wrote a function to convert the input month parameter to a certain format. such as if I passed 04 to the function and the function will return the "_APR_". the function I wrote is like below:
function GetEnMonth()
{
param([string] $month)
switch ($month)
{
($_ -eq "01"){$result = "_JAN_"}
($_ -eq "02"){$result = "_FEB_"}
($_ -eq "03"){$result = "_MAR_"}
($_ -eq "04"){$result = "_APR_"}
($_ -eq "05"){$result = "_MAY_"}
($_ -eq "06"){$result = "_JUN_"}
($_ -eq "07"){$result = "_JUL_"}
($_ -eq "08"){$result = "_AUG_"}
($_ -eq "09"){$result = "_SEP_"}
($_ -eq "10"){$result = "_OCT_"}
($_ -eq "11"){$result = "_NOV_"}
($_ -eq "12"){$result = "_DEC_"}
default {$result ="_No_Result_"}
}
return [string]$result;
}
Then I use below command to execute the function to get the result:
$mYear = $today.substring(0,4)
$mMonth =$today.substring(4,2)
$mDate = $today.substring(6,2)
$monthInEn = GetEnMonth $mMonth
well, the result is always "_No_Result_", why? below is the exception:
**** Exception type : System.Management.Automation.RuntimeException
**** Exception message : You cannot call a method on a null-valued expression.
Could anyone give me an answer for this?
I have searched Google a lot but don't find useful solutions.
This should work:
function GetEnMonth
{
param([string] $month)
switch ($month)
{
"01"{$result = "_JAN_"}
"02"{$result = "_FEB_"}
"03"{$result = "_MAR_"}
"04"{$result = "_APR_"}
"05"{$result = "_MAY_"}
"06"{$result = "_JUN_"}
"07"{$result = "_JUL_"}
"08"{$result = "_AUG_"}
"09"{$result = "_SEP_"}
"10"{$result = "_OCT_"}
"11"{$result = "_NOV_"}
"12"{$result = "_DEC_"}
default {$result ="_No_Result_"}
}
return [string]$result;
}
Here's my take on this. I changed the parameter type to Int, with this you'll be able to get process such as "03" or 3. I also added break statements to make the switch work faster.
function GetEnMonth
{
param([int] $month)
switch ($month)
{
1 {"_JAN_"; break}
2 {"_FEB_"; break}
3 {"_MAR_"; break}
4 {"_APR_"; break}
5 {"_MAY_"; break}
6 {"_JUN_"; break}
7 {"_JUL_"; break}
8 {"_AUG_"; break}
9 {"_SEP_"; break}
10 {"_OCT_"; break}
11 {"_NOV_"; break}
12 {"_DEC_"; break}
default {"_No_Result_"}
}
}
Your switch statment is wrong try this:
function GetEnMonth()
{
param([string] $month)
switch ($month)
{
"01" {$result = "_JAN_"}
"02" {$result = "_FEB_"}
"03" {$result = "_MAR_"}
"04" {$result = "_APR_"}
"05" {$result = "_MAY_"}
"06" {$result = "_JUN_"}
"07" {$result = "_JUL_"}
"08" {$result = "_AUG_"}
"09" {$result = "_SEP_"}
"10" {$result = "_OCT_"}
"11" {$result = "_NOV_"}
"12" {$result = "_DEC_"}
default {$result ="_No_Result_"}
}
return [string]$result;
}
This is not an answer, but another way to do the same in one line and with a culture param:
$month = 3
$smonth=[string]::format([System.Globalization.CultureInfo]"en-US", "_{0:MMM}_",[datetime]("$month/01"))
$smonth
_MAR_
I would like to automatically script out all SQL Server 2008 policies and conditions on a server each night and compare the files to my version control system. In the UI, I can script out individual policies by right-clicking the policy and selecting Export Policy. Is it possible to script out policies and conditions via SMO or PowerShell?
Ideally, I would like to incorporate this into my existing PowerShell script that generates scripts for all of my other server and database objects. Here's the script that currently does this action:
# Load needed assemblies
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.SMO") | out-null
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.SMOExtended")| Out-Null;
#Specify target server and databases.
$sql_server = "SomeServerName"
$SMOserver = New-Object -TypeName Microsoft.SqlServer.Management.Smo.Server -ArgumentList "$sql_server"
$databases = $SMOserver.Databases
$BaseSavePath = "T:\SomeFilePath\" + $sql_server + "\"
#Remove existing objects.
Remove-Item $BaseSavePath -Recurse
#Script server-level objects.
$ServerSavePath = $BaseSavePath
$ServerObjects = $SMOserver.BackupDevices
$ServerObjects += $SMOserver.Endpoints
$ServerObjects += $SMOserver.JobServer.Jobs
$ServerObjects += $SMOserver.LinkedServers
$ServerObjects += $SMOserver.Triggers
foreach ($ScriptThis in $ServerObjects | where {!($_.IsSystemObject)})
{
#Need to Add Some mkDirs for the different $Fldr=$ScriptThis.GetType().Name
$scriptr = new-object ('Microsoft.SqlServer.Management.Smo.Scripter') ($SMOserver)
$scriptr.Options.AppendToFile = $True
$scriptr.Options.AllowSystemObjects = $False
$scriptr.Options.ClusteredIndexes = $True
$scriptr.Options.DriAll = $True
$scriptr.Options.ScriptDrops = $False
$scriptr.Options.IncludeHeaders = $False
$scriptr.Options.ToFileOnly = $True
$scriptr.Options.Indexes = $True
$scriptr.Options.Permissions = $True
$scriptr.Options.WithDependencies = $False
<#Script the Drop too#>
$ScriptDrop = new-object ('Microsoft.SqlServer.Management.Smo.Scripter') ($SMOserver)
$ScriptDrop.Options.AppendToFile = $True
$ScriptDrop.Options.AllowSystemObjects = $False
$ScriptDrop.Options.ClusteredIndexes = $True
$ScriptDrop.Options.DriAll = $True
$ScriptDrop.Options.ScriptDrops = $True
$ScriptDrop.Options.IncludeHeaders = $False
$ScriptDrop.Options.ToFileOnly = $True
$ScriptDrop.Options.Indexes = $True
$ScriptDrop.Options.WithDependencies = $False
<#This section builds folder structures. Remove the date folder if you want to overwrite#>
$TypeFolder=$ScriptThis.GetType().Name
if ((Test-Path -Path "$ServerSavePath\$TypeFolder") -eq "true") `
{"Scripting Out $TypeFolder $ScriptThis"} `
else {new-item -type directory -name "$TypeFolder"-path "$ServerSavePath"}
$ScriptFile = $ScriptThis -replace ":", "-" -replace "\\", "-"
$ScriptDrop.Options.FileName = $ServerSavePath + "\" + $TypeFolder + "\" + $ScriptFile.Replace("]", "").Replace("[", "") + ".sql"
$scriptr.Options.FileName = $ServerSavePath + "\" + $TypeFolder + "\" + $ScriptFile.Replace("]", "").Replace("[", "") + ".sql"
#This is where each object actually gets scripted one at a time.
$ScriptDrop.Script($ScriptThis)
$scriptr.Script($ScriptThis)
} #This ends the object scripting loop at the server level.
#Script database-level objects.
foreach ($db in $databases)
{
$DatabaseObjects = $db.ApplicationRoles
$DatabaseObjects += $db.Assemblies
$DatabaseObjects += $db.ExtendedStoredProcedures
$DatabaseObjects += $db.ExtendedProperties
$DatabaseObjects += $db.PartitionFunctions
$DatabaseObjects += $db.PartitionSchemes
$DatabaseObjects += $db.Roles
$DatabaseObjects += $db.Rules
$DatabaseObjects += $db.Schemas
$DatabaseObjects += $db.StoredProcedures
$DatabaseObjects += $db.Synonyms
$DatabaseObjects += $db.Tables
$DatabaseObjects += $db.Triggers
$DatabaseObjects += $db.UserDefinedAggregates
$DatabaseObjects += $db.UserDefinedDataTypes
$DatabaseObjects += $db.UserDefinedFunctions
$DatabaseObjects += $db.UserDefinedTableTypes
$DatabaseObjects += $db.UserDefinedTypes
$DatabaseObjects += $db.Users
$DatabaseObjects += $db.Views
#Build this portion of the directory structure out here. Remove the existing directory and its contents first.
$DatabaseSavePath = $BaseSavePath + "Databases\" + $db.Name
new-item -type directory -path "$DatabaseSavePath"
foreach ($ScriptThis in $DatabaseObjects | where {!($_.IsSystemObject)})
{
#Need to Add Some mkDirs for the different $Fldr=$ScriptThis.GetType().Name
$scriptr = new-object ('Microsoft.SqlServer.Management.Smo.Scripter') ($SMOserver)
$scriptr.Options.AppendToFile = $True
$scriptr.Options.AllowSystemObjects = $False
$scriptr.Options.ClusteredIndexes = $True
$scriptr.Options.DriAll = $True
$scriptr.Options.ScriptDrops = $False
$scriptr.Options.IncludeHeaders = $False
$scriptr.Options.ToFileOnly = $True
$scriptr.Options.Indexes = $True
$scriptr.Options.Permissions = $True
$scriptr.Options.WithDependencies = $False
<#Script the Drop too#>
$ScriptDrop = new-object ('Microsoft.SqlServer.Management.Smo.Scripter') ($SMOserver)
$ScriptDrop.Options.AppendToFile = $True
$ScriptDrop.Options.AllowSystemObjects = $False
$ScriptDrop.Options.ClusteredIndexes = $True
$ScriptDrop.Options.DriAll = $True
$ScriptDrop.Options.ScriptDrops = $True
$ScriptDrop.Options.IncludeHeaders = $False
$ScriptDrop.Options.ToFileOnly = $True
$ScriptDrop.Options.Indexes = $True
$ScriptDrop.Options.WithDependencies = $False
<#This section builds folder structures. Remove the date folder if you want to overwrite#>
$TypeFolder=$ScriptThis.GetType().Name
if ((Test-Path -Path "$DatabaseSavePath\$TypeFolder") -eq "true") `
{"Scripting Out $TypeFolder $ScriptThis"} `
else {new-item -type directory -name "$TypeFolder"-path "$DatabaseSavePath"}
$ScriptFile = $ScriptThis -replace ":", "-" -replace "\\", "-"
$ScriptDrop.Options.FileName = $DatabaseSavePath + "\" + $TypeFolder + "\" + $ScriptFile.Replace("]", "").Replace("[", "") + ".sql"
$scriptr.Options.FileName = $DatabaseSavePath + "\" + $TypeFolder + "\" + $ScriptFile.Replace("]", "").Replace("[", "") + ".sql"
#This is where each object actually gets scripted one at a time.
$ScriptDrop.Script($ScriptThis)
$scriptr.Script($ScriptThis)
} #This ends the object scripting loop.
} #This ends the database loop.
You have a couple of choices from SMO/Powershell.
1: SQLPS/PowerShell with SQL loaded
SQLSERVER:\SQLPolicy\\DEFAULT\Policies
you can then dig through it, i didnt see an "export" but you can certianly get the info out of it.
2: SMO
basically SMO has a Microsoft.SqlServer.Management.DMF namespace that has severial policy objects (what you end up with in the PowerShell side of things) Policy, PolicyStore, PolicyCondition etc, rather than write out an example, you can find one here.
http://rdbmsexperts.com/Blogs/archives/295
again i didnt see an "export" method anywhere, but you could probably spit out what you needed easily enough.