I have a list of device names exported to an csv file.
I need to import this csv to then query the data and export the objectid of these computers from azure.
I am using the below and the error I am receiving is beneath
Can anyone point me in the right direction?
$test3 = import-csv -path "C:\temp\test3.xml"
Get-MsolDevice -Name $test3.Name | Select-Object -Property ObjectID | Export-CSV -Path "C:\temp\test9.xml"**
Get-MsolDevice : Cannot convert 'System.Object[]' to the type 'System.String' required by parameter 'Name'. Specified method is not supported.
At line:1 char:22
+ Get-MsolDevice -Name $test3.Name | Select-Object -Property ObjectID | ...
+ ~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Get-MsolDevice], ParameterBindingException
+ FullyQualifiedErrorId : CannotConvertArgument,Microsoft.Online.Administration.Automation.GetDevice
$test3.Name is going to return a collection of strings if there is more than one row in the CSV. You'll need to iterate over each like so:
$objectIds = $test3.Name | Foreach-Object {
Get-MsolDevice -Name $_ |
Select-Object -Property ObjectID
}
$objectIds | Export-Csv -Path "C:\temp\test9.xml" -NoTypeInformation
Related
below is the code I am using to find duplicates in a CSV and total them up.
I cant figure out how to Export-CSV correctly
the code below shows what I need in the terminal window
any help would be much appreciated
Import-Csv (Get-ChildItem "E:\Bill3\output.csv") |
Group-Object -Property Code |
Select-Object -Property #{Name='Code';Expression={$_.Name}},
#{Name='Quantity';Expression={
($_.Group| Measure-Object -Sum -Property Quantity ).Sum
}
}
this is how the terminal looks, this is what i would like my exported csv to look like
You can do the following:
Import-Csv (Get-ChildItem "E:\Bill3\output.csv") |
Group-Object -Property Code |
Select-Object -Property #{Name='Code';Expression={$_.Name}},
#{Name='Quantity';Expression={
($_.Group| Measure-Object -Sum -Property Quantity ).Sum
}
} | Export-Csv file.csv -NoType
an empty pipeline element is not allowed
The reason you received the error message above is because of syntax issues with line continuation. The closing } does not continue the line. Therefore, you cannot add your | Export-Csv command on the next line following the last }. They must be on the same line. You can simply run the following code to generate your same error:
PS > | export-csv o.csv
At line:1 char:1
+ | export-csv o.csv
+ ~
An empty pipe element is not allowed.
+ CategoryInfo : ParserError: (:) [], ParentContainsErrorRecordException
+ FullyQualifiedErrorId : EmptyPipeElement
See Natural Line Continuators for an explanation on line continuation.
So I am trying to pipe in a file list into import CSV:
ls *.csv | select FullName | where FullName -NotMatch "fixed" | ForEach-Object {
Import-Csv -Path %($_.FullName) -Delimiter ";"
}
But I am getting this error:
Import-Csv : A positional parameter cannot be found that accepts argument
'C:\***\Documents\Daraz Order\order.list.export 2019-11-13.csv'.
At line:2 char:1
+ Import-Csv -Path %($_.FullName) -Delimiter ";"
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Import-Csv], ParameterBindingException
+ FullyQualifiedErrorId : PositionalParameterNotFound,Microsoft.PowerShell.Commands.ImportCsvCommand
It gives the same error for all the files in the list. I have tried the ToString() method. But the error persist:
+ Import-Csv -Path %($_.FullName.ToString()) -Delimiter ";"
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Import-Csv], ParameterBindingException
+ FullyQualifiedErrorId : PositionalParameterNotFound,Microsoft.PowerShell.Commands.ImportCsvCommand
What might be causing this?
The answer Patrick gave you is correct. However you still get the error. You should try different methods of troubleshooting (using Powershell_ISE obviously).
$import = #()
ls *.csv| select FullName | where FullName -NotMatch "fixed" | foreach-object {
$path = $_.FullName
$path.GetType()
$path
try{
Get-Content -Path $path
}catch{
Write-Host "Path does not exist"
}
$import += Import-Csv -path $path -delimiter ";"
}
In the above example, to make sure we don't get distracted, we put all the content in the import array. Next look at the path, does it exist? Can you obtain the content of the file? Let's look at the type of the file by trying .GetType().
The error basically says that Import-CSV does not except your argument. So try fixing Import-CSV with a valid path to see if you get it to work first.
PS: Your script does actually work on my system (PowerShell 5.1).
It seems some idiosyncrasy of PowerShell 6. I just decided to use a code block and just pipes. The code that worked for me was:
ls *.csv| select FullName,BaseName | where FullName -NotMatch "fixed"| foreach {
$file = $_.FullName.ToString()
$bname = $_.BaseName.ToString()
$bnamepath = ".\$bname-fixed.csv"
Import-Csv $file -Delimiter ';' | Export-Csv $bnamepath -Delimiter ','
}
I still had to do a pipe at the end because keeping the data in a variable causes the output file just have the object properties and not the values of the other CSV. This script will work if you wan to process the files in Excel without changing your system's locale.
I'm currently working on a script to import 2 csv files, compare the fqdn columns and output the results to a file.
The issue is after many hours of testing I'm at the point that it looks like my script is working up until the point of getting the path for each file that needs to be imported but I can't seem to get the import-csv command to do what I need it to.
I'd appreciate any guidance you can provide.
My script so far and the error I'm getting are below:
$CMDB_Installed = Get-ChildItem -Path C:\Users\nha1\Desktop\Reports\CMDBInstall | Sort CreationTime -Descending | Select -expa FullName -First 1 | Out-String
$SCOM_AgentList = Get-ChildItem -Path C:\Users\nha1\Desktop\Reports\SCOMUAT | Sort CreationTime -Descending | Select -expa FullName -First 1 | Out-String
$SL = Import-Csv $SCOM_AgentList
$CL = Import-Csv $CMDB_Installed
Compare-Object -ReferenceObject $CL -DifferenceObject $SL -Property fqdn |
Export-Csv -NoTypeInformation -Path = C:\Users\nha1\Desktop\Reports\AuditOutput\UATNeedsAgent+SCOM\UATHosts-NotinSCOM$(get-date -format yyyy-MM-dd).csv
Error Message:
import-csv : Illegal characters in path.
At line:4 char:7
+ $SL = import-csv $SCOM_AgentList
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : OpenError: (:) [Import-Csv], ArgumentException
+ FullyQualifiedErrorId : FileOpenFailure,Microsoft.PowerShell.Commands.ImportCsvCommand
import-csv : Illegal characters in path.
At line:5 char:7
+ $CL = import-csv $CMDB_Installed
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : OpenError: (:) [Import-Csv], ArgumentException
+ FullyQualifiedErrorId : FileOpenFailure,Microsoft.PowerShell.Commands.ImportCsvCommand
$CMDB_Installed = ... | Select -expa FullName -First 1 | Out-String
Don't use Out-String, unless you want a for-display, multi-line string representation.
Your file-path variables therefore contain newlines (line breaks), which Import-Csv complains about, given that newlines in file names are illegal in NTFS (on Windows).
Simply omit the Out-String call, given that Select -expa FullName -First 1 by definition already outputs a string (given that the .FullName property on the objects output by Get-ChildItem is [string]-typed).
To recreate the problem:
PS> Import-Csv "foo`n" # illegal line break in file path
Import-Csv : Illegal characters in path.
To demonstrate that Out-String produces a multi-line string even with a single-line string as input:
PS> ('foo' | Out-String).EndsWith("`n")
True
I am trying to delete contents of few folders.
What I have:
$Config = #{
InstallPath = 'C:\Program Files\App'
SubPaths = #('www\app1', 'www\app2', 'www\app3')
}
And here is the code to get contents:
$Config.SubPaths | Select-Object { Join-Path $Config.InstallPath $_ } | Get-ChildItem
But it doesn't work, because Get-ChildItem receives object like below:
#{ Join-Path $Config.InstallPath $_ =C:\Program Files\App\www\app1}
Error:
Get-ChildItem : Cannot find drive. A drive with the name '#{ Join-Path $Config.InstallPath $_ =C' does not exist.
At line:1 char:85
+ ... elect-Object { Join-Path $Config.InstallPath $_ } | Get-ChildItem
+ ~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (#{ Join-Path $C...stallPath $_ =D:String) [Get-ChildItem], DriveNotFoun
dException
+ FullyQualifiedErrorId : DriveNotFound,Microsoft.PowerShell.Commands.GetChildItemCommand
How can I convert result of Select-Object to simple array of strings? Or any other approach to make code better?
The results you are getting are because you made a new object with the the literal property Join-Path $Config.InstallPath $_. Instead...
$Config.SubPaths | ForEach-Object { Join-Path $Config.InstallPath $_ } | Get-ChildItem
You are not trying to select a property of a single subpath but generate a string from each of the SubPaths. Using Foreach-object instead to iterate over the collection should get you the results you are looking for.
While you could create custom objects and properties using calculated properties I figure this is not the direction you are going for. But to answer the question in the title you could have done this:
$Config.SubPaths |
Select-Object #{Name="Path";Expression={Join-Path $Config.InstallPath $_}} |
Get-ChildItem
Get-ChildItem should bind to the path property of the new object were are making
I have been working on a PowerShell script for the better part of well a week or two. I've been able to get some parts of it working however I'm unable to fully get this automated.
I deal with a lot of CSV files on a daily basis, I have been tasked with uploading them into our software however sometimes they're too large to handle so I break them down based upon their "type" (it's a column in the CSV) and I export it to a single CSV per "type". I've been able to accomplish this with the following:
$file = gci -Filter "*.csv";
Import-Csv $file `
| Group-Object –Property “type” `
| Foreach-Object `
{
$path=$_.name+”.csv” ; $_.group `
| Export-Csv –Path $path –NoTypeInformation
}
So this works wonderfully, for each individual CSV. Unfortunately I don't have the time to do this for each individual CSV. Now I come to my other PowerShell script:
get-childitem -Filter "*.csv" `
| select-object basename `
| foreach-object{ $path=$_.basename+".csv" #iterate through files.
if(!(Test-Path -path $_.basename)) #If the folder of the file can't be found then it will attempt to create it.
{
New-Item $_.basename -type directory; $file=$_.basename+".csv";
Import-Csv $file `
| Group-Object -Property "Type" `
| Foreach-Object {
$path=$_.name+".csv"; $_.group `
| `
if(!(Test-Path -path $path2))
{
New-Item $path2 -type directory
Export-Csv -Path $path2 + "\" + $path -NoTypeInformation
}
else
{
"Failed on: " + $_.basename
#Export-Csv -Path $_.basename + "\" + $path -NoTypeInformation
}
}
}
else
{
Import-Csv $path `
| Group-Object -Property "Type" `
| Foreach-Object {$path=$_.basename+".csv" ; $_.group
if(Test-Path -path $._)
{
New-Item $path2 -type directory
Export-Csv -Path $path2 + "\" + $path -NoTypeInformation
}
#else
#{
Write-Host "Failed on: $_.basename"
#Export-Csv -Path $_.basename + "\" + $path -NoTypeInformation
#}
}
}
}
I just can't wrap my head around "why" this isn't working effectively. I have two conditionals. Is there a folder for the CSV? If no create one. I have to have another one because one of the "types" contains a \ which errors out if I don't have the folder, so I automatically try to create it. When I run the script I get the Path is null.
The Error is:
The term ' ' is not recognized as the name of a cmdlet, function,
script file, or operable program. Check the spelling of the name, or
if a path was included, verify that the path is correct and try again.
At C:\Users\c.burkinshaw\foldermake.ps1:11 char:26
+ | ` <<<<
+ CategoryInfo : ObjectNotFound: ( :String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
Test-Path : Cannot bind argument to parameter 'Path' because it is null.
At C:\Users\c.burkinshaw\foldermake.ps1:12 char:45
+ if(!(Test-Path -path <<<< $path2))
+ CategoryInfo : InvalidData: (:) [Test-Path], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.TestPathCommand
Any help would be greatly appreciated, if you have questions please don't hesitate to ask.
You have not defined $path2 anywhere, so something like test-path -path $path2 will say path is null. And in one place you are using $._ which will again give errors.
Edit after question updated with error message:
Your error message also says the same
Test-Path : Cannot bind argument to parameter 'Path' because it is
null. At C:\Users\c.burkinshaw\foldermake.ps1:12 char:45
+ if(!(Test-Path -path <<<< $path2))
Also the other error is in:
$path=$_.name+".csv"; $_.group `
| `
what are you trying to do here with the $_.group?
It is not proper. You cannot do $_.group | and provide some if statement.
Other comments:
Why are using $_.basename and then appending .csv? You could have just used $_.name. Try to not use the select-object basename - I don't see the value.
Extract the common import-csv and export-csv part into a function.