unable to export from powershell to CSV [duplicate] - powershell

This question already has answers here:
Writing console output to a file - file is unexpectedly empty
(2 answers)
Closed 3 years ago.
Pls help a poor newby over here...below is my script with the errors at the bottom of the script. The main issue is that i am unable to export to CSV
PS C:\Users\LUPUWANA> $logs = get-eventlog system -ComputerName cafeserver -source Microsoft-Windows-Winlogon -After (Get-Date).AddDays(-7);
$res = #(); ForEach ($log in $logs) {if($log.instanceid -eq 7001) {$type = "Logon"} Elseif ($log.instanceid -eq 7002){$type="Logoff"} Else {Continue} $res += New-Object PSObject -Property #{Time = $log.TimeWritten; "Event" = $type; User = (New-Object System.Security.Principal.SecurityIdentifier $Log.ReplacementStrings[1]).Translate([System.Security.Principal.NTAccount])}};
Export-Csv -Path C:\users\lupuwana\desktop\events.csv
oss get-help -detailed
Supply values for the following parameters:
InputObject:
oss : Cannot process argument transformation on parameter 'Width'. Cannot convert value "get-help" to type "System.Int32". Error: "Input string was not in a
correct format."
At line:4 char:5
+ oss get-help -detailed
+ CategoryInfo : InvalidData: (:) [oss], ParameterBindingArgumentTransformationException
+ FullyQualifiedErrorId : ParameterArgumentTransformationError,oss

Your loop builds an object called $res, so assuming that's the object you wish to export to CSV, you need to supply that object to the Export-Csv Cmdlet:
Export-Csv -InputObject $res -Path C:\users\lupuwana\desktop\events.csv
You may also wish to add the -NoTypeInformation option too otherwise your file will contain an extra header row describing the object type.

Related

update/modify ldap user attribute powershell

My powershell script will update the ldap user attribute for non-Microsoft technology(Active Directory) and i faced some issue on it. This is my reference link for how to update non-Microsoft technology(Active Directory)
This is part of my powershell script
if($time -ne $null)
{
$eD = $time.AddDays(7)
write-host "The date after : "$eD
Set-ADUser xxxxx -AccountExpirationDate $eD
$a = New-Object "System.DirectoryServices.Protocols.DirectoryAttributeModification"
write-host $a
$a.Name = "String1"
write-host $a
$a.Operation = [System.DirectoryServices.Protocols.DirectoryAttributeOperation]::Add
write-host $a
#add values of the attribute
$a.Add("set")
write-host $a
$r.Modifications.Add($a)
$re = $ldapserver.SendRequest($r);
if ($re.ResultCode -ne [System.directoryServices.Protocols.ResultCode]::Success)
{
write-host "Failed!"
write-host ("ResultCode: " + $re.ResultCode)
write-host ("Message: " + $re.ErrorMessage)
}
}
Here are my script output
The date after 7 days : 14/1/2020 11:40:03 AM
0
set
You cannot call a method on a null-valued expression.
At D:\deployment\test_ck.ps1:94 char:25
+ $r.Modifications.Add($a)
+ ~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
i cant figure out why $a is having a null value
This is what assigned to $r
$Domain='ou=test,ou=tes1,o=test2'
$fDomain ='(objectClass=User)'
$sDomain = New-Object System.DirectoryServices.Protocols.SearchRequest -ArgumentList $Domain,$fDomain,
$r = (new-object "System.DirectoryServices.Protocols.ModifyRequest")
$r = $sDomain
The simple PowerShell script below uses the Get-ADUser cmdlet from the ActiveDirectory PowerShell module to retrieve all the users in one OU and then iterate the users to set a couple of AD properties.
# Get all users in the Finance OU.
$FinanceUsers = Get-ADUser -Filter * -SearchBase "OU=Finance,OU=UserAccounts,DC=FABRIKAM,DC=COM"
# Iterate the users and update the department and title attributes in AD.
The example uses the Instance parameter of Set-ADUser to update each user in the OU. The parameter allows any modifications made to the ADUser object to go to the corresponding Active Directory object while only updating object properties that have changed.

PowerShell Error: New-Object : Cannot find an overload for "PlatformParameters" and the argument count: "1"

I am trying to automatically upload a CSV into PowerBi using the Git repository PowerBIPS. I can't seem to get past this error:
New-Object : Cannot find an overload for "PlatformParameters" and the argument count: "1".
With the help of the article linked here (https://powerbi.microsoft.com/en-us/blog/using-a-power-bi-app-to-upload-csv-files-to-a-dataset/), I believe I have found a viable solution to solve this. However, I am running into an error I can't seem to figure out.
I have customized the code from the original article to fit my current situation (outlined in the code below). I am able to run the code up until the "send data to PowerBi comment" where this error is raised.
I have tried referencing the Git documentation to help with this issue, but have found no luck. I have a feeling it has to do with the authentication piece of connecting to PowerBi.
while ($true) {
# Iterate each CSV file and send to PowerBI
Get-ChildItem "$currentPath\CSVData" -Filter "*.csv" | % {
$file = $_
#Import csv and add column with filename
$data = Import-Csv $file.FullName |
select #{Label="File";Expression={$file.Name}}, *
# Send data to PowerBI
$data | Out-PowerBI -DataSetName "CSVSales" -TableName "Sales" -Types #{
"Sales.OrderDate" = "datetime";
"Sales.SalesAmount" = "double";
"Sales.Freight" = "double"
} -BatchSize 300 -Verbose
# Archive the file
Move-Item $file.FullName "$currentPath\CSVData\Archive\" -Force
}
Write-Output "Sleeping..."
Sleep -Seconds 5
}
VERBOSE: Getting the Authentication Token
VERBOSE: Using default authentication flow
New-Object : Cannot find an overload for "PlatformParameters" and the argument
count: "1".
At C:\Program Files\WindowsPowerShell\Modules\PowerBIPS\2.0.3.1\PowerBIPS.psm1:299 char:16
+ ... pltParams = New-Object Microsoft.IdentityModel.Clients.ActiveDirector ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [New-Object], MethodException
+ FullyQualifiedErrorId : ConstructorInvokedThrowException,Microsoft.PowerShell.Commands.NewObjectCommand

Tcp-NetConnection is Failing with Error "Cannot convert value to type System.String"

I am using the below Code to get the content and test it using TCP-netconnection in Powershell. But, I am getting an Error like below.
Test-NetConnection : Cannot process argument transformation on parameter 'ComputerName'. Cannot convert value to type System.String. At line:2 char:34
+ Test-NetConnection -ComputerName $Name -Port 445
+ ~~~~~
+ CategoryInfo : InvalidData: (:) [Test-NetConnection], ParameterBindingArgumentTransformationException
+ FullyQualifiedErrorId : ParameterArgumentTransformationError,Test-NetConnection
Below is script command that I have used.
$Name = Get-Content "C:\Users\vishnuvardhan.chapal\Documents\Test File.txt"
Test-NetConnection -ComputerName $Name -Port 445
Does anyone have an idea on, "How to Convert read data into a string"?
Your $name variable potentially has an array of computer names stored in it. The computername parameter only accepts one string. You will need to loop through your computer names like the following:
$Name = Get-Content "C:\Users\vishnuvardhan.chapal\Documents\Test File.txt"
$name | foreach-object {test-netconnection -computername $_ -port 445}
Your test file.txt file needs to have only computer names in it. They need to be one computer name per line format.

PowerShell: cannot convert type SMO.server to type SMO.server

Error I'm getting from PowerShell:
Cannot convert argument "srv", with value: "[DBADEV\SQL2008r2]", for "SqlBackup" to type "Microsoft.SqlServer.Management.Smo.Server": "Cannot convert the "[DBADEV\SQL2008r2]" value of type
"Microsoft.SqlServer.Management.Smo.Server" to type "Microsoft.SqlServer.Management.Smo.Server"."
At line:23 char:1
+ $backup.SqlBackup($srv)
+ ~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], ParentContainsErrorRecordException
+ FullyQualifiedErrorId : MethodArgumentConversionInvalidCastArgument
I'm attempting to write a PowerShell script to restore a database from our Production box and into our DBADEV box. Below is the code I'm using which is then producing the error.
#Clear Screen
cls
#load assemblies
[System.Reflection.Assembly]::LoadWithPartialName('Microsoft.SqlServer.SMO') | out-null
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.SmoExtended") | Out-Null
$ErrorActionPreference = "Inquire"
# Restore [SQLSRV2k8-0102\SQL2008] instance
$BackupFile = Get-ChildItem "\\NetworkShare\r`$\MSSQL10.SQL2008\MSSQL\Backup\AdventureWorks2008r2" | select -Last 1
$BackupFile
$srv = New-Object Microsoft.SqlServer.Management.Smo.Server("DBADEV\SQL2008r2")
$res = New-Object Microsoft.SqlServer.Management.Smo.Restore
$backup = New-Object Microsoft.SqlServer.Management.Smo.Backup
$Backup.Devices.AddDevice($BackupFile, [Microsoft.SqlServer.Management.Smo.DeviceType]::File)
$Backup.Database = "AdventureWorks2008r2"
$Backup.Action = [Microsoft.SqlServer.Management.Smo.BackupActionType]::Database
$backup.Initialize = $true
$backup.SqlBackup($srv)
$srv.Databases["AdventureWorks2008r2"].Drop()
$res.Devices.AddDevice($BackupFile, [Microsoft.SqlServer.Management.Smo.DeviceType]::File)
$res.Database = "AdventureWorks2008r2"
$res.NoRecovery = $true
$res.SqlRestore($srv)
The error seems a bit cryptic to me (as do most PowerShell errors). Any thoughts on why this is occurring? I'm also getting the error when I use Mike Fal's powershell script here: http://www.mikefal.net/2014/07/22/restoreautomation-powershell-module/
The one thing that seems to get me past this error is by passing "DBADEV\SQL2008r2" directly into SQLRestore,
i.e. $res.SqlRestore("DBADEV\SQL2008r2") instead of $res.SqlRestore($srv)
This now generate an error stating "Restore failed for Server 'DBADEV\SQL2008r2'
Well from my experiences this kind of errors appear because of wrong name/data type in variable.
I would try to escape \ in "DBADEV\SQL2008r2"
or try what I found on MSDN
$srv = new-Object Microsoft.SqlServer.Management.Smo.Server("(local)")
Write-Host $srv.Information.Version
so it could look like
New-Object Microsoft.SqlServer.Management.Smo.Server("(DBADEV\SQL2008r2)")

how to add data from a file to an open variable in powershell

I am trying to add an open varible to this command so when the data pulls from line 24 it adds it to the variable and makes it executable.
$data = Get-Content "C:\Users\bgriffiths\Documents\test.dat"
$data[24]
I have tried adding different formats to do this and nothing seems to work.
one command i tried was
invoke-command sql -query = $data
I get an error telling me
Invoke-Command : A parameter cannot be found that matches parameter name 'query'.
At line:4 char:26
+ invoke-command sql -query <<<< = $data
+ CategoryInfo : InvalidArgument: (:) [Invoke-Command], ParameterBindingException
+ FullyQualifiedErrorId : NamedParameterNotFound,Microsoft.PowerShell.Commands.InvokeCommandCommand
another command I have been trying to run is
$Command.CommandType.text = $data
the only error I get from this is
Property 'text' cannot be found on this object; make sure it exists and is settable.
At line:10 char:30
+ $Command.CommandType. <<<< text = $data
+ CategoryInfo : InvalidOperation: (text:String) [], RuntimeException
+ FullyQualifiedErrorId : PropertyNotFound
I am at a lost on how to import file data into the script and have it run it.
I figured out how to run commands for sql through my powershell I had to actaully import the assembly list for the sql ps and then I was able to run the Invoke-SqlCmd
the script to add the information for sqlps to your windows ps is -
$ErrorActionPreference = "Stop"
$sqlpsreg="HKLM:\SOFTWARE\Microsoft\PowerShell\1\ShellIds\Microsoft.SqlServer.Management.PowerShell.sqlps"
if (Get-ChildItem $sqlpsreg -ErrorAction "SilentlyContinue")
{
throw "SQL Server Powershell is not installed."
}
else
{
$item = Get-ItemProperty $sqlpsreg
$sqlpsPath = [System.IO.Path]::GetDirectoryName($item.Path)
}
#
# Preload the assemblies. Note that most assemblies will be loaded when the provider
# is used. if you work only within the provider this may not be needed. It will reduce
# the shell's footprint if you leave these out.
#
$assemblylist =
"Microsoft.SqlServer.Smo",
"Microsoft.SqlServer.Dmf ",
"Microsoft.SqlServer.SqlWmiManagement ",
"Microsoft.SqlServer.ConnectionInfo ",
"Microsoft.SqlServer.SmoExtended ",
"Microsoft.SqlServer.Management.RegisteredServers ",
"Microsoft.SqlServer.Management.Sdk.Sfc ",
"Microsoft.SqlServer.SqlEnum ",
"Microsoft.SqlServer.RegSvrEnum ",
"Microsoft.SqlServer.WmiEnum ",
"Microsoft.SqlServer.ServiceBrokerEnum ",
"Microsoft.SqlServer.ConnectionInfoExtended ",
"Microsoft.SqlServer.Management.Collector ",
"Microsoft.SqlServer.Management.CollectorEnum"
foreach ($asm in $assemblylist)
{
$asm = [Reflection.Assembly]::LoadWithPartialName($asm)
}
#
# Set variables that the provider expects (mandatory for the SQL provider)
#
Set-Variable -scope Global -name SqlServerMaximumChildItems -Value 0
Set-Variable -scope Global -name SqlServerConnectionTimeout -Value 30
Set-Variable -scope Global -name SqlServerIncludeSystemObjects -Value $false
Set-Variable -scope Global -name SqlServerMaximumTabCompletion -Value 1000
#
# Load the snapins, type data, format data
#
Push-Location
cd $sqlpsPath
Add-PSSnapin SqlServerCmdletSnapin100
Add-PSSnapin SqlServerProviderSnapin100
Update-TypeData -PrependPath SQLProvider.Types.ps1xml
update-FormatData -prependpath SQLProvider.Format.ps1xml
Pop-Location
Write-Host -ForegroundColor Yellow 'SQL Server Powershell extensions are loaded.'
Write-Host
Write-Host -ForegroundColor Yellow 'Type "cd SQLSERVER:\" to step into the provider.'
Write-Host
Write-Host -ForegroundColor Yellow 'For more information, type "help SQLServer".'
the link where I found this is http://blogs.msdn.com/b/mwories/archive/2008/06/14/sql2008_5f00_powershell.aspx