I try to run this PowerShell script to get counter.
[CmdletBinding()]
param (
[Parameter(Mandatory = $true)]
[String]
$DatabaseName
)
$ErrorActionPreference = "Stop"
$VerbosePreference = "Continue"
cls
Write-Output "Collecting counters..."
Write-Output "Press Ctrl+C to exit."
$counters = #("\Processor(_Total)\% Processor Time", "\LogicalDisk(C:)\Disk Reads/sec", "\LogicalDisk(C:)\Disk Writes/sec",
"\LogicalDisk(C:)\Disk Read Bytes/sec", "\LogicalDisk(C:)\Disk Write Bytes/sec", "\SQLServer:Databases($DatabaseName)\Log Bytes Flushed/sec")
Get-Counter -Counter $counters -SampleInterval 1 -MaxSamples 3600 |
Export-Counter -FileFormat csv -Path "C:\sql-perfmon-log.csv" -Force
But I got error when ran the script.
Error on the screen.
I found out that error occur in "\SQLServer:Databases($DatabaseName)\Log Bytes Flushed/sec"
Can somebody prompt me How I can enter a specific instance probably with credentials?
I see you're trying to run a powershell script from a command prompt.
Make sure you're doing this on the machine your SQL databases are hosted on.
You need to either open powershell administratively on your computer, or if you already have an administrative command prompt open, type "powershell" into it.
You can either paste all the code into your current host after specifying a string for $DatabaseName or just dot-source . the script and pass $DatabaseName as a parameter into the script.
If you're not sure what any of that means, take a look at
https://technet.microsoft.com/en-us/library/dn425048.aspx for more information on getting started with using powershell.
Related
I've setup a SQL Server 2016 agent job that has 2 steps that is executed by the same service account, Step 1 executes an SSIS package that writes 2 files out to a share. Step 2 executes embedded powershell code that combines these 2 files into a single file and creates a file on that same share where the 2 files were created by SSIS. When I execute the job, Step 1, the SSIS package completes successfully and creates the 2 files on this share. But when Step 2 executes I get the error below. Just a point of info, when I run this script locally from my windows 10 box, I have no issues.
I guess my question is, if SSIS can execute successfully with the same service account can this be a permissions issue for powershell scripts? I'm not a server admin so if this is a stupid questions please forgive my ignorance. Any help/direction anyone can provide would be appreciated.
Message
Executed as user: XXX\sqlsvc02. The job script encountered the following errors. These errors did not stop the script: A job step received an error at line 12 in a PowerShell script. The corresponding line is 'Get-Content $pathCounts, $pathDetails | Set-Content $outFile'. Correct the script and reschedule the job. The error information returned by PowerShell is: 'Cannot find path '\xxx\shared\MonthlyReports\BoundPoliciesAddedAtFaultEndorsementWithin10Days_Counts.csv' because it does not exist. ' A job step received an error at line 12 in a PowerShell script. The corresponding line is 'Get-Content $pathCounts, $pathDetails | Set-Content $outFile'. Correct the script and reschedule the job. The error information returned by PowerShell is: 'Cannot find path '\xxx\shared\MonthlyReports\BoundPoliciesAddedAtFaultEndorsementWithin10Days_Details.csv' because it does not exist. '. Process Exit Code 0. The step succeeded.
Here is my powershell script:
# Define variables
$path = '\\xxx\shared\MonthlyReports'
$pathCounts = Join-Path -Path $path -ChildPath 'BoundPoliciesAddedAtFaultEndorsementWithin10Days_Counts.csv'
$pathDetails = Join-Path -Path $path -ChildPath 'BoundPoliciesAddedAtFaultEndorsementWithin10Days_Details.csv'
$date = Get-Date
$dateStr = $date.ToString("yyyyMM")
# Define combined file name
$outFile = Join-Path $path -ChildPath("BoundPoliciesAddedAtFaultEndorsementsWithin10Days_" + $dateStr + ".csv")
# Execute combine files code
Get-Content $pathCounts, $pathDetails | Set-Content $outFile
Here is an image of what Step #2 looks like:
I'm trying to write a script in Power Shell to connect to a remote server and execute a .bat file. Since I wanted to do this for more than one server I thought I could place the .bat file on another server which shares ist resources and call it from there, but that does not work. When I place the .bat file in my temp folder and execute it via the script it works. However trying to execute it from the shared resources does not. Why is that?
Note: I can manually start the process via the Task-Manager that starts the .bat file in the shared resources and it works.
script:
$CompName = "myotherserver"
$cred = get-credential
$process = get-wmiobject -query "SELECT * FROM Meta_Class WHERE __Class = 'Win32_Process'" -namespace "root\cimv2" -computername $CompName -credential $cred
$results = $process.Create( "cmd.exe `/c \\mysharedresc\temp\started.bat" )
started.bat:
echo started > c:\temp\started.txt
If you need more annotations or Information please ask for it.
Edit: Working means for me it creates the started.txt in C:\temp. Not working means it does not (but in this case there is no error given.)
So I am trying to write a Powershell script that creates a backup of a databases, compresses the backup, and uploads it to an FTP site. Here is a part of my script
Sample Script/Code:
Write-Host "Backup of Database " $databaseName " is starting"
push-location
Invoke-Sqlcmd -Query "--SQL Script that backs up database--" -ServerInstance "$serverName"
pop-location
Write-Host "Backup of Database " + $databaseName " is complete"
#Create a Zipfile of the database
Write-Host "Compressing Database and creating Zip file...."
sz a -t7z "$zipfile" "$file"
Write-Host "Completed Compressing Database and creating Zip file!"
I am wanting to prevent any code after the "Invoke-Sqlcmd......." part from being executed until the SQL script backing up the database is complete because the compression line is failing to find the backup of the database because the backup takes a fairly long time to complete.
I am extremely new to using Powershell and didn't quite understand what a couple of the other possibly related questions I found were offering as a solution as I call my SQL statement a different way.
Possible Related Questions:
Get Powershell to wait for an SQL command to execute
Powershell run SQL job, delay, then run the next one
Are you sure your ...script that backs up the database isnt just throwing an error and the ps continuing?
This seems to indicate that it does in fact wait on that call:
Write-Host "starting"
push-location
Invoke-Sqlcmd -Query "waitfor delay '00:00:15';" -ServerInstance "$serverName"
pop-location
Write-Host "complete"
In any case, you should guard against the file existing, by either aborting if the file does not exist or polling until it does (i'm not 100% on when the .bak file is written to disk).
# abort
if(!(test-path $file)) {
}
# or, poll
while(!(test-path $file)) {
start-sleep -s 10;
}
So, I am fairly new to PowerShell and need to create a script to rename the computers in our office. That portion of the script works. The part I am having trouble with is the output.
I have this set in task scheduler, but when it runs I do not see if the rename was successful. Below is my script and below that is what goes into the text file.
start-transcript -path C:\Users\abhagwandin.SENECA\Desktop\RenameResults.txt
$CSV = Import-Csv "C:\Users\abhagwandin.SENECA\Desktop\Computer Desktop Names Test.csv" -Header OldName, NewName
Foreach ($name in $CSV)
{
write-output $name
netdom renamecomputer $name.OldName /newname: $name.NewName /userd: admin /passwordd: pass /usero: admin /passwordo: pass /reboot /force
}
stop-transcript
-------------------------------------------------------------------------------
**********************
Windows PowerShell Transcript Start
Start time: 20150520154216
Username :
Machine : (Microsoft Windows NT 6.1.7601 Service Pack 1)
**********************
Transcript started, output file is C:\Users\abhagwandin.SENECA\Desktop\RenameRe
sults.txt
OldName NewName
------- -------
JFLAHNYCD1 JFLAHERTY
**********************
Windows PowerShell Transcript End
End time: 20150520154218
**********************
You know that renaming a computer through a cmdline command in powershell instead of using the built in cmdlets can give problems with the output if you don't parse the output (and preferably create a new object for it)?
Why don't you use rename-computer or the rename() method of the win32_computersystem wmi class? Both can be used remotely so you don't even have to schedule tasks that way.
Just create an input file with the current name and the desired names and use a loop to process them.
I am in the middle of moving to the cloud, migrating from SBS 2003 Active Directory, to 2008 R2.
I configured a new user, and noticed that the user was unable to reset their password.
My Server Admin showed me how to use net user.
I noticed that I can obtain information from some accounts and not others. With over 100 accounts to process, I thought I'd try PowerShell.
In this post (Use powershell to look up 'net user' on other domains?) Lorenzo recommends using Get-ADUser (and this applies to polling from another domain). When I run Get-ADUser from my PowerShell prompt, I receive a message stating that the commandlet is not recognized.
I am reading the user IDs from a text file, and sending the output to a log file so that I can send to the server admin for further analysis.
Here is my code so far (please note that I am completely new to PowerShell):
# Get our list of user names from the local staff.txt file
$users = get-content 'C:\Scripts\staff.txt'
# Create log file of output:
$LogTime = Get-Date -Format 'MM-dd-yyyy_hh-mm-ss'
$CompPath = "C:\Scripts\"
$CompLog = $CompPath + "NetUserInfo" + $LogTime + ".txt"
New-Item -path $CompLog -type File
foreach ($user in $users) {
#Testing user:
"Testing user: $user" | out-file $CompLog -Append
# Obtain user information using net user:
net user $user /domain >> $CompLog
# Pause to let system gather information:
Start-Sleep -Second 15
}
As the script runs currently, my log file will have two or three user names followed by the response "The request will be processed at a domain controller for domain (domain)"
If net user, from CMD, would return "System error 5 has occurred, Access is denied." This is not logged in the output file. IF net user, from CMD, would return user information, this is logged to the output file. I am currently receiving output for only a couple users, but when I run the command from CMD, I am able to retrieve information for at least ten.
My first thought was that I needed to wait for the net user command to complete (hence the Start-Sleep command) but that has not had any effect on the output.
Any assistance would be greatly appreciated.
Sorry, I don't have enough reputation to add a comment.
When you run programs in Powershell (such as net user... or ping) it should be running exactly the same as it would in the normal command prompt (cmd).
If I understand correctly you're getting different results when you (effectively) run the same thing in Powershell or Command Prompt. Is that right?
Are you using the ISE to build your script? If so you can set Breakpoints that will pause the script and allow you to see what the variables are. It could be that the $user variable isn't holding what you think it should be, or that the value doesn't match the name for a domain user account.
EDIT:
What happens when you run the net user ... command interactively (e.g. not as a script, but manually) in Powershell? Do you get an error? If so, what does the error say?
Additional related stuff:
You shouldn't need the Start-Sleep as the commands are run in order, and the next line shouldn't execute until the previous on has completed.
Also, which version of Powershell are you using?
(You can check by running $host.version.Major)
The Get-ADUser cmdlet requires version 3 (I believe) and also needs to import the Active Directory module.
The reason the error output is not being appended to the log file is because you are only redirecting the STDOUT (standard output stream). To also redirect the STDERR (standard error stream) change
net user $user /domain >> $CompLog
to
net user $user /domain 2>&1 $CompLog
This explains it a bit more:
http://www.techotopia.com/index.php/Windows_PowerShell_1.0_Pipes_and_Redirection#Windows_PowerShell_Redirection_Operators