Quantcast
Channel: PowerShell.com – PowerShell Scripts, Tips, Forums, and Resources
Viewing all 6937 articles
Browse latest View live

How to Manage Microsoft Azure SQL Database Using PowerShell with REST APIs

$
0
0

In our previous article published on this forum, we have presented a somewhat unorthodox (from the perspective of a typical DBA or IT Pro - but certainly not that of a developer) method of managing Azure SQL Database that involves directly invoking REST APIs, providing an alternative to PowerShell-based scripting, which relies on Azure module cmdlets to run the underlying managed code. While considerably more challenging, such an approach offers more flexibility, facilitating functionality that is not directly exposed via Azure Portal or Azure PowerShell cmdlets. We have illustrated the principles of this methodology through a couple of fairly straightforward examples, enumerating all SQL Database servers in a given subscription and, subsequently, creating a new server (effectively, emulating Get-AzureSqlDatabaseServer and New-AzureSqlDatabaseServer cmdlets). Now, it is time to show some of the unique benefits of REST APIs by demonstrating their unique capabilities, not available via PowerShell.

Read More


emailed notifications

$
0
0

I opted to receive email notifications when a thread I commented on or created gets a new comment.  However, I did not expect to receive email notifications for comments that I had made.  I don't really need to be notified and told that I have created a thread or replied to a post.  With that said, how do you turn email notifications off?

Changing pagefile on Server 2012 from default to specific size and place.

$
0
0

I am trying to change the pagefile on my new servers from Automatically manage paging file size for all drives to Custom - C: drive Initial size 4096 and Maximum size 4096

 

If I can, I would like to be able to put it back to the original configuration too.

Here is what I have so far with the error I am getting.

PS C:\> Set-WmiInstance -Class Win32_PageFileSetting -Arguments @{name="C:\pagefile.sys"; InitialSize = 4096; MaximumSize = 4096}

Set-WmiInstance : Generic failure 

At line:1 char:1

+ Set-WmiInstance -Class Win32_PageFileSetting -Arguments @{name="C:\pagefile.sys" ...

+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

    + CategoryInfo          : InvalidOperation: (:) [Set-WmiInstance], ManagementException

    + FullyQualifiedErrorId : SetWMIManagementException,Microsoft.PowerShell.Commands.SetWmiInstance

 

IE not visible from scheduled PS script

$
0
0

Hi all,

I'm trying to create a PS logon script that will listen to a serial port, pass on the data to its original application, parse the data, and use the result to open an internal server and display an information page relating to the data.

I've gotten it working from an active powershell session, but when I run it as a scheduled task I can't see the IE that it calls.  I know that it is actually loading and performing login and lookup because I can see a new user session created on our internal webpage, and each time I feed the serial port a new barcode scan I can see that it passes it on towards the originally intended application.

I've seen some discussion on TechNet that seems to indicate that using IE in this way isn't possible, but then how is it managing to login to the site?

 


# Variables
$username = ""
$password = ""
$meterno = ""
$rawmeterno = ""
$ReceivePort = "COM6"
$SendPort = "COM7"


Function Initialize () {
$global:RCport = $null
$global:SNport = $null

$global:RCport = new-object system.io.ports.serialport $ReceivePort,9600,none,8,one
$global:RCport | add-member -membertype "NoteProperty" -name "identifier" -value "ReceiveSerial"
$global:RCport.open()
#$global:RCport
$global:SNport = new-object system.io.ports.serialport $SendPort,9600,none,8,one
$global:SNport | add-member -membertype "NoteProperty" -name "identifier" -value "SendSerial"
$global:SNport.open()
#$global:SNport
}

Function ParseMeter($rawmtr){
$meter = $rawmtr |
 %{
  if ($_ | sls -pattern "SD") {
   ([regex]"[0-9]{5}SleepDrinks").matches($_) | % {$_.value}}
  elseif ($_ | sls -pattern "TD/TR") {
   $TD = ([regex]"[T]Drinks[/][T][R][0-9]{3}").matches($_) | %{$_.value}
   $TD = ($TD -replace "/TR", "")
   $TD}
  else {$_ | % { $_.tostring().split()[1] }}
  }
write-host "ParseMeter result: $meter `n"
$meter
}

Function Main {
 Do{ 
  $rawmeterno = $global:RCport.readline()
  write-host $rawmeterno
  $meterno = $rawmeterno | %{ParseMeter($_)}
  $global:SNport.writeline("$rawmeterno")
  
  #check for ie
  $ie
  if (!($ie)) {
   $ie = New-Object -com InternetExplorer.Application
   $ie.visible=$true
   sleep -s 2}#if
  $ie.navigate2("http://server/endpointlookup.aspx")
  sleep -s 2
  $ie.locationname
  $ie
  
  #login
  if ($ie.locationname -eq "http://server/login.aspx?ReturnUrl=%2fcc%2fendpointlookup.aspx") {
   sleep -s 2
   write-host "Login Function"
   $ie.visible = $true
   $ie.navigate2("http://server/login.aspx")
   while($ie.busy) {start-sleep -s 2}
   $ie.document.getElementById("LoginName").value= $username
   sleep -s 1
   $ie.document.getElementById("Password").value = $password
   sleep -s 1
   $ie.document.getElementById("LoginBtn").click()
   sleep -s 3
   while($ie.busy) {start-sleep -s 2}
   
   #lookup
   $ie.navigate2("http://server/endpointLookup.aspx")
   while($ie.ReadyState -ne 4) {start-sleep -s 1}
   sleep -s 1
   $meterno
   $ie.document.getElementById("ctl00_PageBody_MeterNumberBox").value = $meterno
   write-host "meterno assigned"
   sleep -s 2
   $ie.document.getElementById("ctl00_PageBody_RetrieveButton").click()
   write-host "button clicked"
   sleep -s 2
   write-host "about to assign 'details' to variable"
   $details = @( $ie.document.getelementsbytagname('a')) | where-object {$_.innerText -eq 'Details'}
   $details
   write-host "variable assigned, about to click"
   $details.click()
   write-host "details clicked"
   Trap{"$_" ; $global:SNport.close(); $global:SNport.dispose(); $global:RCport.close(); $global:RCport.dispose(); $ie.quit() ;sleep -s 2; Break }
  }#if
  
  #lookup
  else {
   $ie.navigate2("http://server/endpointLookup.aspx")
   while($ie.ReadyState -ne 4) {start-sleep -s 1}
   write-host "Lookup Function"
   $ie.visible = $true
   $ie.document.getElementById("ctl00_PageBody_MeterNumberBox").value = $meterno
   write-host "Meterno assigned"
   sleep -s 1
   $ie.document.getElementById("ctl00_PageBody_RetrieveButton").click()
   write-host "clicked GO"
   sleep -s 1
   $elsedetails = @( $ie.document.getelementsbytagname('a')) | where-object {$_.innerText -eq 'Details'}
   write-host "variable assigned, about to click"
   $elsedetails.click()
   write-host "details clicked"
   Trap{"$_" ; $global:SNport.close(); $global:SNport.dispose(); $global:RCport.close(); $global:RCport.dispose(); $ie.quit() ;sleep -s 2; Break }
   }#else
 }#do
 while ($global:RCport.isopen -eq $true)
}#function - Main

Initialize
sleep -s 2
Main

 

The scheduled task is set to run at login, elevated.  And I'm testing this on Win7(64) using IE10 and PS 3.0.

As you can see in the script, I set IE to visible in several places.  Any ideas?

 

Thanks for any feedback!

change windows service "log on as" to user account. NO! Slow WMI, bad boy.

$
0
0

get-module |Select -expandedproperty exportedcommands |?{$_ -notlike "Get-WmiObject" -AND ($_ | gm -membertype method -name change) -ne $null}

 

I need this command to return a cmdlet that will change the service log on as account and password.  

Help with CSV Output

$
0
0

I am trying to cobble together a script to compare two CSV files and output the difference to a third CSV.  So far it does show me the difference between the two files, but my Output file is not in the correct format.  It does not give me the header row, and it places all output into one cell.

From what I understand, when it compares the two files, it reads all three of my columns as one object.  This does give me the correct output in all of my tests as some users have the same name, but different ID Number. 

Now I just need to Export my results to CSV in a more friendly format.  From what I have read I need to use a CustomPSObject, but my attempts have all failed miserably.

Here is my current code.

$path         = Split-Path -parent $MyInvocation.MyCommand.Definition
$newfile      = $path + "\a.csv"
$oldfile      = $path + "\b.csv"
$diffile      = $path + "\c.csv"

Compare-Object -ReferenceObject (get-content $oldfile) -DifferenceObject (Get-Content $newfile) | Where-Object {$_.SideIndicator -eq "=>"} | Export-CSV $diffile

 

Thanks for any help.

 

 

Trying to create script which allows user to specify target PC then accepts user credentials to perform Invoke-Comand on remote PC

$
0
0

I'm trying to build a simple script.

1. Allow user to name a target PC

2. Perform registry key deletion on target

 

If  I run the following strings individually I achieve my objective.

1. $name = Read-Host -Prompt "Please type in the MachineName." 

2. Invoke-Command -cn $name -credential Domain\User {pushd;sl 'HKlM:\SYSTEM...'; if(test-path 'Key XYZ'){remove-item ''Key XYZ''}ElSE{"''Key XYZ'' does not exist"};popd}

 

How do I get these two strings to wait for my input to specify target name: $name, then prompt me for credentials and perform Reg key deletion?

When I run them together I do not get a prompt.

 

Using Powershell to clean up Stale Computers

$
0
0

Basically what I want is all of the computers that have not authenticated in the last 30 days in a specific OU.  This following command works but is not exactly what I want.

Search-ADAccount-AccountInactive-ComputersOnly-SearchBase"OU=Test,DC=contoso,dc=com"-TimeSpan90.00:00:00|Format-TableName,ObjectClass-A

however, I would like the timestamp to show up as well and export it to excel. Anyone has any ideas?

I appreciate the help


The PowerShell File Frontier, Part 2: File Length

$
0
0

In my previous lesson we looked at a way to copy files between computers. Although you could just as easily copy to a different local location or use Move-Item which will copy and then delete the file. Yes, I realize there are tools like Robocopy that you could also use but this is Prof. PowerShell not Prof. Robocopy and my aim is to instruct as much as it is to provide practical solutions.

Read More 

The PowerShell File Frontier, Part 1

$
0
0

In my day-to-day work, I use a variety of cloud based services to keep a variety of folders synchronized between the different computers I use. But occasionally I need to grab some files from a nonsynchronized computer and copy them to one of my synchronized devices. Use PowerShell, this is a pretty straightforward task. In fact, I bet if you have to manage files for people, or even for yourself, you might find these techniques useful, especially if you are still learning PowerShell.

Read More

PowerShell - WMF 5.0 July preview uninstallation fails

$
0
0

Fortunately, the PowerShell Team is already aware of this issue and documented this behavior....

Read More

 

Configuring IIS Prerequisites for the App-V 5 Server with PowerShell

$
0
0

While I’d much rather recommend that you configure a Windows Server that will host the App-V 5.0 server components via a solution such as MDT with the required IIS components enabled in an automated build, here’s how to add the components with PowerShell.

The following code uses the Add-WindowsFeature to add the IIS components that are required to support the App-V 5.0 Management and Publishing Servers. These are the minimum required components as requested by the setup application.

Unearth the Windows Experience Index in Windows 8.1 with PowerShell

$
0
0

Greg Shultz demonstrates how to use the RunWinSAT batch file and the DisplayWinSAT PowerShell script to display your Windows 8.1 system's Windows Experience Index scores.

Read More                    

Backup MSSQL databases and verify backups

$
0
0

Hello all, 

i have a simple script that backups all none system DBs on instance which works fine.

I want to add something like mssql "verify-only" to check if backups are OK.

Bellow is the script that i have so far, but is is not workingn as expected.

 

$date = get-date -format  "dd.MM.yyyy"
$dir = "C:\SQLbackups\$date"
New-Item -type Directory -path $dir




$ServerName = "localhost\Instace1"
$BackupDirectory = $dir
$BackupDate = get-date -format yyyyMMdd_HHmmss
write-host "Creating database backups new folder" 

[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.SMO") | Out-Null
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.SmoExtended") | Out-Null
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.ConnectionInfo") | Out-Null
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.SmoEnum") | Out-Null
#[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.SMO") | out-null

$ServerSMO = new-object ("Microsoft.SqlServer.Management.Smo.Server") $ServerName
$DatabaseList = $ServerSMO.Databases

foreach ($Database in $DatabaseList)
{
if($Database.IsSystemObject -ne $True -and  $Database.IsAccessible -eq $True)

{
$DatabaseName = $Database.Name
write-host "##########################################################"
write-host "##### Database" $Database.Name "backup in progress #######"
write-host "##########################################################"
$DatabaseBackup = new-object ("Microsoft.SqlServer.Management.Smo.Backup")
$DatabaseBackup.Database = $DatabaseName
$DatabaseBackup.Action = "Database"
$DatabaseBackup.Action = [Microsoft.SqlServer.Management.Smo.BackupActionType]::Database
$DatabaseBackup.Initialize = $TRUE
$DatabaseBackup.Devices.AddDevice($BackupDirectory + "\" + $DatabaseName + "_" + $BackupDate + ".BAK", "File")
$DatabaseBackup.SqlBackup($ServerSMO)
#$DatabaseRestore = new-object ("Microsoft.SqlServer.Management.Smo.Restore")
#$DatabaseRestore.Devices.AddDevice($DatabaseBackup, [Microsoft.SqlServer.Management.Smo.DeviceType]::File)
#$DatabaseRestore.SqlVerify($ServerSMO)
#write-host "Backed up file" $Database.Name  " has been verified. Health status OK"
}
}


set-location $BackupDirectory
$DBBackups = Get-content backups.txt

foreach ($DBBackup in $DBBackups)
{
$DatabaseRestore = new-object ("Microsoft.SqlServer.Management.Smo.Restore")

$DBRestore.Devices.AddDevice($DBBackup, [Microsoft.SqlServer.Management.Smo.DeviceType]::File)
if (!($DBRestore.SqlVerify($ServerSMO))){

write-host "Backed up file" $Database.Name " has been verified. Health status OK"
}
}

 

So here, backups are done, and second foraech  should go through txt file in which all backups are listed and "Microsoft.SqlServer.Management.Smo.Restore" should run SQLVerify against each database .bak file.

What i have in output in ISE is not what i want. It is like it ran multiple times against the last file in txt. instead of checking each file.


Backed up file testDB1  has been verified. Health status OK
Backed up file testDB1  has been verified. Health status OK
Backed up file testDB1  has been verified. Health status OK
Backed up file testDB1  has been verified. Health status OK

 

This os one case.

The second case is If i remove the second foreach in the script and put  ("Microsoft.SqlServer.Management.Smo.Restore" in the first foreach loop where i am backing up each DB ( it is commented in the code here)  it is working but returns one strange "false" in output like:

 

##########################################################
##### Database Test1_database backup in progress #######
##########################################################
False
Backed up file Test1_database  has been verified. Health status OK
##########################################################
##### Database testDB1 backup in progress #######
##########################################################
False
Backed up file testDB1  has been verified. Health status OK

Can someone help me out here.

Auditing mapped drives on a network by OU

$
0
0

Similar to this post in 2012: http://powershell.com/cs/forums/p/9777/16289.aspx

I'm looking for a powershell script that will let me all the machines in an OU on my network and see what drives they have mapped, either by user or GP. I've tried running the second script down in the post and I'm getting the same error the previous question poster got: 

----------------

Test-Connection : Cannot validate argument on parameter 'ComputerName'. The argument is null or empty. Supply an argume

nt that is not null or empty and then try the command again.

At line:22 char:33

+ if(Test-Connection -ComputerName <<<<  $child.name -Count 1 -Quiet){

    + CategoryInfo          : InvalidData: (:) [Test-Connection], ParameterBindingValidationException

    + FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.PowerShell.Commands.TestConnectionCommand

----------------

If anyone can help get this script running or suggest a different solution I'd greatly appreciate it.

-Adam


Display output in HTML

$
0
0

Hello Guys,

Am new to powershell, i have the below script to find the directory space. 

My requirement: 

1. I need to display the output (diskspace in GB) in a HTML format.

2. The HTML will display the output as a pie chart or bar chart. (indicates in red or green respectively if it cross particular disk size)

3. HTML with header and with time and date it generated the report.

 

Please help in assisting. 

 

write-host "- $directory" -foreground "GREEN"
[string]$result = robocopy.exe /b /l /mir "
\\Server\directory" "C:\temp" /r:0 /w:0 /ns /nc /nfl /ndl /njh /Bytes

if (!($lastexitcode -eq 16))
{
$pos = ($result).indexof("Bytes : ")
$start = $pos + 8
$length = $result.length
$end = $length - $start
$newstring = ($result).substring($start,$end) 
$newstring = $newstring.trim()
$result = $newstring.split()[0]
echo $result

$final = [math]::round($result /1Gb, 3)

echo $final

}
else
{
echo "CANNOT ACCESS"
}

Windows Management Framework 5.0 (September 2014) preview is available for download

$
0
0

An updated version of WMF 5.0 preview is now available with a great set of enhancements and new features. Some of these changes are:

Read More

Friday Fun: Creating PowerShell Scripts with PowerShell

$
0
0

Sometimes PowerShell really does seem like magic. Especially when you can use it to handle complicated or tedious tasks, such as creating a PowerShell script. I know many an IT Pro who want to script but without having to actually write a script.

Read More 

How can i use Get-Focus or Get-Window in powershell 2.0

$
0
0

Dear All,

Hope you all are fine.

This is my first post on Powershell.com

 

Question:>>  How can I use Get-Focus or Get-Window in powershell 2.0.

I am trying to get the total uptime of a process during a day using

Example:(get-date).Subtract((Get-Process firefox).starttime)|findstr 'TotalHours'

Now the concern is this is not the efficient time as the user can open the process window and minimize it for full day.

**** So I am looking for the cmdlet that will only capture the duration when the Process/Window has focus or is active. This way we will have the actual duration the user was working on that process.

Dear Experts, kindly guide me

Limitation - I cannot upgrade Powershell version, so need a fix with powershell 2.0 onlySad

I am using powershell 2.0 and there is No cmdlet available to match my requirement of above cmdlet

I have already checked all available in 2.0

http://technet.microsoft.com/en-us/magazine/ff714569.aspx

PS C:\Users> get-host


Name             : ConsoleHost
Version          : 2.0
InstanceId       : 2aec344a-619b-4455-b086-42ba5ca60995
UI               : System.Management.Automation.Internal.Host.InternalHostUserInterface
CurrentCulture   : en-US
CurrentUICulture : en-US
PrivateData      : Microsoft.PowerShell.ConsoleHost+ConsoleColorProxy
IsRunspacePushed : False
Runspace         : System.Management.Automation.Runspaces.LocalRunspace



PS C:\Users> $PSVersionTable

Name                           Value
----                           -----
CLRVersion                     2.0.50727.5477
BuildVersion                   6.1.7601.17514
PSVersion                      2.0
WSManStackVersion              2.0
PSCompatibleVersions           {1.0, 2.0}
SerializationVersion           1.1.0.1
PSRemotingProtocolVersion      2.1

 

Set DeviceAccessState from Allowed to Blocked

$
0
0

Hello,

when a customer connects his mobíle device to our Exchange (Version: 14.02.0283.003), the mobile device is quarantined till an admin allows the connection.

When the admin wants to delete the partnership (f.e. with remove-activesyncdevice), the DeviceAccessState will not turn to blocked or quarantined.

That means, that the customer can connect this device again to the Exchange Server without knowing of the admin.

How can I (admin) reset the settings so that I will be asked again, when the customer wants to connect to Exchange.

Greetings Berra

Viewing all 6937 articles
Browse latest View live