Script not running in task scheduler
Help with Validation Script
Hi All
I am having an issue with the script below which gives me the results im after for about 100 rows but then it exports incorrect values.
I am trying to compare my CSV which contains GroupName, Description, Managedby against AD and export 'Matched' expressions for matched results, Failed for not matched results and export AD's description and Manager so I can identify the issues.
Please help :)
########################################################################################################## # # # This script imports a spread sheet and checks each row for details and out puts the results # # # ########################################################################################################## #$csv = import-csv C:\PS\import\ESP_Final_Pre_Valuation_testing.csv $csv = import-csv C:\PS\import\ESP_Final_Pre_Valuation.csv foreach ($row in $csv) { $adgroup = get-adgroup $row.groupname -Properties description | select description $adgroup.managedby = (get-aduser -identity $adgroup.managedby) | select name try{ #Searches AD for the group name from the CSV if (get-adgroup $row.groupname){ Write-Host -ForegroundColor cyan "Group"$($row.groupname)"has been found" $row.NameCheck = 'Matched' } else { Write-Host -ForegroundColor red "Group"$($row.groupname)"could not be found" $row.NameCheck = 'Failed' } # Compares AD's group description against the description in the CSV if (Compare-Object $adgroup.description $row.Description) { Write-host -ForegroundColor red "Group"$($row.groupname)"description doesnt match" $row.DescriptionCheck = 'Failed' $row.addescription = $adgroup.description } else { Write-Host -ForegroundColor green "Group"$($row.groupname)"has a matching Description" $row.DescriptionCheck = 'Matched' $row.addescription = $null } # Compares AD's group managedby against the one in the CSV if (Compare-Object ($adgroup.managedby).name $row.managedby) { Write-Host -ForegroundColor red "Group"$($row.groupname)"owner doesnt match" $row.ManagedbyCheck = 'Failed' $row.admanagedby = $adgroup.managedby } else { Write-host -ForegroundColor green "Group"$($row.groupname)"has a matching owner" $row.ManagedbyCheck = 'Matched' } #Exports the above results to a CSV $row | select * | export-csv C:\PS\Exports\ESP_Final_Validation.csv -Append -NoTypeInformation $row.admanagedby = $null $row.addescription = $null } catch{} finally{} }
Using Powershell to run a batchfile with arguments on another computer
Hi,
Can anyone help with this one?
I have a bunch of servers and one of them is the 'controller' for want of a better term.
Now and again we have to run a batch command on all of the servers. I can get a batch command to work remotely from Server 1 to Server 2 using PowerShell, but not when arguments are involved.
For example this works:
Invoke-Command –ComputerName Server2 -ScriptBlock {Start-Process "C:\Program Files\Folder1\Stop.bat" }
However this doesn't:
Invoke-Command –ComputerName Server2 -ScriptBlock {Start-Process "C:\Program Files\Folder1\Stop.bat" -stop -clean}
Neither does:
Invoke-Command –ComputerName Server2 -ScriptBlock {Start-Process "C:\Program Files\Folder1\Stop.bat" } -ArgumentList -stop -clean
If I run
C:\Program Files\Folder1\Stop.bat -stop -clean
Directly on server2, all is OK.
What am I doing wrong?
copy multiple files content in one file with file names
hello friends;
How can I copy multiple text files contents in one file with file names.
I used cat or type or get-content but this commands doesn't copy the file names in one file.
capture output to csv and use filter
I want to capture the output of script into a file that I could later email to group. I want to filter Name to only selective databases for my output file
[CmdletBinding()] $ssasInstance = 'ss1' [System.Reflection.Assembly]::LoadWithPartialName("Microsoft.AnalysisServices") $server = New-Object Microsoft.AnalysisServices.Server $server.connect($ssasInstance) $database=$server.databases foreach ($db in $server.databases) { $dbwriteout = $db|select name,state Write-host $dbwriteout $Cubes=New-object Microsoft.AnalysisServices.Cube $Cubes=$db.cubes }Thanks.
Command Completion when using Powershell Direct
Hello,
is there a way to enable command completion when connecting remotely to a VM via PowerShell Direct?
I'm using Windows Server 2016 TP5.
Thanks
Christian
Command Completion when using Just Enough Administration Sessions
Hello,
is there a way to enable command completion when connecting remotely to a VM to Just Enough Administration Context?
I'm using Windows Server 2016 TP5.
Thanks
Christian
Exporting SQLCMD output to a comma delimeted .csv file
Hello,
Want to run the below shown PS script. The only issue that I have now is writing to the output file with a comma delimiter. I should also have the column header. Can you please help with this?
Currently, when I open up the output file using Excel, there is no column separation. So, comma delimiter will help.
=================
##Save the below powershell script in folder "E:\PowerShellScripts\SQLServersBackupStatusFromMSDB.ps1"$QueryPath= "E:\PowerShellScripts\BackupStatusQuery1.sql"
$OutputFile = "E:\PowerShellScripts\BackupStatusQuery1_Output.csv"
$ExecuteQuery= Get-Content -path $QueryPath | out-string
#"Results -- > `r`n`r`n" > $OutputFile
FOREACH($server in GC "E:\PowerShellScripts\SQLServerList.txt")
{
$server
#"---------------------------------------------------------------------------------------------------------">> $OutputFile
#$server >> $OutputFile
#"---------------------------------------------------------------------------------------------------------">> $OutputFile
invoke-sqlcmd -ServerInstance $server -query $ExecuteQuery -querytimeout 65534 | ft -autosize | out-string -width 4096 >> $OutputFile
}
==============
Victor
Victor
getting ps to work from cmd line
Hi we are running 2008 r2 64 bit OS on server A and Windows Server 2003 STD SP2 (I believe this is a 32 bit OS) on server B. I am attempting to run powershell with the following syntax from the command line on A after remoting in to A as domain administrator.. xxx-yyyyyyy is server B.
powershell invoke-command -ComputerName xxx-yyyyyyy -ScriptBlock {'C:\aaaaa\bbbbbbbbbbb\ccccccccccccImport.vbs'}
from a directory on A called c:windows\winsxs\wow64_microsoft-windows-powershell-exe_somethingthatlookslikeaguid_6.1.nnnn.mmmmm._none_somethingelsethatlookslikeaguid.
the n's and m's in the path represent some digits whose meaning I don't know. And I'm not sure what the guids represent.
The reason I'm doing this is to simulate an issue I'm having doing the same thing from an app that runs on server A. That app seems to reach and execute the vb script thru powershell. But running from the command line doesn't even reach or execute the vb script. There are no errors in the dos window. The cmd prompt returns shortly (not immediately) after I hit return . Can someone help me just to get the cmd line to work?
I think what I am going to find once this works from the cmd line is that as in my app, logging in the vbscript works fine but execution of a 3rd party import function after preliminary logging and before final logging returns a return code of 0 but does nothing.
Debug simple powershell script: get macaddress, username and netbios in csv file
Hi everybody,
I'm not a killer in powershell and i want to retrieve localhostname, current user logged in, and macaddresses of local computer to export all in CSV file.
I writed a litle script to do this and I need your help to debug it
Here is my script
$macAddresses = Get-WmiObject win32_networkadapterconfiguration $tab=$macAddresses.macaddress $netbiosName=$(Get-WmiObject Win32_Computersystem).name $currentUser=$(Get-WmiObject Win32_Computersystem).username foreach ($mc in $tab) { write-output $mc write-output $tab write-output $netbiosName write-output $currentUser } | Export-Csv c:\temp\result.txt -NoTypeInformation -Encoding UTF8
here is error:
Thank you fro your help
Orwell
How to stop getting prompted to "Confirm"
Hello,
I have some Windows Server 2008 systems that I'm trying to run a powershell script on to delete some temp files, but I keep getting prompted with "Confirm... Y [Yes] [A] Yes to All...... ect" Is there a way to bypass the Confirm?
Thanks,
Tom
Tom Martin Email: tmartin@caa.com
Combining Multiple CSV Files with Powershell
Hi,
I have a number of CSV files that I want to combine into a single CSV file. They all have the same number of rows and one of the files has 2 columns.(i.e. a timestamp row and a numerical value that is associated with each timestamp) and all of the rest have a single column (a numerical value that is associated with the relevant timestamp in the first column of the first row but for a different system). I need the output file to have multiple columns e.g. if there is a single two-column file, as described, and 4 single-column files, the output file would have six columns with each of the single columns from the 4 single-column files being placed progressively to the right of the two-column file to allow information for the relevant timestamp for each of the 4 additional systems (as well as the original) to be viewed and ultimately graphed.
I have been trawling through the web and Powershell utilities such as import-csv, export-csv, get-content etc etc to figure out how I can do this but without success. I need the final output file that results from the combination to be in a format such that when I use if as the input to import-csv, the first row will be in a format such that each component of the first row will be a heading for the imported CSV file ... but I think this should happen by default anyway. Any ideas on this?
Thanks,
alan_the_geek.
How do I get a report or list of user mailboxes and the size of the mailbox.
Simple windows form with a combobox and radio
Hi,
Sorry, but i'm newbie in PS and my english so bad(
I try create a simple windows form with a combobox and radio for easy select credentials and connect to MS online services.
It must import from csv Username and pass, after it i'm select param(from radio) to connect, username(from combobox) and after click button must be running powershell console.
Sorry for my bad english(
CSV file like:
Username,Password
user1@test.onmicrosoft.com,13456
user2@1111.onmicrosoft.com,654321
Script:
Add-Type -assembly System.Windows.Forms $main_form = New-Object System.Windows.Forms.Form $main_form.Text ='Connect' $main_form.Width = 100 $main_form.Height = 100 $main_form.AutoSize = $true $main_form.TopMost = $true $Label = New-Object System.Windows.Forms.Label $Label.Text = "Select service:" $Label.Location = New-Object System.Drawing.Point(10,10) $Label.AutoSize = $true $main_form.Controls.Add($Label) $RadioButton = New-Object System.Windows.Forms.RadioButton $RadioButton.Location = New-Object System.Drawing.Point(10,30) $RadioButton.Text = 'MSO' $RadioButton.AutoSize = $true $main_form.Controls.Add($RadioButton) $RadioButton1 = New-Object System.Windows.Forms.RadioButton $RadioButton1.Location = New-Object System.Drawing.Point(10,50) $RadioButton1.Text = 'Azure' $RadioButton1.AutoSize = $true $main_form.Controls.Add($RadioButton1) $ComboBox = New-Object System.Windows.Forms.ComboBox $ComboBox.DropDownStyle = [System.Windows.Forms.ComboBoxStyle]::DropDownList $ComboBox.DataSource = @{} import-csv C:\Users.csv -delimiter "," | ForEach-Object { $ComboBox.Items.Add($_.username) $ComboBox.DataSource.Add($_.username,$_.pass) } $ComboBox.Location = New-Object System.Drawing.Point(10,80) $ComboBox.Width = 200 $main_form.Controls.Add($ComboBox) $button = New-Object System.Windows.Forms.Button $button.Text = 'Connect' $button.Location = New-Object System.Drawing.Point(70,120) $main_form.Controls.Add($button) $button.Add_Click({ $x = import-csv C:\azure\moduls\Login\cred\Users.csv -delimiter "," | ? { $_.username -eq $combobox.Text } | Select -first 1 $sel = $ComboBox.SelectedItem.ToString(); $main_form.Close() }) $main_form.ShowDialog()
Using C# to run PowerShell command to create VirtualDirectory fails
I can run these commands with no problem directly in PowerShell. But trying to get C# to run them, I receive errors.
md d:\ftproot\vdir\test20140317A; New-WebVirtualDirectory -Site "[site]/[a virt directory]" -Name test20140317A -physicalPath d:\ftproot\vdir\test20140317A;
When running in c# through two different means, I receive these errors
Exception:Caught: "A parameter cannot be found that matches parameter name 'physicalPath'." (System.Management.Automation.CmdletInvocationException) A System.Management.Automation.CmdletInvocationException was caught: "A parameter cannot be found that matches parameter name 'physicalPath'." Though in Visual Studio , there's something called InteliTrace and it's showing a whole slew of exceptions starting with Exception:Thrown: "Unable to load DLL 'wldp.dll': The specified module could not be found. (Exception from HRESULT: 0x8007007E)" (System.DllNotFoundException) A System.DllNotFoundException was thrown: "Unable to load DLL 'wldp.dll': The specified module could not be found. (Exception from HRESULT: 0x8007007E)" Exception:Thrown: "Requested registry access is not allowed." (System.Security.SecurityException) A System.Security.SecurityException was thrown: "Requested registry access is not allowed." Exception:Thrown: "Cannot find path 'C:\Users\jpacella\Documents\WindowsPowerShell\Modules' because it does not exist." (System.Management.Automation.ItemNotFoundException) A System.Management.Automation.ItemNotFoundException was thrown: "Cannot find path 'C:\Users\jpacella\Documents\WindowsPowerShell\Modules' because it does not exist." Exception:Thrown: "Could not load file or assembly 'Microsoft.IIS.PowerShell.Framework' or one of its dependencies. The system cannot find the file specified." (System.IO.FileNotFoundException) A System.IO.FileNotFoundException was thrown: "Could not load file or assembly 'Microsoft.IIS.PowerShell.Framework' or one of its dependencies. The system cannot find the file specified." Exception:Thrown: "Cannot find path 'C:\Users\jpacella\Documents\WindowsPowerShell\Modules' because it does not exist." (System.Management.Automation.ItemNotFoundException) A System.Management.Automation.ItemNotFoundException was thrown: "Cannot find path 'C:\Users\jpacella\Documents\WindowsPowerShell\Modules' because it does not exist." Exception:Thrown: "Process should have elevated status to access IIS configuration data." (System.InvalidOperationException) A System.InvalidOperationException was thrown: "Process should have elevated status to access IIS configuration data." Exception:Thrown: "Object reference not set to an instance of an object." (System.NullReferenceException) A System.NullReferenceException was thrown: "Object reference not set to an instance of an object." Exception:Thrown: "Cannot find drive. A drive with the name 'IIS' does not exist." (System.Management.Automation.DriveNotFoundException) A System.Management.Automation.DriveNotFoundException was thrown: "Cannot find drive. A drive with the name 'IIS' does not exist." Exception:Thrown: "" (System.Management.Automation.ParameterBindingException) A System.Management.Automation.ParameterBindingException was thrown: "" Exception:Thrown: "The pipeline has been stopped." (System.Management.Automation.PipelineStoppedException) A System.Management.Automation.PipelineStoppedException was thrown: "The pipeline has been stopped." Exception:Thrown: "A parameter cannot be found that matches parameter name 'physicalPath'." (System.Management.Automation.CmdletInvocationException) A System.Management.Automation.CmdletInvocationException was thrown: "A parameter cannot be found that matches parameter name 'physicalPath'."
These are the two different ways I invoked the script
PowerShell ps = PowerShell.Create(); ps.AddCommand("New-Item") .AddParameter("Path", newPathName) .AddParameter("ItemType", "directory"); ps.AddStatement().AddCommand("New-WebVirtualDirectory") .AddParameter("Site", Properties.Settings.Default.VirtualDirectoryPath) .AddParameter("Name", userName) .AddParameter("physicalPath", newPathName); ps.Invoke();
and (scriptContents is a string holding the
Runspace runspace = RunspaceFactory.CreateRunspace(); runspace.Open(); Pipeline pipeline = runspace.CreatePipeline(); pipeline.Commands.AddScript(scriptContents); pipeline.Commands.Add("Out-String"); Collection<PSObject> results = pipeline.Invoke(); runspace.Close();
Getting exception in executing Open method of System.Management.Automation.Runspaces
Hi,
I am getting exception in executing Open method of System.Management. Automation.Runspaces when connecting to remote server. The exception which we get is given below:-
Connecting to remote server AU00001GSC01 failed with the following error message : WinRM cannot process the request. The following error with errorcode 0x8009030e occurred while using Kerberos authentication: A specified logon session does not exist. It may already have been terminated. Possible causes are: -The user name or password specified are invalid. -Kerberos is used when no authentication method and no user name are specified. -Kerberos accepts domain user names, but not local user names. -The Service Principal Name (SPN) for the remote computer name and port does not exist. -The client and remote computers are in different domains and there is no trust between the two domains. After checking for the above issues, try the following: -Check the Event Viewer for events related to authentication. -Change the authentication method; add the destination computer to the WinRM TrustedHosts configuration setting or use HTTPS transport. Note that computers in the TrustedHosts list might not be authenticated. -For more information about WinRM configuration, run the following command: winrm help config. For more information, see the about_Remote_Troubleshooting Help topic.Code snippet which is giving exception is pasted below:-
public static System.Collections.ObjectModel.Collection<PSObject> RunCmdlet(string commandName, string remoteServer, params CommandParameter[] parameters) { WSManConnectionInfo connectionInfo = new WSManConnectionInfo(false, remoteServer, 0, null, null, null); using (Runspace runSpace = RunspaceFactory.CreateRunspace(connectionInfo)) { runSpace.Open(); LoadWmsCmdlets(runSpace); return RunCmdlet(runSpace, commandName, parameters); } }In the above code we are trying to run the powershell command on a remote server on the same domain.
Powershell - Check Windows Service is started or not started
Hi all,
I am new to powershell and I am looking to write a script that will check if a service is not started and will start the service and if it is started will confirm that it is started in a log and or display. I found a script online that seems to be working, it will start the service if it is not equal to started. However I can't get it to confirm that if it is already started to display this (and not sure how exactly to input into log yet)
I am experimenting with the telnet service on a windows 2008 server
See below copy of script, no matter if the service is started or not it will display the same text that "service is now started" etc. Is there a better way of doing this as i can't seem to get mutiple if statements working?
Thank you for your help
function FuncCheckService{
param($ServiceName)
$arrService = Get-Service -Name $ServiceName
if ($arrService.Status -ne "Started"){
Start-Service $ServiceName
Write-Host "Starting " $ServiceName " service"
" ---------------------- "
" Service is now started"
}
if ($arrService.Status -eq "started"){
Write-Host $ServiceName " service is already started"
}
}
FuncCheckService -ServiceName "Telnet"
Comparing two arrays
Hi Team,
I have two arrays as mentioned below
Array1 Array2
John Mike
Mark Paul
Bill
John
Mark
I need to compare this two arrays and after comparison, Array2 should have only values which are present in Array1. All other values in Array2 should be deleted.
Say, after comparison, Array2 should have only John and Mark and other values should be deleted. Please suggest!!
Cheers
Jim
How do i filter the results of get-aduser to only match numerical values
Admittedly i am fairly new to powershell but this is proving more complicated than it needs to be. I have been asked to export all users from AD and then filter out any user with an employee id that is not the standard form of 6 numbers. I have tried to output all users using the following one liner which gives me all the data including non standard employee ids
get-aduser-filter {employeeid-like"*"-andmail -like"*" } -Propertiesdistinguishedname,mail,employeeid|Select-Objectemployeeid,mail, distinguishedname
i now need to whittle that down to only employee ids that are 6 numbers in length and exclude all characters. I have tried using match instead of like to filter but it seems that is not allowed.
Thanks
AD groups to excel
Sorry if this is the wrong area cant find where it may go.i have many AD groups and have been asked what folders they apply to huuuuge job
to help I have a command that will tell me some details of the AD groups so I know what they was created and last used.
I want to push this out to an excel file but I can t make it work I never use PS please help.
here is what I am using the command to pull the details form AD works great it is jus the pushing to to excel that's the issue:
PS C:\Windows> Get-ADGroup -filter {ObjectClass -eq "group"} -Properties * -searchbase "OU=EU,DC=main,DC=intgin,DC=net"
| FT name, whencreated, GroupCategory, whenchanged ¦ Get-Process | Export-Csv c:\ADGroupDetails.txt