Splitting .mdf database into several files - sql-server

I need to split database .bak into several files, using powershell. How best to do it?
Any examples?

Something like this might work:
$filename = "C:\path\to\your.bak"
$chunksize = 20480
$totalsize = (Get-Item $filename).Length
$stream = New-Object IO.FileStream($filename, [IO.FileMode]::Open)
$reader = New-Object IO.BinaryReader($stream)
$chunk = New-Object byte[] $chunksize
$size = $chunksize
$i = 0
do {
$rest = $totalsize - ($i * $chunksize)
$i++
if ($chunksize -gt $rest) {
$size = $rest
$chunk = New-Object byte[] $size
}
$reader.Read($chunk, 0, $size) | Out-Null
[IO.File]::WriteAllBytes(({0}.{1:d3}" -f ($filename, $i)), $chunk)
} until ($chunksize -gt $rest)
$reader.Close()
$stream.Close()

Related

Powershell Listview : Add 6 items lists in 6 different columns

I have an issue with my PS script including a listview.
I need to check the content of 6 directorys and show the content in 6 different columns :
The issue is that i can't get a correct visual, they are all in the same column
Here is my code :
$Form = New-Object Windows.Forms.Form
$Form.Text = "New Test"
$Form.Width = 1550
$Form.Height = 800
$Listview = New-Object System.Windows.Forms.ListView
$Listview.Location = New-Object System.Drawing.Size(15,10)
$Listview.Size = New-Object System.Drawing.Size(550,10)
$Listview.AutoResizeColumns([System.Windows.Forms.ColumnHeaderAutoResizeStyle]::ColumnContent)
$Listview.View = "Details"
$Listview.FullRowSelect = $true
$Listview.GridLines = $true
$Listview.Height = 650
$Listview.Width =1500
$Listview.AllowColumnReorder = $true
$Listview.Sorting = [System.Windows.Forms.SortOrder]::None
#[void]$Listview.Columns.Add('Null',0)
[void]$Listview.Columns.Add('Scripts',150)
[void]$Listview.Columns.Add('Applications',150)
[void]$Listview.Columns.Add('Systems',500)
[void]$Listview.Columns.Add('Databases',100)
[void]$Listview.Columns.Add('Datas',150)
[void]$Listview.Columns.Add('Backups',500)
$oButton = New-Object Windows.Forms.Button
$oButton.Text = "List"
$oButton.Top = 700
$oButton.Left = 350
$oButton.Width = 150
$oButton.Anchor = [System.Windows.Forms.AnchorStyles]::Bottom -bor [System.Windows.Forms.AnchorStyles]::Right
$a = (Get-ChildItem "C:\Scripts\").Name
$b = (Get-ChildItem "C:\Applications\").Name
$c = (Get-ChildItem "C:\Systems\").Name
$d = (Get-ChildItem "C:\Databases\").Name
$e = (Get-ChildItem "C:\Datas\").Name
$f = (Get-ChildItem "C:\Backups\").Name
$Entry = New-Object System.Windows.Forms.ListViewItem($_.Null)
foreach($mp in $a){
$Entry1 = New-Object System.Windows.Forms.ListViewItem($_.Scripts)
$Listview.Items.Add($mp)
}
foreach($mp1 in $b){
$Entry2 = New-Object System.Windows.Forms.ListViewItem($_.Applications)
$Listview.Items.Add($Entry2).SubItems.Add($mp1)
}
foreach($mp2 in $c){
$Entry3 = New-Object System.Windows.Forms.ListViewItem($_.Systems)
$Listview.Items.Add($Entry3).SubItems.Add($mp2)
}
foreach($mp3 in $d){
$Entry4 = New-Object System.Windows.Forms.ListViewItem($_.Databases)
$Listview.Items.Add($Entry4).SubItems.Add($mp3)
}
foreach($mp4 in $e){
$Entry5 = New-Object System.Windows.Forms.ListViewItem($_.Datas)
$Listview.Items.Add($Entry5).SubItems.Add($mp4)
}
foreach($mp5 in $f){
$Entry6 = New-Object System.Windows.Forms.ListViewItem($_.Backup)
$Listview.Items.Add($Entry6).SubItems.Add($mp5)
}
$Form.Add_Shown({$Form.Activate()})
$Form.controls.add($oButton)
$Form.controls.add($Listview)
$Form.ShowDialog()
I tried a lot of change but im still blocked
Thanks in advance for you help
Regards

Error when executing SQL-Query from Powershell

I always get an error when executing this script:
Incorrect syntax near '#values'
I have the following function to execute my SQL statement:
$Server = "Server"
$Database = "Database"
$i = 0
function ExecuteSQLQuery(){
$Connection = New-Object System.Data.SqlClient.SqlConnection
$Connection.ConnectionString = "server='$Server';database='$Database'; trusted_connection=true;"
$Connection.Open()
$query = #
"INSERT INTO [Database].[dbo].[Folder](FolderPath,UserGroup,Permission,AccessControllType) VALUES #values
"#
$command = $connection.CreateCommand()
$command.CommandText = $query
$command.Parameters.Add("#values", $values)
$command.ExecuteNonQuery()
}
And this is the rest of the code in which I am getting the Data for the INSERT
$RootPath = "\\server\folder1\folder2\folder3"
$Folders = dir $RootPath -recurse | where {$_.psiscontainer -eq $true}
#root folder permission
$ACLs = get-acl $RootPath | ForEach-Object { $_.Access }
Foreach ($ACL in $ACLs) {
#Add-Content -Value $OutInfo -Path $OutFile
$FolderPath = $RootPath
$User = $ACL.IdentityReference
$Permission = $ACL.FileSystemRights
$AccessControllType = $ACL.AccessControlType
if($i -gt 50) {
Invoke-sqlcmd #params -Query $InsertResult
$i=0
$values = ""
}
elseif($i -eq 0) {
$values += "('$FolderPath','$User','$Permission','$AccessControllType')"
$i ++
}
else {
$values += ",('$FolderPath','$User','$Permission','$AccessControllType')"
$i ++
}
}
#subfolders
foreach ($Folder in $Folders) {
$ACLs = get-acl $Folder.fullname | ForEach-Object { $_.Access }
Foreach ($ACL in $ACLs) {
$FolderPath = $Folder.Fullname
$User = $ACL.IdentityReference
$Permission = $ACL.FileSystemRights
$AccessControllType = $ACL.AccessControlType
$IsInherited = $ACL.IsInherited
if ($i -gt 50) {
ExecuteSQLQuery
$i=0
$values = ""
}
elseif ($i -eq 0) {
$values += "('$FolderPath','$User','$Permission','$AccessControllType')"
$i ++
}
else {
$values += ",('$FolderPath','$User','$Permission','$AccessControllType')"
$i ++
}
}
}
I am new to Powershell so I don't now if the error is because of my code or if the $values contains something Powershell or SQL can't handle.
Do you guys have any ideas?

Ping Multiple IP/HostNames

I am just trying to make a simple IP/Hostname checker. The one part I am struggling with is getting it to ping each item from a list. It only shows the result of the first, or last one.
I have tried adding items from the text box into an array and pinging them that way, and it had the same results.
Here is my Current Code.
[System.Windows.Forms.Application]::EnableVisualStyles()
function ping-list{
$IPStatus.Text = ""
$names = #($IPList.text)
$Names | ForEach-Object{
if (Test-Connection -ComputerName $_ -Count 1){
$IPStatus.Text += "$_ is Online"
Write-Host "$_ is Online"
}
else{
$IPStatus.Text += "$_ is Offline"
Write-Host "$_ is Offline"
}
}
}
$Pinger = New-Object system.Windows.Forms.Form
$Pinger.ClientSize = '657,557'
$Pinger.text = "Pinger"
$Pinger.TopMost = $false
$IPStatus = New-Object system.Windows.Forms.TextBox
$IPStatus.multiline = $true
$IPStatus.width = 234
$IPStatus.height = 498
$IPStatus.enabled = $true
$IPStatus.location = New-Object System.Drawing.Point(408,45)
$IPStatus.Font = 'Microsoft Sans Serif,10'
$IPStatus.Text = "Ready"
$IPList = New-Object system.Windows.Forms.TextBox
$IPList.multiline = $true
$IPList.width = 234
$IPList.height = 498
$IPList.enabled = $true
$IPList.location = New-Object System.Drawing.Point(15,45)
$IPList.Font = 'Microsoft Sans Serif,10'
$IPList.Text = #("127.0.0.1")
$PingButton = New-Object system.Windows.Forms.Button
$PingButton.text = "button"
$PingButton.width = 60
$PingButton.height = 30
$PingButton.location = New-Object System.Drawing.Point(298,240)
$PingButton.Font = 'Microsoft Sans Serif,10'
$PingButton.Add_Click({ping-list})
$Pinger.controls.AddRange(#($IPStatus,$IPList,$PingButton))
$Pinger.Add_Shown( {$Pinger.Activate()})
$Pinger.ShowDialog()
$IPList.text gets all the text in the textbox.
Instead use Lines
function ping-list{
$IPStatus.Text = ""
$Names = #($IPList.Lines)
$Names | ForEach-Object{
if (Test-Connection -ComputerName $_ -Count 1){
$IPStatus.Text += "$_ is Online`r`n"
Write-Host "$_ is Online"
}
else{
$IPStatus.Text += "$_ is Offline`r`n"
Write-Host "$_ is Offline"
}
}
}

How do I add Checked Items from a CheckedListBox to a Combobox (dropdown) and remove them from the Combobox when unchecked?

I should start by saying that i'm new to PowerShell and i'm still in the learning phase. I've hit a road block and any help would be appreciated.
I have the following code:
# LOAD WINFORMS ASSEMBLY
[reflection.assembly]::LoadWithPartialName( "System.Windows.Forms")
[reflection.assembly]::LoadWithPartialName( "System.Drawing")
# CREATE FORMS
$Form = New-Object Windows.Forms.Form
$Form.text = "Post-Image Configuration Tool"
$Form.Width = 900
$Form.Height = 560
$Form.BackColor = "#3a73b8"
$Form.ForeColor = "White"
$Form.FormBorderStyle = "None"
$Form.StartPosition = "CenterScreen"
# START NETWORK CONFIGURATION PAGE
$GetConnectedAdapters = Get-WmiObject -Class Win32_NetworkAdapter -Filter "NetConnectionStatus = 2" | Select-Object NetConnectionID, Name, MACAddress
$netConfigList1 = New-Object System.Windows.Forms.CheckedListBox
$netConfigList1.Location = New-Object System.Drawing.Size(310,300)
$netConfigList1.Size = New-Object System.Drawing.Size(480,180)
$netConfigList1.Height = 100
$netConfigList1.BackColor = "#3a73b8"
$netConfigList1.ForeColor = "White"
$netConfigList1.BorderStyle = "None"
$netConfigList1.Font = $ListFont
$netConfigList1.add_SelectedIndexChanged({ListNetAdapters})
$netConfigListAdapters = #()
ForEach ($i in $GetConnectedAdapters.NetConnectionID){
$GetAdapterName = Get-WmiObject -Class Win32_NetworkAdapter |Where {$_.NetConnectionID -eq $i} | Select-Object Name, NetConnectionID, MACAddress
$AdapterName = $i +" - " + "("+ $GetAdapterName.Name +")"
$netConfigListAdapters += ,$AdapterName
}
$netConfigList1.Items.AddRange($netConfigListAdapters)
$netConfigSubtext5 = New-Object Windows.Forms.Label
$netConfigSubtext5.Location = New-Object Drawing.Point 290,400
$netConfigSubtext5.Size = New-Object Drawing.Point 590,20
$netConfigSubtext5.text = "• Select the Standby Adapter:"
$netConfigSubtext5.font = $SubTextFont
$netConfigComboBox1 = New-Object System.Windows.Forms.ComboBox
$netConfigComboBox1.Location = New-Object System.Drawing.Size(310,420)
$netConfigComboBox1.Size = New-Object System.Drawing.Size(260,20)
$netConfigComboBox1.Font = $SubTextFont
$netConfigComboBox1.DropDownStyle = "DropDownList"
[void] $netConfigComboBox1.Items.Add("None (All Adapters Active)")
$NetConfiguration = $netConfigList1,$netConfigSubtext5,$netConfigComboBox1
# CREATE FUNCTIONS
Function ListNetAdapters
{
$RemoveItems = #()
$AddItems = #()
for($index =0; $index -lt $netConfigList1.Items.Count; $index++)
{
$test = $netConfigList1.Items | Where-Object { $netConfigList1.Items.IndexOf($index) }
if($netConfigList1.GetItemChecked($index) -AND $netConfigComboBox1.Items -notcontains $test)
{
$AddItems += ,$test
}
ForEach($i in $netConfigComboBox1.Items){
IF(($netConfigList1.CheckedItems -notcontains $i) -AND ($i -ne 'None (All Adapters Active)')){$RemoveItems += ,$i}
}
}
ForEach ($i in $RemoveItems){$netConfigComboBox1.Items.Remove($i)}
ForEach ($i in $AddItems){$netConfigComboBox1.Items.Add($i)}
}
Function AddNetConfiguration
{
ForEach ($i in $NetConfiguration){$form.controls.add($i)}
}
AddNetConfiguration
# DISPLAY FORM
$form.ShowDialog()
Basically, what i'm trying to accomplish is exactly what you would see in the Advanced Settings of a NIC Team in Windows Server 2012/2012 R2. I want the network adapters selected in the CheckedListBox to populate in the ComboBox and be removed if unchecked.
I've installed WMF 4.0 on my Windows 7 PC and this seems to work well, but I get "System.Object[]" in Windows Server 2012. So i'm apparently missing the big picture or doing something wrong.
Windows Server 2012 comes with PowerShell v3.0, you have to make it to WMF4.0
Answer moved from question by editor
I was able to get it working after I fixed the $ListNetAdapters function. I think I was over complicating it before.
Function ListNetAdapters
{
$RemoveItems = #()
$AddItems = #()
ForEach($checkedItem in $netConfigList1.CheckedItems){
IF($netConfigComboBox1.Items -notcontains $checkedItem){$AddItems += ,$checkedItem}
}
ForEach($item2Badded in $AddItems){$netConfigComboBox1.Items.Add($item2Badded)}
ForEach($dropdownItem in $netConfigComboBox1.Items){
IF($netConfigList1.CheckedItems -notcontains $dropdownItem){$RemoveItems += ,$dropdownItem}
}
ForEach($item2Bremoved in $RemoveItems){
IF($item2Bremoved -ne 'None (All Adapters Active)'){$netConfigComboBox1.Items.Remove("$item2Bremoved")}
}
}

Powershell filedownload from https

I am trying to download several files using Powershell and its Invoke-WebRequest method.
I'm basically looping through several filenames (I know that they are available on the server) and download them.
My problem is that my script works for the first file and fails for every file that follows. When I open one of the later files (.csv`s) there is just some html code in it).
I already read a lot about passing session cookings but I am not sure if this is my problem or how I can do that.
My script so far looks like this:
$httpsUser = 'XXX'
$httpsPass = 'YYY'
foreach ($instrument in 'ivv','ijh','ijr','iwm') {
$Source = 'https://***', `
$instrument, '-en_us.csv' -join ""
$Target = 'C:\User\', `
$instrument, '-en_us.csv' -join ""
$uri = New-Object “System.Uri” “$Source”
$WebClient = [System.Net.HttpWebRequest]::Create($uri)
$webclient.Proxy.Credentials =
[System.Net.CredentialCache]::DefaultNetworkCredentials
$webclient.Credentials =
New-Object System.Net.NetworkCredential($httpsUser,$httpsPass)
Invoke-WebRequest -Uri $Source -OutFile $Target
}
Thank you all and let me know what you think :)
It seems like you don't using the HttpWebRequest you created to download the file. Anyway, I would recommend using System.Net.WebClient:
$wc = New-Object System.Net.WebClient
$wc.Credentials = New-Object System.Net.NetworkCredential($httpsUser,$httpsPass)
$wc.DownloadFile($Source, $target)
Try using webclient methods DownloadFile(src,dst). Should be something like this:
$httpsUser = 'XXX'
$httpsPass = 'YYY'
foreach ($instrument in 'ivv','ijh','ijr','iwm') {
$Source = 'https://***', `
$instrument, '-en_us.csv' -join ""
$Target = 'C:\User\', `
$instrument, '-en_us.csv' -join ""
$webclient = New-Object -TypeName Net.WebClient
$webclient.Encoding = [System.Text.Encoding]::UTF8
$webclient.UseDefaultCredentials = $true
$webclient.Proxy.Credentials = New-Object System.Net.NetworkCredential($httpsUser,$httpsPass)
$webclient.DownloadFile($Source,$Target)
}
Thank you all for your answers. I figured out now that the site generates a security token while logging in. This token needs to be passed in every webrequest. I was not yet able to figure out how to do that with powershell but know that perl has a build in function (called $merch) for exactly this problem.
To solve my problem I had to automatize the IE :( (I know this is not the most sophisticated way but right now it is the quickest solution. If anyone is interested here is the code for that:
$ie = new-object -ComObject 'InternetExplorer.Application'
$requestUri = 'https://www.trololo.com'
$userIdFragment = "userName";
$passwordIdFragment = "password";
$buttonIdFragment = "submitLogin";
$ie.visible = 'false'
$ie.navigate($requestUri)
while($ie.Busy) { Start-Sleep -Milliseconds 100 }
$doc1 = $ie.Document
$doc1.getElementsByTagName("input") | % {
if ($_.id -ne $null){
if ($_.id.Contains($buttonIdFragment)) { $btn = $_ }
if ($_.id.Contains($passwordIdFragment)) { $pwd = $_ }
if ($_.id.Contains($userIdFragment)) { $user = $_ }
}
}
$user.value = "XXXX"
$pwd.value = "YYYY
$btn.disabled = $false
$btn.click()
while($ie.Busy) { Start-Sleep -Milliseconds 5000 }
$ie.navigate($requestUri)
while($ie.Busy) { Start-Sleep -Milliseconds 200 }
$doc1 = $ie.Document
$link = $doc1.getElementsByTagName("a") | where-object {$_.href -match "Your String"}
$link.click()
Start-Sleep -Milliseconds 1000
$wshell = new-object -com wscript.shell
$wshell.appactivate("Internet Explorer")
$wshell.sendkeys("%s")

Resources